package com.yihu.jw.hospital.prescription.service;


import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.dict.dao.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.area.BaseDrugStoreDO;
import com.yihu.jw.entity.base.dict.BaseJobCategoryDO;
import com.yihu.jw.entity.base.dict.DictDeptDescDO;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.org.BaseDoctorPatientFollowDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.base.words.BaseSensitiveDO;
import com.yihu.jw.entity.base.wx.*;
import com.yihu.jw.entity.base.yx.YxTokenMappingDO;
import com.yihu.jw.entity.hospital.consult.WlyyDoctorClinicRoomDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalWaitingRoomDO;
import com.yihu.jw.entity.hospital.dict.BaseJpushTemplateDO;
import com.yihu.jw.entity.hospital.dict.WlyyChargeDictDO;
import com.yihu.jw.entity.hospital.doctor.WlyyDoctorOnlineTimeDO;
import com.yihu.jw.entity.hospital.doctor.WlyyDoctorWorkTimeDO;
import com.yihu.jw.entity.hospital.doctor.WlyyPatientRegisterTimeDO;
import com.yihu.jw.entity.hospital.healthCare.YlzMedicalRelationDO;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.entity.ylzinfo.OauthYlzConfigDO;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.healthCare.service.HealthCareService;
import com.yihu.jw.hospital.consult.dao.BaseAdviceTreatmentDao;
import com.yihu.jw.hospital.consult.dao.HospitalWaitingRoomDao;
import com.yihu.jw.hospital.consult.dao.WlyyConsultAdviceDao;
import com.yihu.jw.hospital.dict.WlyyChargeDictDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.doctor.dao.DoctorWorkTimeDao;
import com.yihu.jw.hospital.doctor.dao.PatientRegisterTimeDao;
import com.yihu.jw.hospital.doctor.dao.WlyyDoctorOnlineTimeDao;
import com.yihu.jw.hospital.drugstore.dao.BaseDrugStoreDao;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.hospital.httplog.service.BaseOperateLogService;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.mapping.service.DoctorMappingService;
import com.yihu.jw.hospital.mapping.service.PatientMappingService;
import com.yihu.jw.hospital.message.dao.BaseBannerDoctorDao;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.prescription.dao.*;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.TnyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.YkyyEntranceService;
import com.yihu.jw.hospital.prescription.service.useragent.BaseUserAgent;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.order.BusinessOrderService;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.order.pay.ylz.YlzPayService;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BaseDoctorPatientFollowDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientMedicareCardDao;
import com.yihu.jw.restmodel.base.dict.DictHospitalDeptVO;
import com.yihu.jw.restmodel.base.org.BaseOrgVO;
import com.yihu.jw.restmodel.hospital.archive.ArchiveVO;
import com.yihu.jw.restmodel.hospital.consult.WlyyHospitalSysDictVO;
import com.yihu.jw.restmodel.hospital.doctor.WlyyDoctorWorkTimeVO;
import com.yihu.jw.restmodel.hospital.prescription.*;
import com.yihu.jw.restmodel.web.*;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.jw.sms.dao.BaseSmsTemplateDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.LatitudeUtils;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import com.yihu.jw.utils.*;
import com.yihu.jw.utils.Pkis.PKIService_PortType;
import com.yihu.jw.utils.Pkis.PKIService_ServiceLocator;
import com.yihu.jw.utils.encode.Base64;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.utils.sfutils.HttpClientUtils;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.dao.WxPushLogDao;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
import com.yihu.jw.wechat.enterprise.EnterpriseService;
import com.yihu.jw.wechat.service.BaseSensitiveFilterWordsService;
import com.yihu.jw.wechat.service.WxAccessTokenService;
import com.yihu.jw.yx.dao.YxTokenMappingDao;
import com.yihu.mysql.query.BaseJpaService;

import com.yihu.utils.security.MD5;
import com.ylzinfo.ehc.EhcHandler;
import com.ylzinfo.ehc.common.utils.DateUtils;
import com.ylzinfo.ehc.trans.TransRequest;
import com.ylzinfo.ehc.trans.TransResponse;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import jxl.write.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.Boolean;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by Trick on 2019/5/17.
 */
@Service
@Transactional
public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, PrescriptionDao> {

    private static final Logger logger = LoggerFactory.getLogger(PrescriptionService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BasePatientMedicareCardDao basePatientMedicareCardDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionExpressageDao prescriptionExpressageDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private HospitalWaitingRoomDao hospitalWaitingRoomDao;
    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private PatientMappingService patientMappingService;
    @Autowired
    private DoctorMappingService doctorMappingService;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private WlyyChargeDictDao wlyyChargeDictDao;
    @Autowired
    private WlyyHospitalSysDictDao sysDictDao;
    @Autowired
    private DoctorWorkTimeDao doctorWorkTimeDao;
    @Autowired
    private PatientRegisterTimeDao patientRegisterTimeDao;
    @Autowired
    private WlyyHttpLogDao wlyyHttpLogDao;
    @Autowired
    private WlyyDoctorClinicRoomDao wlyyDoctorClinicRoomDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private PrescriptionExpressageService sfexpressService;
    @Autowired
    private WlyyDoctorOnlineTimeDao wlyyDoctorOnlineTimeDao;
    @Autowired
    private OauthYlzConfigDao oauthYlzConfigDao;
    @Autowired
    private PatientRegisterDao patientRegisterDao;
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private WlyyInspectionDao wlyyInspectionDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemMessageService systemMessageService;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseDoctorPatientFollowDao baseOrgPatientDao;
    @Autowired
    private WlyyHospitalWorkRuleDao wlyyHospitalWorkRuleDao;
    @Autowired
    private BaseDoctorInfoService baseDoctorService;
    @Autowired
    private BusinessOrderDao businessOrderDao;
    @Autowired
    private YkyyEntranceService ykyyEntranceService;
    @Autowired
    private BusinessOrderService businessOrderService;
    @Autowired
    private YkyyService ykyyService;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private PrescriptionCheckDao prescriptionCheckDao;
    @Autowired
    private PrescriptionExpressageLogDao prescriptionExpressageLogDao;
    @Autowired
    private PrescriptionEmrDao prescriptionEmrDao;
    @Autowired
    private WlyyConsultAdviceDao wlyyConsultAdviceDao;
    @Autowired
    private BaseUserAgent userAgent;

    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private YlzPayService ylzPayService;
    @Autowired
    private PatientMappingDao patientMappingDao;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private BasePatientWechatDao patientWechatDao;
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WeixinMessagePushUtils weixinMessagePushUtils;
    @Autowired
    private BasePatientWechatDao basePatientWechatDao;
    @Autowired
    private WxPushLogDao wxPushLogDao;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;

    @Autowired
    private DictDeptDescDao dictDeptDescDao;

    @Autowired
    private BaseSensitiveFilterWordsService baseSensitiveFilterWordsService;
    @Autowired
    private BaseBannerDoctorDao baseBannerDoctorDao;
    @Autowired
    private BaseDrugStoreDao baseDrugStoreDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private PrescriptionSignDao prescriptionSignDao;
    @Autowired
    private PrescriptionDiagnosisDao  prescriptionDiagnosisDao;
    @Autowired
    private XzyyPrescriptionService xzyyPrescriptionService;

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private YxTokenMappingDao yxTokenMappingDao;
    @Autowired
    private BaseNatAppointmentDao baseNatAppointmentDao;
    @Autowired
    private PayInfoNoticeService payInfoNoticeService;
    @Autowired
    private BaseJobCategoryDao jobCategoryDao;
    @Autowired
    private BaseSmsTemplateDao smsTemplateDao;
    @Autowired
    private YkyySMSService ykyySMSService;
    @Autowired
    private TnyyEntranceService tnyyEntranceService;
    @Autowired
    private BaseJpushTemplateDao baseJpushTemplateDao;
    /*@Autowired
    HikariDataSource dataSource;*/
    @Autowired
    private BaseSensitiveDao baseSensitiveDao;
    @Autowired
    private BaseOperateLogService baseOperateLogService;
    @Autowired
    private BaseAdviceTreatmentDao baseAdviceTreatmentDao;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private TasyNatService tasyNatService;
    @Autowired
    private HealthCareService healthCareService;

    public static String entranceUrl = "http://172.16.100.240:10023/xzzx/";

    public static String entranceHealthCareUrl = "http://172.16.100.240:10023/healthCare/";

    @Value("${demo.flag}")
    private boolean demoFlag;
    @Value("${wechat.id}")
    private String wechatId;
    @Value("${wechat.flag}")
    private boolean flag;


    /**
     * 获取居民就诊记录接口
     *
     * @param patient
     * @param startTime
     * @param endTime
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public List<WlyyOutpatientVO> findOutpatientList(String patient, String startTime, String endTime, boolean demoFlag,String ksdm,String cardNo) throws Exception {
        logger.info("findOutpatientList patient:" + patient);
        String patNo = patientMappingService.findHisPatNoByPatient(patient,cardNo);
        if (StringUtils.isBlank(patNo)) {
            return null;
        }
        logger.info("findOutpatientList patNo " + patNo);
        List<WlyyOutpatientVO> wlyyOutpatientVOList  =  entranceService.BS30025(patNo, null, startTime, endTime, demoFlag,ksdm);
        if (StringUtils.isNoneBlank(ksdm)){
            if (!ksdm.equalsIgnoreCase("1500010")){
                List<WlyyOutpatientVO> wlyyOutpatientVOList1  =  entranceService.BS30025(patNo, null, startTime, endTime, demoFlag,"1500010");
                if (wlyyOutpatientVOList!=null&&wlyyOutpatientVOList.size()!=0){
                    if(wlyyOutpatientVOList1!=null&&wlyyOutpatientVOList1.size()!=0){
                        for (WlyyOutpatientVO wlyyOutpatientVO:wlyyOutpatientVOList1){
                            logger.info("==="+wlyyOutpatientVO);
                            if (wlyyOutpatientVO!=null){
                                wlyyOutpatientVOList.add(wlyyOutpatientVO);
                            }
                        }
                    }
                }else {
                    wlyyOutpatientVOList = new ArrayList<>();
                    wlyyOutpatientVOList = wlyyOutpatientVOList1;
                }
            }
        }
        return wlyyOutpatientVOList;
    }

    /**
     * 修改续方物流信息
     */
    public WlyyPrescriptionExpressageDO updPrescriptionExpressage(String id,Integer oneselfPickupFlg,String name,String mobile,String address
            ,String provinceCode,String provinceName,String cityCode,String cityName,String townCode,String townName
            ,String streetCode,String streetName){

        WlyyPrescriptionExpressageDO expressageDO = prescriptionExpressageDao.findOne(id);
        expressageDO.setOneselfPickupFlg(oneselfPickupFlg);
        if(oneselfPickupFlg == 0){
            //自取
            expressageDO.setName(name);
            expressageDO.setMobile(mobile);
            expressageDO.setAddress(address);
            expressageDO.setProvinceCode(provinceCode);
            expressageDO.setProvinceName(provinceName);
            expressageDO.setCityCode(cityCode);
            expressageDO.setCityName(cityName);
            expressageDO.setTownCode(townCode);
            expressageDO.setTownName(townName);
            expressageDO.setStreetCode(streetCode);
            expressageDO.setStreetName(streetName);
        }else{
            //快递
            expressageDO.setName(null);
            expressageDO.setMobile(null);
            expressageDO.setAddress(null);
            expressageDO.setProvinceCode(null);
            expressageDO.setProvinceName(null);
            expressageDO.setCityCode(null);
            expressageDO.setCityName(null);
            expressageDO.setTownCode(null);
            expressageDO.setTownName(null);
            expressageDO.setStreetCode(null);
            expressageDO.setStreetName(null);
        }
        prescriptionExpressageDao.save(expressageDO);
        return expressageDO;
    }

    /**
     * 查询单条门诊记录
     *
     * @param patient
     * @param conNo
     * @return
     */
    public WlyyOutpatientVO findOutpatientInfo(String patient, String conNo) throws Exception {
        logger.info("findOutpatientList patient:" + patient);
        /*String patNo = patientMappingService.findHisPatNoByPatient(patient);*/
        BasePatientDO patientDO = basePatientDao.findById(patient);
        if (patientDO==null){
            return null;
        }
        PatientMappingDO patientMappingDO = patientMappingDao.findByIdcardAndSource(patientDO.getIdcard(),"1");
        String patNo = "";
        if (patientMappingDO!=null){
            patNo = patientMappingDO.getMappingCode();
        }
        if (StringUtils.isBlank(patNo)) {
            return null;
        }
        logger.info("findOutpatientList patNo:" + patNo);
        List<WlyyOutpatientVO> list = entranceService.BS30025(patNo, conNo, null, null, demoFlag,null);

        if (list != null && list.size() > 0) {
            WlyyOutpatientVO outpatientVO = list.get(0);
            outpatientVO.setSex(patientDO.getSex() + "");
            outpatientVO.setBirthday(patientDO.getBirthday());
            outpatientVO.setIdcard(patientDO.getIdcard());
            return outpatientVO;
        }
        return null;
    }

    /**
     *
     */
    public List<WlyyPrescriptionVO> findOriginPrescriptionList(String registerSn, String patient, String realOrder, String admNo, boolean demoFlag) throws Exception {
        /*String patNo = patientMappingService.findHisPatNoByPatient(patient);*/
        BasePatientDO patientDO = basePatientDao.findById(patient);
        if (patientDO==null){
            return null;
        }
        PatientMappingDO patientMappingDO = patientMappingDao.findByIdcardAndSource(patientDO.getIdcard(),"1");
        String patNo = "";
        if (patientMappingDO!=null){
            patNo = patientMappingDO.getMappingCode();
        }
        if (StringUtils.isBlank(patNo)) {
            return null;
        }
        //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);
        List<WlyyPrescriptionVO> prescriptionVOS = entranceService.BS16017(registerSn, realOrder, patNo, admNo, demoFlag);
        for (WlyyPrescriptionVO prescriptionVO:prescriptionVOS){
            WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = readOutPatientXml(registerSn);//电子病历
            prescriptionVO.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO);
        }
        return prescriptionVOS;
    }

    /**
     * 获取单条处方记录
     *
     * @param registerSn
     * @param patient
     * @param admNo
     * @param realOrder
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public WlyyPrescriptionVO findOriginPrescription(String registerSn, String patient, String admNo, String realOrder, boolean demoFlag) throws Exception {
        /*String patNo = patientMappingService.findHisPatNoByPatient(patient);*/
        BasePatientDO patientDO = basePatientDao.findById(patient);
        if (patientDO==null){
            return null;
        }
        PatientMappingDO patientMappingDO = patientMappingDao.findByIdcardAndSource(patientDO.getIdcard(),"1");
        String patNo = "";
        if (patientMappingDO!=null){
            patNo = patientMappingDO.getMappingCode();
        }
        if (StringUtils.isBlank(patNo)) {
            return null;
        }
        List<WlyyPrescriptionVO> rs = entranceService.BS16017(registerSn, realOrder, patNo, admNo, demoFlag);
        if (rs != null && rs.size() > 0) {
            return rs.get(0);
        }
        return null;
    }

    /**
     * 获取复诊记录列表
     *
     * @param patient
     * @param status
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findReOutpatientList(String patient, Integer status, String startTime, String endTime,String outpatientType, Integer page, Integer size) {
        String totalSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.patient =:patient  ";
        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)) {
            totalSql += " AND o.create_time >=:createTime ";
            totalParams.put("createTime", DateUtil.strToDateLong(startTime + " 00:00:00"));
        }
        if (StringUtils.isNotBlank(endTime)) {
            totalSql += " AND o.create_time <=:endTime ";
            totalParams.put("endTime", DateUtil.strToDateLong(endTime + " 23:59:59"));

        }
        if (StringUtils.isNotBlank(outpatientType)){
            totalSql+=" AND o.outpatient_type = :outpatientType ";
            totalParams.put("outpatientType", outpatientType);
        }
       /* totalParams.add(patient);
        if(status!=null){
            totalSql +=  " AND o.status = ? ";
            totalParams.add(status);
        }
        if(StringUtils.isNotBlank(startTime)){
            totalSql += " AND create_time >= ? ";
            totalParams.add(DateUtil.strToDateLong(startTime+" 00:00:00"));
        }
        if(StringUtils.isNotBlank(endTime)){
            totalSql += " AND create_time <= ? ";
            totalParams.add(DateUtil.strToDateLong(endTime+" 23:59:59"));
        }*/
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql, totalParams);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        String condition = "";
        if ("xm_ykyy_wx".equals(wechatId)) {
            if (flag){
                condition = "date_format(o.register_date ,'%Y-%m-%d %H:%i:%S' ) AS registerDate,";
            }else {
                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 " +
                " o.id AS \"id\", " +
                " o.adm_no AS \"admNo\", " +
                " o.origin_adm_no AS \"originAdmNo\", " +
                " o.register_no AS \"registerNo\", " +
                " o.origin_register_no AS \"originRegisterNo\", " +
                " o.origin_con_no AS \"originConNo\"," +
                " o.con_no AS \"conNo\"," +
                " o.hospital AS \"hospital\"," +
                " o.hospital_name AS \"hospitalName\"," +
                " o.win_no AS \"winNo\"," +
                " o.type AS  \"type\"," +
                " o.outpatient_type AS  \"outpatientType\"," +
                " o.dept AS \"dept\", " +
                " o.dept_name AS \"deptName\", " +
                " o.patient AS \"patient\", " +
                " o.patient_name AS \"patientName\", " +
                " o.doctor AS \"doctor\", " +
                " o.doctor_name AS \"doctorName\", " +
                " o.idcard AS \"idcard\", " +
                " o.card_no AS \"cardNo\"," +
                " o.mjz AS \"mjz\", " +
                " o.icd10 AS \"icd10\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " o.adm_date AS \"admDate\", " +
                " o.con_date AS \"conDate\", " +
                " o.description AS \"description\", " +
                " o.disease_img AS \"diseaseImg\"," +
                " o.consumer as \"consumer\"," +
                " o.consumer_name as \"consumerName\"," +
                " o.consumer_mobile as \"consumerMobile\", "+
                " o.fee as \"fee\", ";
        if ("xm_ykyy_wx".equals(wechatId)) {
            if (flag){
                sql = sql + "date_format(o.create_time ,'%Y-%m-%d %H:%i:%S' ) AS createTime,";
            }else {
                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.pay_status as \"payStatus\"," +
                " o.his_status as \"hisStatus\"  " +
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.consumer =:patient ";
        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)) {
            sql += " AND o.create_time >=:createTime ";
            params.put("createTime", DateUtil.strToDateLong(startTime + " 00:00:00"));
        }
        if (StringUtils.isNotBlank(endTime)) {
            sql += " AND o.create_time <=:endTime ";
            params.put("endTime", DateUtil.strToDateLong(endTime + " 23:59:59"));

        }
        if (StringUtils.isNotBlank(outpatientType)){
            sql+=" AND o.outpatient_type = '"+outpatientType+"' ORDER BY o.create_time DESC ";
        }
        logger.info("sql="+sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params, page, size);
        for(Map<String, Object> map:list){
            String outpatientId = map.get("id").toString();
            String outPatientStatus = map.get("status")==null?"":map.get("status").toString();
            String consultSql = "select t.id as \"id\" from wlyy_consult t where t.relation_code ='"+outpatientId+"'";
            List<Map<String, Object>> consultList = hibenateUtils.createSQLQuery(consultSql);
            if (consultList!=null&&consultList.size()!=0){
                if (outPatientStatus.equalsIgnoreCase("0")&&consultList!=null&&consultList.size()>0&&null!=consultList.get(0).get("id")){
                    map.put("haveConsult","1");
                }else {
                    map.put("haveConsult","0");
                }
            }else {
                map.put("haveConsult","0");
            }
        }
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    /**
     * 获取单条复诊记录信息
     *
     * @param outpatientId
     * @return
     */
    public com.alibaba.fastjson.JSONObject findReOutpatientInfo(String outpatientId, String prescriptionId, String wxId) throws Exception {
        com.alibaba.fastjson.JSONObject rs = new com.alibaba.fastjson.JSONObject();

        //复诊信息
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        if("2".equalsIgnoreCase(outpatientDO.getOutpatientType())){
            String generalDept="";
            String generalDeptName="";
            String generalSex="";
            String generalJob="";
            String generalOrgName="";
            List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(outpatientDO.getGeneralDoctor());
            if(depts!=null&&depts.size()>0){
                generalDept=depts.get(0).getDeptCode();
                generalDeptName=depts.get(0).getDeptName();
                generalOrgName=depts.get(0).getOrgName();
            }
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(outpatientDO.getGeneralDoctor());
            if(baseDoctorDO!=null){
                generalJob=baseDoctorDO.getJobTitleName();
                generalSex= IdCardUtil.getSexForIdcard(baseDoctorDO.getIdcard());
                rs.put("generalName",baseDoctorDO.getName());
                rs.put("generalPhoto",baseDoctorDO.getPhoto());
            }
            rs.put("generalDept",generalDept);
            rs.put("generalDeptName",generalDeptName);
            rs.put("generalSex",generalSex);
            rs.put("generalJob",generalJob);
            rs.put("generalOrgName",generalOrgName);

        }
        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",outpatientDO.getOperator());
        rs.put("status",outpatientDO.getStatus());
        rs.put("fee",outpatientDO.getFee());
        rs.put("hisStatus",outpatientDO.getHisStatus());
        rs.put("icd10Name",outpatientDO.getIcd10Name());
        rs.put("createTime",DateUtil.dateToStrLong(outpatientDO.getCreateTime()));
        //居民详情
        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("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"));
        String hisPatient="";
        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(basePatientDO.getId());
        if(null!=patientMappingDO){
            hisPatient = patientMappingDO.getMappingCode();
        }
        rs.put("hisPatient",hisPatient);
        Long time = new Date().getTime() - outpatientDO.getCreateTime().getTime();
        rs.put("time", time);

        //获取处方信息
        List<WlyyPrescriptionDO> prescriptionDOs = null;
        if (StringUtils.isNotBlank(prescriptionId)) {
            prescriptionDOs = prescriptionDao.findById(prescriptionId);
        } else {
            prescriptionDOs = prescriptionDao.findByOutpatientId(outpatientId);
        }
        if (!"2".equalsIgnoreCase(outpatientDO.getOutpatientType())){
            List<WlyyPrescriptionVO> prescriptionVOs = new ArrayList<>();
            List<BusinessOrderDO> businessOrders = new ArrayList<>();
            BusinessOrderDO businessOrder = new BusinessOrderDO();
            if (prescriptionDOs != null && prescriptionDOs.size() > 0) {
                convertToModels(prescriptionDOs, prescriptionVOs, WlyyPrescriptionVO.class);
                for (WlyyPrescriptionVO vo : prescriptionVOs) {
                    List<WlyyPrescriptionCheckDO> prescriptionCheckDO = prescriptionCheckDao.findByPrescriptionId(vo.getId());
                    //疾病信息
                    vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                    if(null!=prescriptionCheckDO&&prescriptionCheckDO.size()>0){
                        vo.setDispUser(prescriptionCheckDO.get(0).getOperate());
                        vo.setDispUserName(prescriptionCheckDO.get(0).getOperateName());
                    }

                    //药品信息
                    List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                    System.out.println("=====PrescriptionId======"+vo.getId());
                    convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(), 1), infoVOs, WlyyPrescriptionInfoVO.class);
                    vo.setInfoVOs(infoVOs);

                    //检查检验信息
                    List<WlyyInspectionVO> inspectionVOs = new ArrayList<>();
                    vo.setInspectionVOs(convertToModels(wlyyInspectionDao.findByPrescriptionId(vo.getId(), 1), inspectionVOs, WlyyInspectionVO.class));

                    if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO1 = prescriptionEmrDao.findEmrByPrescriptionId(vo.getId());
                        if (wlyyPrescriptionEmrDO1 != null) {
                            vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO1);
                        } else {
                            WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = readOutPatientXml(outpatientDO.getOriginRegisterNo());
                            //电子病历
                            vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO);
                        }
                    } else if (wxId.equalsIgnoreCase("xm_xzzx_wx")) {
                        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO1 = prescriptionEmrDao.findEmrByPrescriptionId(vo.getId());
                        if (wlyyPrescriptionEmrDO1 != null) {
                            vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO1);
                        } else {
                            List<WlyyPrescriptionEmrDO> listEmr = xzzxEntranceService.selectHistoryEmr(hisPatient,"");
                            if (null!=listEmr&&listEmr.size()>0){
                                vo.setWlyyPrescriptionEmrDO(listEmr.get(0));
                            }
                        }
                    }else {
                        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO1 = prescriptionEmrDao.findEmrByPrescriptionId(vo.getId());
                        if (wlyyPrescriptionEmrDO1 != null) {
                            vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO1);
                        }
                    }
                    //支付信息
                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(vo.getId());
                    if (null!=businessOrderDO){
                        businessOrders.add(businessOrderDO);
                    }
                }

            }
            rs.put("prescriptions", prescriptionVOs);
            rs.put("businessOrder", businessOrders);

            //物流信息
            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);
            }

            //物流配送新
            List<WlyyPrescriptionExpressageLogDO> expressageLogDOs = prescriptionExpressageLogDao.queryByOutpatientIdOrderByCreateTimeDesc(outpatientId);
            List<WlyyPrescriptionExpressageLogVO> expressageLogVOs = new ArrayList<>();
            if (expressageLogDOs != null && expressageLogDOs.size() > 0) {
                rs.put("expressageLogs", convertToModels(expressageLogDOs, expressageLogVOs, WlyyPrescriptionExpressageLogVO.class));
            } else {
                rs.put("expressageLogs", null);
            }
        }else {
            List<BaseAdviceTreatmentDO>  treatmentDOS=baseAdviceTreatmentDao.findByRelationCode(outpatientId);
            if (treatmentDOS!=null&&treatmentDOS.size()>0){
                //药品
                List<WlyyPrescriptionInfoDO> infoDOList=prescriptionInfoDao.findByPrescriptionId(treatmentDOS.get(0).getId(), 1);
                treatmentDOS.get(0).setInfoList(infoDOList);
                rs.put("treatments",treatmentDOS.get(0));
            }else{
                rs.put("treatments","");
            }
        }


        //预约记录
        List<WlyyPatientRegisterTimeDO> timeDOs = patientRegisterTimeDao.findByOutpatientId(outpatientId);
        if (timeDOs != null && timeDOs.size() > 0) {
            rs.put("register", timeDOs.get(0));
        } else {
            rs.put("register", null);
        }

        return rs;
    }


    /**
     * 查询历史
     *
     * @param patient
     * @param status
     * @param startTime
     * @param endTime
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findPrescriptionList(String patient, String status, String startTime, String endTime, Integer page, Integer size, String wxId) {

        String totalSql = "SELECT " +
                " count(1) AS \"total\" " +
                " FROM " +
                " wlyy_prescription p ";
        totalSql += " WHERE 1=1 and p.check_status <>3 and p.check_status <>4";
        if (StringUtils.isNotBlank(patient)) {
            totalSql += " AND p.patient_code ='" + patient + "'";
        }
        if (StringUtils.isNotBlank(status)) {
            totalSql += " AND p.status IN (" + status + ")";
        }
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    totalSql += " and create_time >= str_to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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)) {
                if (flag){
                    totalSql += " and create_time <= str_to_date('" + startTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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'";
            }

        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);

        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        String sql = "SELECT " +
                " p.id as \"id\", " +
                " p.real_order AS \"realOrder\"," +
                " p.origin_real_order AS \"originRealOrder\"," +
                " p.adm_no AS \"admNo\"," +
                " p.origin_adm_no AS \"originAdmNo\"," +
                " p.serial_no AS \"serialNo\"," +
                " p.type AS \"type\", " +
                " p.patient_code AS \"patientCode\", " +
                " p.patient_name AS \"patientName\", " +
                " p.ssc AS \"ssc\", " +
                " p.doctor AS \"doctor\", " +
                " p.doctor_name AS \"doctorName\", " +
                " p.status AS \"status\", " +
                " p.mk_fail_reason AS \"mkFailReason\", " +
                " p.mk_time AS \"mk_time\", " +
                " p.prescribe_reason AS \"prescribeReason\", " +
                " p.prescribe_time AS \"prescribeTime\", " +
                " p.pay_time AS \"payTime\", " +
                " p.dosage_time AS \"dosageTime\", " +
                " p.jih_time AS \"finishTime\", " +
                " p.create_time AS \"createTime\", " +
                " p.dept AS \"dept\", " +
                " p.dept_name AS \"deptName\", " +
                " p.hospital AS \"hospital\", " +
                " p.hospital_name AS \"hospitalName\", " +
                " p.consult AS \"consult\", " +
                " p.dispensary_type AS \"dispensaryType\", " +
                " p.reason AS \"reason\", " +
                " p.remark AS \"remark\", " +
                " p.cancel_reason AS \"cancelReason\", " +
                " p.ca_cert_data AS \"caCertData\", " +
                " p.ca_message AS \"caMessage\", " +
                " p.digital_sign_no AS \"digitalSignNo\", " +
                " p.original_data_abstract AS \"originalDataAbstract\", " +
                " p.str_original_data AS \"strOriginalData\", " +
                " p.his_dept_code AS \"hisDeptCode\", " +
                " p.his_doctor_code AS \"hisDoctorCode\", " +
                " p.his_gister_type_code AS \"hisGisterTypeCode\", " +
                " p.his_rate_type_code AS \"hisRateTypeCode\", " +
                " p.his_hospital AS \"hisHospital\", " +
                " p.his_register_fee AS \"hisRegisterFee\", " +
                " p.pay_status AS \"payStatus\" " +
                " FROM " +
                " wlyy_prescription p " +
                " WHERE 1=1 and p.check_status <>3  ";
        if (StringUtils.isNotBlank(patient)) {
            sql += " AND p.patient_code ='" + patient + "'";
        }
        if (StringUtils.isNotBlank(status)) {
            sql += " AND p.status IN (" + status + ")";
        }
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql += " and create_time >= str_to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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)) {
                if (flag){
                    sql += " and create_time <= str_to_date('" + startTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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 + "";
        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyPrescriptionVO.class));

        //设置病种,药品
        if (list != null && list.size() > 0) {
            for (WlyyPrescriptionVO vo : list) {
                vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                vo.setInfoVOs(convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(), 1), infoVOs, WlyyPrescriptionInfoVO.class));
            }
        }

        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    public List<WlyyPrescriptionDiagnosisVO> findDiagnosisById(String id) {
        List<WlyyPrescriptionDiagnosisDO> list = prescriptionDiagnosisDao.findByPrescriptionId(id, 1);
        List<WlyyPrescriptionDiagnosisVO> rs = new ArrayList<>();
        if (list != null && list.size() > 0) {
            return convertToModels(list, rs, WlyyPrescriptionDiagnosisVO.class);
        }
        return rs;
    }

    public WlyyPrescriptionDO findPrescriptionDo(String prescriptionId) {
        return prescriptionDao.findOne(prescriptionId);
    }

    public Map<String, Object> findPrescriptionInfo(String prescriptionId) {
        //续方信息
        Map<String, Object> rs = new HashedMap();
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        rs.put("prescription", convertToModel(wlyyPrescriptionDO, WlyyPrescriptionVO.class));

        //居民详情
        BasePatientDO basePatientDO = basePatientDao.findById(wlyyPrescriptionDO.getPatientCode());
        rs.put("patientName", basePatientDO.getName());
        rs.put("patientId", basePatientDO.getId());
        rs.put("idCard", basePatientDO.getIdcard());
        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()));

        //诊断信息
        rs.put("diagnosis", findDiagnosisById(wlyyPrescriptionDO.getId()));

        //药品信息
        rs.put("infos", prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(), 1));

        return rs;
    }

    public Boolean checkPrescription(String patient) {
        List<WlyyPrescriptionDO> list = prescriptionDao.findByPatientCode(patient);
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }


    /**
     * 发起图文和视频复诊
     *
     * @param outpatientJson
     * @param expressageJson
     * @return
     * @throws Exception
     */
    @Transactional
    public WlyyOutpatientDO appointmentRevisit(String outpatientJson, String expressageJson, String registerJson, String chargeType) throws Exception {
        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        BaseDoctorDO doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
        outpatientDO.setIsAgree("1");
        outpatientDO.setMjz("mz");
        outpatientDO.setStatus("0");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setIdcard(patientDO.getIdcard());
        outpatientDO.setCreateTime(new Date());


        if (outpatientDO.getRegisterDate() == null) {
            outpatientDO.setRegisterDate(new Date());
        }
        WlyyPrescriptionExpressageDO expressageDO = new WlyyPrescriptionExpressageDO();
        if(!outpatientDO.getOutpatientType().equalsIgnoreCase("3")){
            WlyyPrescriptionExpressageDO previous = checkOutPatientPre(outpatientDO.getPatient());
            //2.物流信息
            expressageDO = objectMapper.readValue(expressageJson, WlyyPrescriptionExpressageDO.class);
            if (null!=previous.getId()&&previous.getOneselfPickupFlg()!=expressageDO.getOneselfPickupFlg()){
                WlyyOutpatientDO wlyyOutpatientDO = new WlyyOutpatientDO();
                wlyyOutpatientDO.setOutpatientType(outpatientDO.getOutpatientType());
                wlyyOutpatientDO.setRemindCount(previous.getOneselfPickupFlg());
                return wlyyOutpatientDO;
            }
        }

        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("WX_MONEY");
        Double price = 0.0;
        String chargeType1 = null;
        if (doctorDO!=null){
            if (outpatient.getOutpatientType().equalsIgnoreCase("1")){
                if(outpatientDO.getType().equalsIgnoreCase("1")){
                    chargeType1 = doctorDO.getTwfzChargeType();
                }else if(outpatientDO.getType().equalsIgnoreCase("2")){
                    chargeType1 = doctorDO.getSpfzChargeType();
                }
            }else if (outpatient.getOutpatientType().equalsIgnoreCase("3")){
                if(outpatientDO.getType().equalsIgnoreCase("1")){
                    chargeType1 = doctorDO.getTwzxChargeType();
                }else if(outpatientDO.getType().equalsIgnoreCase("2")){
                    chargeType1 = doctorDO.getSpzxChargeType();
                }
            }else if (outpatient.getOutpatientType().equalsIgnoreCase("2")){
                chargeType1 = doctorDO.getXtfzChargeType();
            }
            if(doctorDO!=null){
                if (StringUtils.isNoneBlank(chargeType1)){
                    WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByChargeType(chargeType1);
                    if (chargeDictDO!=null){
                        price = chargeDictDO.getReqFee();
                    }else {
                        price = Double.parseDouble(hospitalSysDictDO.getDictValue());
                    }
                }
            }else {
                price = Double.parseDouble(hospitalSysDictDO.getDictValue());
            }
        }else {
            if (StringUtils.isNoneBlank(chargeType)){
                WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByChargeType(chargeType);
                if (chargeDictDO!=null){
                    price = chargeDictDO.getReqFee();
                }else {
                    price = Double.parseDouble(hospitalSysDictDO.getDictValue());
                }
            }
        }
        /*if (doctorDO != null && StringUtils.isNoneBlank(doctorDO.getFee())) {
            price = Double.parseDouble(doctorDO.getFee());
        }else {
            price = Double.parseDouble(hospitalSysDictDO.getDictValue());
        }*/
        if (price == 0.0) {
            outpatientDO.setPayStatus(1);
        } else {
            outpatientDO.setPayStatus(0);
            outpatientDO.setFee(price);
            outpatient = outpatientDao.save(outpatientDO);
        }

        if (outpatient.getOutpatientType().equalsIgnoreCase("1")){
            if (outpatient.getType().equalsIgnoreCase("1")){
                businessOrderService.recharge(outpatient.getId(), "图文复诊-诊查费", "2", "图文复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
            }else if (outpatient.getType().equalsIgnoreCase("2")){
                businessOrderService.recharge(outpatient.getId(), "视频复诊-诊查费", "3", "视频复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
            }
        }else if (outpatient.getOutpatientType().equalsIgnoreCase("2")){
            businessOrderService.recharge(outpatient.getId(), "协同复诊-诊查费", "5", "协同复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }else if ("3".equalsIgnoreCase(outpatient.getOutpatientType())){
            BusinessOrderDO businessOrderDO = businessOrderService.recharge(outpatient.getId(), "专家咨询费", "1", "专家咨询费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }


        WlyyPatientRegisterTimeDO registerTimeDO = null;
        WlyyPatientRegisterTimeDO wlyyPatientRegisterTimeDO =new WlyyPatientRegisterTimeDO();
        try {
            //如果是视频预约咨询
            if (StringUtils.isNotBlank(registerJson)) {
                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                wlyyPatientRegisterTimeDO = patientRegisterTimeDao.save(registerTimeDO);
            }
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约，请选择其他号源");
        }
        if (!outpatientDO.getOutpatientType().equalsIgnoreCase("3")){
            if (1==expressageDO.getOneselfPickupFlg()){
                if("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                    String drugCode= expressageDO.getHospitalCode()==null?"5550":expressageDO.getHospitalCode();
                    expressageDO.setHospitalCode(drugCode);
                }
                System.out.println("进入物流信息");
                expressageDO.setDel(1);
                expressageDO.setCreateTime(new Date());
                expressageDO.setOutpatientId(outpatient.getId());
                prescriptionExpressageDao.save(expressageDO);
            }else {
                System.out.println("写入自取信息");
                String drugStoreCode = expressageDO.getHospitalCode();
                BaseDrugStoreDO baseDrugStoreDO = baseDrugStoreDao.findDrugByid(drugStoreCode);
                if (null!=baseDrugStoreDO){
                    expressageDO.setCityCode(baseDrugStoreDO.getCityCode());
                    expressageDO.setCityName(baseDrugStoreDO.getCityName());
                    expressageDO.setProvinceCode(baseDrugStoreDO.getProvinceCode());
                    expressageDO.setProvinceName(baseDrugStoreDO.getProvinceName());
                    expressageDO.setTownCode(baseDrugStoreDO.getTownCode());
                    expressageDO.setTownName(baseDrugStoreDO.getTownName());
                    expressageDO.setHospitalCode(baseDrugStoreDO.getDrugStoreCode());
                    expressageDO.setHospitalName(baseDrugStoreDO.getHospitalName());
                    expressageDO.setHospitalAddress(baseDrugStoreDO.getAddress());
                }
                expressageDO.setDel(1);
                expressageDO.setCreateTime(new Date());
                expressageDO.setOutpatientId(outpatient.getId());
                prescriptionExpressageDao.save(expressageDO);
            }
        }
        if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
            logger.info("心脏中心同步患者开始");
            xzzxEntranceService.updatePatientMapping(outpatient.getConsumer(),outpatient.getCardNo());
            logger.info("同步患者id成功");
        }


        //3.创建候诊室
        createRoom(outpatient, chargeType);
        String content = "向您发起了图文复诊，点击查看";

        return outpatient;
    }
    public WlyyPrescriptionExpressageDO checkOutPatientPre(String patientId) throws ParseException {
        String sql = "select t.id as \"id\",t.adm_no as \"admNo\",t.create_time as \"createTime\" from wlyy_outpatient t where 1=1";
        String startDate = DateUtil.getStringDateShort()+" 00:00:00";
        String endDate = DateUtil.getStringDateShort()+" 23:59:59";
        if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)||"xm_xzzx_wx".equalsIgnoreCase(wechatId)){
            sql+=" and t.create_time >= '" +startDate+"' "+
                    " and t.create_time <= '" +endDate+"' ";
        }else if("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            sql+=" and  t.create_time >= to_char('"+startDate+"','yyyy-mm-dd hh:mm:ss')\n" +
                    "and t.create_time < to_char('"+endDate+"','yyyy-mm-dd hh:mm:ss')";
        }else {
            sql+=" and t.create_time >= '" +startDate+"' "+
                    " and t.create_time <= '" +endDate+"' ";
        }
        if (StringUtils.isNoneBlank(patientId)){
            sql+=" and t.patient = '"+patientId+"'";
        }
        sql +=" and t.outpatient_type = 1  order by t.create_time desc";
        System.out.println(sql);
        List<Map<String,Object>> listPrescript = hibenateUtils.createSQLQuery(sql);
        WlyyPrescriptionExpressageDO wlyyPrescriptionExpressageDO = new WlyyPrescriptionExpressageDO();
        if (listPrescript!=null&&listPrescript.size()>=1){
            Map<String,Object> mapPrescript = listPrescript.get(0);
            String outPatientId = mapPrescript.get("id").toString();
            List<WlyyPrescriptionExpressageDO> list =  prescriptionExpressageDao.findByOutpatientId(outPatientId);
            if(list!=null&&list.size()!=0){
                wlyyPrescriptionExpressageDO = list.get(0);
            }
        }
        return wlyyPrescriptionExpressageDO;
    }

    /**
     * 创建候诊室
     *
     * @param outpatientDO
     * @return
     */
    public Boolean createRoom(WlyyOutpatientDO outpatientDO, String chargeType) {
        System.out.println("进入创建候诊室");
        WlyyHospitalWaitingRoomDO waitingRoom = new WlyyHospitalWaitingRoomDO();

        waitingRoom.setDept(outpatientDO.getDept());
        waitingRoom.setDeptName(outpatientDO.getDeptName());
        waitingRoom.setHospital(outpatientDO.getHospital());
        waitingRoom.setHospitalName(outpatientDO.getHospitalName());

        //是否是有协同门诊医生
        if (StringUtils.isNotBlank(outpatientDO.getGeneralDoctor())) {
            System.out.println("是否是有协同门诊医生");
            waitingRoom.setGeneralDoctor(outpatientDO.getGeneralDoctor());
            waitingRoom.setGeneralDoctorName(outpatientDO.getGeneralDoctorName());
        }

        waitingRoom.setPatientId(outpatientDO.getPatient());
        waitingRoom.setPatientName(outpatientDO.getPatientName());
        waitingRoom.setReservationTime(outpatientDO.getRegisterDate());
        waitingRoom.setVisitStatus(0);
        //设置复诊类型
        waitingRoom.setReservationType(StringUtils.isNotBlank(outpatientDO.getOutpatientType()) ? Integer.parseInt(outpatientDO.getOutpatientType()) : 1);

        waitingRoom.setSort(0);
        waitingRoom.setConsultType(Integer.parseInt(outpatientDO.getType()));
        if (StringUtils.isNotBlank(outpatientDO.getDoctor())) {
            waitingRoom.setDoctor(outpatientDO.getDoctor());
            waitingRoom.setDoctorName(outpatientDO.getDoctorName());
        }
        waitingRoom.setOutpatientId(outpatientDO.getId());
        waitingRoom.setCreateTime(new Date());

        if (StringUtils.isNotBlank(chargeType)) {
            waitingRoom.setChargeType(chargeType);
        }

        hospitalWaitingRoomDao.save(waitingRoom);

        return true;
    }


    public Boolean cancelPrescription(String prescriptionId) {
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        prescriptionDO.setStatus(-2);
        return true;
    }


    /**
     * @param admNo     门诊唯一号
     * @param realOrder 处方号
     * @param status    处方状态 1审方失败，2审核完成，3结算完成
     * @return
     */
    public Map<String, Object> updatePrescriptionByHisStatu(String admNo, String realOrder, String status) throws Exception {
        Map<String, Object> rs = new HashedMap();

        String sql = "";
        //status 处方流程状态 ，13  开方失败/调整中，20 诊断完成/开方成功/待支付,已完成：100 已完成
        //pay_status`:处方结算状态，0为未结算，1为结算成功，默认为0',
        String outPatientSql = "";
        if ("1".equals(status)) {
            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);
            jdbcTemplate.execute(sql);

        } else if ("2".equals(status)) {
            //开方成功时候，先用处方号获取本地处方状态是否为开方失败，如果是则需要更新本地的处方
            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 + "'";
            jdbcTemplate.execute(outPatientSql);
            jdbcTemplate.execute(sql);

        } else if ("3".equals(status)) {
            //自取处方结束
            WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findByRealOrder(realOrder);
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());

            if (null != wlyyPrescriptionDO && 1 == wlyyPrescriptionDO.getDispensaryType()) {
                //取药类型:1 自取 2快递配送
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setStatus(100);

                prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(), 100, 2, outpatientDO.getDoctor(), outpatientDO.getDoctorName(), "", new Date());
                prescriptionDao.save(wlyyPrescriptionDO);

            } else {
                //取药类型:1 自取 2快递配送
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setStatus(32);

                try {
                    WlyyPrescriptionVO vo = findOriginPrescription(outpatientDO.getRegisterNo(), outpatientDO.getPatient(), admNo, realOrder, demoFlag);
                    wlyyPrescriptionDO.setDispUser(vo.getDispUser());
                    wlyyPrescriptionDO.setDispUserName(vo.getDispUserName());
                    wlyyPrescriptionDO.setDispDate(new Date());
                    prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(), 32, 2, vo.getDispUser(), vo.getDispUserName(), "", new Date());
                } catch (Exception e) {
                    logger.error("获取处方信息异常" + e.toString());
                }
                prescriptionDao.save(wlyyPrescriptionDO);
            }
            //发送取药系统消息
            SystemMessageDO systemMessageDO = sendPatientGetDrugMes(outpatientDO, wlyyPrescriptionDO);

            rs.put("mes", systemMessageDO);
        }

        rs.put("flag", true);
        return rs;
    }

    public SystemMessageDO sendPatientGetDrugMes(WlyyOutpatientDO outpatient, WlyyPrescriptionDO prescriptionDO) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        try {

            systemMessageDO.setTitle("患者取药");
            systemMessageDO.setType("7");
            systemMessageDO.setReceiver(outpatient.getDoctor());
            systemMessageDO.setReceiverName(outpatient.getDoctorName());
            systemMessageDO.setRelationCode(outpatient.getId());
            systemMessageDO.setSender(outpatient.getPatient());
            systemMessageDO.setSenderName(outpatient.getPatientName());
            systemMessageDO.setRelationCode(outpatient.getId());

            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", "患者已完成取药");

            systemMessageDO.setData(data.toString());

            systemMessageService.saveMessage(systemMessageDO);

        } catch (Exception e) {
            logger.error("sendPatientGetDrugMes :" + e.toString());
        }
        return systemMessageDO;
    }

    /**
     * 获取卡记录
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public JSONArray findPatientCard(String patient) throws Exception {
        BasePatientDO patientDO = basePatientDao.findById(patient);
        JSONArray res = entranceService.BS15018(patientDO.getIdcard(), null, demoFlag);
        JSONArray rs = new JSONArray();
        if (res != null) {
            for (int i = 0; i < res.size(); i++) {
                JSONObject card = res.getJSONObject(i);
                String cardStat = card.getString("CARD_STAT");
                String name = card.getString("name");
                if ("激活".equals(cardStat)&&name.equalsIgnoreCase(patientDO.getName())) {
                    rs.add(card);
                }
            }
        }
        return rs;
    }

    public Map<String, Object> checkOutpatient(String patient,String wxId,boolean flag,String outpatientType) throws Exception {
        //-1卡余额不足，,-2 存在未结束的诊断热 1成功
        Map<String, Object> rs = new HashedMap();
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("consultAccount");
        String accountControl = "0";
        if (null!=wlyyHospitalSysDictDO){
            accountControl = wlyyHospitalSysDictDO.getDictValue();
        }
        //1.判断
        //net.sf.json.JS余额判断改到前端ONObject json = entranceService.qutpatientBalance(cardNo,demoFlag);
        if (flag){
            if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
                List<WlyyOutpatientDO> outpatientDOS = new ArrayList<>();
                if (StringUtils.isNotBlank(outpatientType)){
                    outpatientDOS = outpatientDao.findByPatientListByStatusAndType(patient,outpatientType);
                }else {
                    outpatientDOS = outpatientDao.findByPatientListByStatus(patient);
                }
                if (outpatientDOS!=null&&outpatientDOS.size()!=0){
                    WlyyOutpatientDO outpatientDO = outpatientDOS.get(0);
                    if (outpatientDO.getHisStatus()!=null&&"0".equalsIgnoreCase(accountControl)){
                        logger.info("您上一次就诊进入"+outpatientDO.getHisStatus());
                        if(outpatientDO.getHisStatus()!=1&&outpatientDO.getHisStatus()!=-1){
                            logger.info("您上一次就诊进入======"+outpatientDO.getHisStatus());
                            rs.put("outpatient", outpatientDO);
                            rs.put("code", -3);
                            rs.put("mes", "您上一次就诊未结算，请结算后才能发起复诊。");
                            List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wxId, patient);
                            if (patientWechatDos == null || patientWechatDos.size() == 0) {
                                throw new Exception("openid不存在！");
                            }
                            WxWechatDO wxWechatDO = wechatDao.findById(wxId);
                            BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
                            String payUrl = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(),patientWechatDo.getOpenid(),outpatientDO.getCardNo(),"WX");
                            rs.put("payUrl",payUrl);
                            return rs;
                        }

                    }else if (outpatientDO.getHisStatus()==null&&"0".equalsIgnoreCase(accountControl)){
                        rs.put("outpatient", outpatientDO);
                        rs.put("code", -3);
                        rs.put("mes", "您上一次就诊未结算，请结算后才能发起复诊。");
                        List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wxId, outpatientDO.getConsumer());
                        if (patientWechatDos == null || patientWechatDos.size() == 0) {
                            throw new Exception("openid不存在！");
                        }
                        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
                        BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
                        String payUrl = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(),patientWechatDo.getOpenid(),outpatientDO.getCardNo(),"WX");
                        rs.put("payUrl",payUrl);
                        return rs;
                    }
                }
            }
        }

        //2.判断是否有未结束的
        List<WlyyOutpatientDO> list = new ArrayList<>();
        if(StringUtils.isNotBlank(outpatientType)&&outpatientType.equalsIgnoreCase("3")){
            list = outpatientDao.findByPatientAndDoctorList(patient);
        }else {
            list = outpatientDao.findByPatientList(patient);
        }

        if (list != null && list.size() > 0) {
            if(!list.get(0).getOutpatientType().equalsIgnoreCase("3")){
                rs.put("outpatient", list.get(0));
                rs.put("code", -2);
                rs.put("mes", "存在未结束的诊断");
                return rs;
            }else {
                rs.put("outpatient", list.get(0));
                rs.put("code", -2);
                rs.put("mes", "存在未结束的咨询");
                return rs;
            }
        }
        rs.put("code", 1);
        rs.put("mes", "验证通过");
        return rs;
    }

    /**
     * 获取所有医院列表
     *
     * @return
     */
    public List<BaseOrgVO> findAllHospital(Integer level, String keyWord) {

        if (StringUtils.isNoneEmpty(keyWord)) {
            keyWord = "%" + keyWord + "%";

            if (level != null) {
                List<BaseOrgDO> list = baseOrgDao.findByLevelAndName(level, "1", keyWord);
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list, rs, BaseOrgVO.class);
            } else {
                List<BaseOrgDO> list = baseOrgDao.findByDelAndName("1", keyWord);
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list, rs, BaseOrgVO.class);
            }
        } else {

            if (level != null) {
                List<BaseOrgDO> list = baseOrgDao.findByLevelAndDel(level, "1");
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list, rs, BaseOrgVO.class);
            } else {
                List<BaseOrgDO> list = baseOrgDao.findByDel("1");
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list, rs, BaseOrgVO.class);
            }
        }

    }

    /**
     * 获取机构下部门信息
     *
     * @param orgCode
     * @return
     */
    public List<DictHospitalDeptVO> findDeptByHospital(String orgCode, String dept, String consultDeptFlag) {
        List<DictHospitalDeptDO> list;
        if (StringUtils.isNotBlank(consultDeptFlag) && "1".equals(consultDeptFlag)) {
            list = dictHospitalDeptDao.findByOrgCodeAndConsultDeptFlag(orgCode, consultDeptFlag);
        } else {
            list = dictHospitalDeptDao.findByOrgCodeIn(orgCode);
        }
        List<DictHospitalDeptVO> rs = new ArrayList<>();
        convertToModels(list, rs, DictHospitalDeptVO.class);
        if (rs != null && rs.size() > 0 && StringUtils.isNotBlank(dept)) {
            //排序
            for (int i = 0; i < rs.size(); i++) {
                String id = rs.get(i).getCode();
                if (dept.equals(id)) {
                    Collections.swap(rs, 0, i);
                }
            }
        }
        return rs;
    }


    /**
     * 获取医生列表.
     *
     * @param orgCode
     * @param dept
     * @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 " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.expertise AS \"expertise\"," +
                " d.introduce AS \"introduce\"," +
                " d.job_title_code AS \"jobTitleCode\", " +
                " d.job_title_name AS \"jobTitleName\"," +
                " d.charge_type AS \"chargeType\"," +
                " d.outpatient_type AS \"outpatientType\"," +
                " d.consult_status AS \"consultStatus\"," +
                " h.dept_code AS \"deptCode\","+
                " h.dept_name AS \"deptName\","+
                " h.org_code AS \"orgCode\","+
                " h.org_name AS \"orgName\","+
                " t.photo AS \"hosptialphoto\""+
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " left join base_org t on t.id = h.org_code" +
                " WHERE  " +
                " 1=1 and d.del=1 ";
        Map<String, Object> params = new HashedMap();
        if (StringUtils.isNotBlank(dept)) {
            sql += " AND h.dept_code = '" + dept + "'";
        }
        if (StringUtils.isNotBlank(orgCode)) {
            sql += " AND h.org_code = '" + orgCode + "'";
        }
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equals(chargeType)) {
                //查询全部号源
            } else {
                sql += " AND d.charge_type ='" + chargeType + "'";
            }
        } else {
            sql += " AND d.charge_type is not null ";
        }
        if (StringUtils.isNotBlank(outpatientType)) {
            if ("all".equals(outpatientType)) {
                //查询全部权限
            } else {
                sql += " AND d.outpatient_type like'%" + outpatientType + "%'";
            }
        } else {
            sql += " AND d.outpatient_type is not null ";
        }
        if (StringUtils.isNotBlank(key)) {
            sql += " AND (h.dept_name like '%" + key + "%' OR d.name like '%" + key + "%' OR d.expertise like '%" + key + "%') ";
        }
        if (StringUtils.isNotBlank(consultStatus)) {
            sql += " AND d.consult_status = '" + consultStatus + "'";
        }
        if (StringUtils.isNotBlank(endDate) && StringUtils.isNotBlank(startDate)) {
            sql += " AND EXISTS ( " +
                    " SELECT " +
                    "  1 " +
                    " FROM " +
                    "  wlyy_doctor_work_time t " +
                    " WHERE " +
                    "  t.doctor = d.id " +
                    " AND t.start_time >=:startDate" +
                    " 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"));

        }

        logger.info("v sql:" + sql);

        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params);

        if (list != null && list.size() > 0 && StringUtils.isNotBlank(doctorCode)) {
            //排序
            for (int i = 0; i < list.size(); i++) {
                String id = (String) list.get(i).get("id");
                if (doctorCode.equals(id)) {
                    Collections.swap(list, 0, i);
                }
            }
        }

        return list;
    }

    /**
     * 获取医生列表带排班
     *
     * @param orgCode
     * @param dept
     * @return
     */
    public MixEnvelop findDoctorWithWork(String orgCode, String dept, String chargeType, String doctorCode, String outpatientType, String startDate, String endDate, String key, String consultStatus, Integer page, Integer size,String ywCode) {

        String totalSql = "SELECT " +
                " count(1) AS \"total\" " +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " WHERE  " +
                " 1=1 ";
        Map<String, Object> params = new HashedMap();
        if (StringUtils.isNotBlank(dept)) {
            totalSql += " AND h.dept_code = '" + dept + "'";
        }
        if (StringUtils.isNotBlank(orgCode)) {
            totalSql += " AND h.org_code = '" + orgCode + "'";
        }
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equalsIgnoreCase(chargeType)) {

            } else {
                totalSql += " AND d.charge_type ='" + chargeType + "'";
            }
        } else {
            totalSql += " AND d.charge_type is not null ";
        }
        if (StringUtils.isNotBlank(outpatientType)) {
            if (outpatientType.contains("or")) {
                String[] outpatientTypeArray = outpatientType.split("or");
                totalSql += " AND ( ";

                for (int i = 0; i < outpatientTypeArray.length; i++) {
                    totalSql += " d.outpatient_type like'%" + outpatientTypeArray[i] + "%'";
                    if (i != outpatientTypeArray.length - 1) {
                        totalSql += " or ";
                    }
                }
                totalSql += "  ) ";
            } else {
                totalSql += " AND d.outpatient_type like'%" + outpatientType + "%'";
            }
        } else {
            totalSql += " AND d.outpatient_type is not null ";
        }
        if (StringUtils.isNotBlank(key)) {
            totalSql += " AND (h.dept_name like '%" + key + "%' OR d.name like '%" + key + "%' OR d.expertise like '%" + key + "%') ";
        }
        if (StringUtils.isNotBlank(consultStatus)) {
            totalSql += " AND d.consult_status = '" + consultStatus + "'";
        }
        if (StringUtils.isNotBlank(endDate) && StringUtils.isNotBlank(startDate)) {
            totalSql += " AND EXISTS ( " +
                    " SELECT " +
                    "  1 " +
                    " FROM " +
                    "  wlyy_doctor_work_time t " +
                    " WHERE " +
                    "  t.doctor = d.id " +
                    " AND t.start_time >=:startDate" +
                    " 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"));
        }
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql, params);

        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = hibenateUtils.objTransformLong(rstotal.get(0).get("total"));
        }

        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.expertise AS \"expertise\"," +
                " d.introduce AS \"introduce\"," +
                " d.job_title_code AS \"jobTitleCode\", " +
                " d.job_title_name AS \"jobTitleName\"," +
                " d.charge_type AS \"chargeType\"," +
                " h.dept_code AS \"deptCode\"," +
                " h.dept_Name AS \"deptName\"," +
                " d.outpatient_type AS \"outpatientType\"," +
                " d.consult_status AS \"consultStatus\"," +
                " d.twfz_charge_type AS \"twfzConsultStatus\"," +
                " d.spfz_charge_type AS \"spfzConsultStatus\"," +
                " d.twzx_charge_type AS \"twzxConsultStatus\"," +
                " d.spzx_charge_type AS \"spzxConsultStatus\"," +
                " d.xtfz_charge_type AS \"xtfzConsultStatus\" " +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " WHERE " +
                " 1=1";
        if (StringUtils.isNotBlank(dept)) {
            sql += " AND h.dept_code = '" + dept + "'";
        }
        if (StringUtils.isNotBlank(orgCode)) {
            sql += " AND h.org_code = '" + orgCode + "'";
        }

        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equalsIgnoreCase(chargeType)) {

            } else {
                sql += " AND d.charge_type ='" + chargeType + "'";
            }
        } else {
            sql += " AND d.charge_type is not null";
        }

        if (StringUtils.isNotBlank(outpatientType)) {
            if (outpatientType.contains("or")) {
                String[] outpatientTypeArray = outpatientType.split("or");
                sql += " AND ( ";

                for (int i = 0; i < outpatientTypeArray.length; i++) {
                    sql += " d.outpatient_type like'%" + outpatientTypeArray[i] + "%'";
                    if (i != outpatientTypeArray.length - 1) {
                        sql += " or ";
                    }
                }
                sql += " ) ";
            } else {
                sql += " AND d.outpatient_type like'%" + outpatientType + "%'";
            }
        } else {
            sql += " AND d.outpatient_type is not null ";
        }

        if (StringUtils.isNotBlank(key)) {
            sql += " AND (h.dept_name like '%" + key + "%' OR d.name like '%" + key + "%' OR d.expertise like '%" + key + "%') ";
        }
        if (StringUtils.isNotBlank(consultStatus)) {
            sql += " AND d.consult_status = '" + consultStatus + "'";
        }
        if (StringUtils.isNotBlank(endDate) && StringUtils.isNotBlank(startDate)) {
            sql += " AND EXISTS ( " +
                    " SELECT " +
                    "  1 " +
                    " FROM " +
                    "  wlyy_doctor_work_time t " +
                    " WHERE " +
                    "  t.doctor = d.id " +
                    " AND t.start_time >= :startDate" +
                    " AND t.start_time <= :endDate" +
                    " )";
        }
        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);
        if (list != null && list.size() > 0) {
            //获取排班
            for (Map<String, Object> doctor : list) {
                String id = (String) doctor.get("id");
                List<WlyyDoctorWorkTimeVO> times = findDoctorWorkTime(id, orgCode,ywCode);
                doctor.put("workTime", times);
                String deptTyepCode = "";
                if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                    deptTyepCode = "6";
                    List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(id);
                    if (null!=depts&&depts.size()>0){
                        BaseDoctorHospitalDO baseDoctorHospitalDO = depts.get(0);
                        String deptcode =  baseDoctorHospitalDO.getDeptCode();
                        String hosptitalCode = baseDoctorHospitalDO.getOrgCode();
                        List<DictHospitalDeptDO> dictHospitalDeptDO = dictHospitalDeptDao.findByOrgCodeAndCode(hosptitalCode,deptcode);
                        if(null!=dictHospitalDeptDO&&dictHospitalDeptDO.size()>0){
                            if (StringUtils.isNotBlank(dictHospitalDeptDO.get(0).getDeptTypeCode())){
                                deptTyepCode = dictHospitalDeptDO.get(0).getDeptTypeCode();
                            }
                        }
                    }
                }
                List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
                String sqlCharge = "SELECT\n" +
                        "\tm.req_fee as \"twfzFee\",\n" +
                        "\ta.req_fee as \"spfzFee\",\n" +
                        "\tb.req_fee as \"spzxFee\",\n" +
                        "\tv.req_fee as \"twzxFee\",\n" +
                        "\tg.req_fee as \"jyzxFee\",\n" +
                        "\td.req_fee as \"xtzxFee\"\n" +
                        "FROM\n" +
                        "\tbase_doctor t\n" +
                        "LEFT JOIN wlyy_charge_dict m ON t.twfz_charge_type = m.charge_type and m.is_del='1'\n" +
                        "LEFT JOIN wlyy_charge_dict a ON t.spfz_charge_type = a.charge_type and a.is_del='1'\n" +
                        "LEFT JOIN wlyy_charge_dict b ON t.spzx_charge_type = b.charge_type and b.is_del='1'\n" +
                        "LEFT JOIN wlyy_charge_dict v ON t.twzx_charge_type = v.charge_type and v.is_del='1'\n" +
                        "LEFT JOIN wlyy_charge_dict d ON t.twzx_charge_type = d.charge_type and d.is_del='1'\n" +
                        " LEFT JOIN wlyy_charge_dict g ON t.jyzx_charge_type = g.charge_type and g.is_del='1'\n" +
                        "WHERE t.id = '"+doctor.get("id")+"' ";
                chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);

                doctor.put("chargeTypeList",chargeDictDOLists);
            }
            if (StringUtils.isNotBlank(doctorCode)) {
                //排序
                for (int i = 0; i < list.size(); i++) {
                    String id = (String) list.get(i).get("id");
                    if (doctorCode.equals(id)) {
                        Collections.swap(list, 0, i);
                    }
                }
            }
        }
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    public List<WlyyDoctorWorkTimeVO> findDoctorWorkTime(String doctor, String hospital,String ywCode) {

        List<WlyyHospitalWorkRuleDO> list = wlyyHospitalWorkRuleDao.findByHospital(hospital);

        if (list != null && list.size() > 0) {
            WlyyHospitalWorkRuleDO rule = list.get(0);

            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");

            Integer openDay = rule.getMaxDay();
            if (openTime.before(new Date())) {
                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 endDate = DateUtil.stringToDate(maxDateString, "yyyy-MM-dd HH:mm:ss");
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            String isCheckWork = "1";//1需要判断医生在班0不需要
            if (StringUtils.isNoneBlank(ywCode)){
                WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById(ywCode);
                if (wlyyHospitalSysDictDO!=null){
                    isCheckWork = wlyyHospitalSysDictDO.getDictValue();
                }

            }
            if ("1".equalsIgnoreCase(isCheckWork)){
                List<WlyyDoctorWorkTimeDO> timeDOs = doctorWorkTimeDao.findDoctorWorkTime(doctor, new Date(), endDate);
                if (timeDOs != null && timeDOs.size() > 0) {
                    convertToModels(timeDOs, timeVOs, WlyyDoctorWorkTimeVO.class);
                    if (timeVOs != null && timeVOs.size() > 0) {
                        for (WlyyDoctorWorkTimeVO timeVO : timeVOs) {
                            timeVO.setCount(findWorkTimeInfoCout(timeVO.getId()));
                            try {
                                timeVO.setWeekday(getDayForWeek(DateUtil.dateToStr(timeVO.getStartTime(),"yyyy-MM-dd")));
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            return timeVOs;
        }
        return null;
    }
    public Integer getDayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        Integer dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }
    /**
     * 查询医生列表带月份排班状态
     *
     * @param orgCode
     * @param dept
     * @param chargeType
     * @param date
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findDoctorWithMouthWork(String orgCode, String dept, String chargeType, String date, String nameKey, String iswork, Integer page, Integer size) {

        String totalSql = "SELECT " +
                " count(1) AS \"total\" " +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " JOIN base_doctor_role r ON r.doctor_code = d.id " +
                " WHERE  " +
                " h.org_code = '" + orgCode + "'" +
                " AND r.role_code ='specialist' and d.del=1 ";
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equalsIgnoreCase(chargeType)) {
                //不过滤号别
            } else {
                totalSql += " AND d.charge_type ='" + chargeType + "'";

            }
        } else {
            //不传号别过滤不为为空
            totalSql += " AND d.charge_type is not null ";
        }
        if (StringUtils.isNotBlank(dept)) {
            totalSql += " AND h.dept_code = '" + dept + "' ";
        }
        if (StringUtils.isNotBlank(nameKey)) {
            totalSql += " AND d.name like '%" + nameKey + "%' ";
        }
        //过滤排班
        if (StringUtils.isNotBlank(iswork)) {
            if ("1".equals(iswork)) {
                totalSql += " AND d.id IN ( " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
            } else {
                totalSql += " AND d.id NOT IN ( " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
            }

        }
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);

        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = hibenateUtils.objTransformLong(rstotal.get(0).get("total"));
        }

        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.expertise AS  \"expertise\"," +
                " d.introduce AS \"introduce\"," +
                " d.job_title_code AS \"jobTitleCode\", " +
                " d.job_title_name AS \"jobTitleName\"," +
                " d.charge_type AS \"chargeType\"," +
                " h.dept_code AS \"deptCode\"," +
                " h.dept_Name AS \"deptName\"" +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " JOIN base_doctor_role r ON r.doctor_code = d.id " +
                " WHERE  " +
                " h.org_code = '" + orgCode + "'" +
                " AND r.role_code ='specialist' and d.del=1 ";
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equalsIgnoreCase(chargeType)) {
                //不过滤号别
            } else {
                sql += " AND d.charge_type ='" + chargeType + "'";
            }
        } else {
            //不传号别过滤不为为空
            sql += " AND d.charge_type is not null ";
        }
        if (StringUtils.isNotBlank(dept)) {
            sql += " AND h.dept_code = '" + dept + "' ";
        }
        if (StringUtils.isNotBlank(nameKey)) {
            sql += " AND d.name like '%" + nameKey + "%' ";
        }
        //过滤排班
        if (StringUtils.isNotBlank(iswork)) {
            if ("1".equals(iswork)) {
                sql += " AND d.id IN ( " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
            } else {
                sql += " AND d.id NOT IN ( " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
            }

        }

        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, size);
        if (list != null && list.size() > 0) {
            //获取排班
            for (Map<String, Object> doctor : list) {
                String id = (String) doctor.get("id");
                List<WlyyDoctorWorkTimeDO> workTimeDOs = doctorWorkTimeDao.findDoctorWorkTimeByMonth(id, "%" + date + "%");
                if (workTimeDOs != null && workTimeDOs.size() > 0) {
                    doctor.put("isScheduling", true);
                } else {
                    doctor.put("isScheduling", false);
                }
            }
        }
        logger.info("findDoctorWithMouthWork :" + sql);
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    /**
     * 挂号
     *
     * @return
     */
    public net.sf.json.JSONObject registerOutPatient(String outPatientId, String doctor) throws Exception {

        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outPatientId);


        DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(doctor, outpatientDO.getHospital());
        if (doctorMappingDO == null) {
            throw new RuntimeException("未找到医生映射信息");
        }

        BasePatientDO basePatientDO = basePatientDao.findById(outpatientDO.getPatient());

        Integer manageType = 1;//处理类型（1-新增 2-修改 3-删除） 必填

        //查找居民当天挂号记录
        String date = DateUtil.dateToStr(new Date(), "yyyy-MM-dd");
        List<WlyyPatientRegisterDO> patientRegisterDOs = patientRegisterDao.findByPatientAndDateAndDoctorAndDel(outpatientDO.getPatient(), date, doctor,1);
        if (patientRegisterDOs != null && patientRegisterDOs.size() > 0) {
            WlyyPatientRegisterDO registerDO = patientRegisterDOs.get(0);
            //判断是否已经挂号，如果已经挂号
            if (StringUtils.isNotBlank(registerDO.getConNo()) && StringUtils.isNotBlank(registerDO.getRegisterNo())) {

                net.sf.json.JSONObject res = new JSONObject();
                res.put("@RESULT", "0");
                logger.info("已经挂号 res: " + res.toString());

                //更新挂号流水号
                outpatientDO.setConNo(registerDO.getConNo());
                outpatientDO.setRegisterNo(registerDO.getRegisterNo());
                outpatientDO.setAdmDate(registerDO.getCreateTime());
                outpatientDO.setXtgzh(registerDO.getXtgzh());
                outpatientDO.setRealOrder(registerDO.getRealOrder());
                outpatientDao.save(outpatientDO);
                //调用电子病历注册
                manageType = 2;
                try {
                    registDianziBingli(outpatientDO, basePatientDO, manageType, registerDO.getRegisterNo(), registerDO.getConNo());
                }catch (Exception e){
                    e.printStackTrace();
                }
                return res;
            }
        }
        //下载银医通
        net.sf.json.JSONObject object1 = entranceService.qutpatientBalance(outpatientDO.getCardNo(), demoFlag);
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        if (doctorDO == null) {
            throw new RuntimeException("未找到医生信息");
        }
        logger.info("下载银医通");
        String chargeType = "";
        if ("1".equalsIgnoreCase(outpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(outpatientDO.getType())){
            chargeType = doctorDO.getTwfzChargeType();
        }else if ("1".equalsIgnoreCase(outpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(outpatientDO.getType())){
            chargeType = doctorDO.getSpfzChargeType();
        }else if ("3".equalsIgnoreCase(outpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(outpatientDO.getType())){
            chargeType = doctorDO.getTwzxChargeType();
        }else if ("3".equalsIgnoreCase(outpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(outpatientDO.getType())){
            chargeType = doctorDO.getSpzxChargeType();
        }else if ("3".equalsIgnoreCase(outpatientDO.getOutpatientType())&&"3".equalsIgnoreCase(outpatientDO.getType())){
            chargeType = doctorDO.getJyzxChargeType();
        }else if ("2".equalsIgnoreCase(outpatientDO.getOutpatientType())){
            chargeType = doctorDO.getXtfzChargeType();
        }else {
            chargeType = doctorDO.getChargeType();
        }
        net.sf.json.JSONObject rs = entranceService.BS10111(outpatientDO.getCardNo(), doctorMappingDO.getMappingCode(), outpatientDO.getDept(), chargeType, outpatientDO.getWinNo(), demoFlag);
        net.sf.json.JSONObject res = rs.getJSONObject("resquest");
        logger.info("挂号结果 res: " + res.toString());
        String rsCode = res.getString("@RESULT");

        if ("0".equals(rsCode)) {
            //存储挂号号
            // {"resquest":{"@RESULT":"0","@MSG":"完成","@serial_no":"47770476","@times":"28"}}
            String serialNo = (String) res.get("@serial_no");
            outpatientDO.setRegisterNo(serialNo);
            String conNo = (String) res.get("@times");
            outpatientDO.setConNo(conNo);
            String xtgzh = (String) res.get("@xtgzh");
            String realOrder = (String) res.get("@real_order");
            outpatientDO.setXtgzh(xtgzh);
            outpatientDO.setRealOrder(realOrder);
            outpatientDO.setAdmDate(new Date());
            logger.info("挂号流水 @serial_no: " + serialNo + " @times: " + conNo);
            outpatientDao.save(outpatientDO);

            //存储就诊记录
            WlyyPatientRegisterDO registerDO = new WlyyPatientRegisterDO();
            // 存储挂号医生与挂号科室
            registerDO.setDoctor(outpatientDO.getDoctor());
            registerDO.setDoctorName(outpatientDO.getDoctorName());
            registerDO.setDept(outpatientDO.getDept());
            registerDO.setDeptName(outpatientDO.getDeptName());
            registerDO.setRealOrder(realOrder);
            registerDO.setXtgzh(xtgzh);
            registerDO.setPatient(outpatientDO.getPatient());
            registerDO.setPatientName(outpatientDO.getPatientName());
            //挂号流水号与挂号次数
            registerDO.setRegisterNo(serialNo);
            registerDO.setConNo(conNo);
            registerDO.setCreateTime(new Date());
            registerDO.setDel(1);
            registerDO.setDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
            patientRegisterDao.save(registerDO);

            //调用电子病历注册
            manageType = 1;//处理类型（1-新增 2-修改 3-删除） 必填
            registDianziBingli(outpatientDO, basePatientDO, manageType, registerDO.getRegisterNo(), registerDO.getConNo());

        } else if ("-2".equals(rsCode)) {

            String serialNo = (String) res.get("@serial_no");
            String xtgzh = (String) res.get("@xtgzh");
            String realOrder = (String) res.get("@real_order");
            outpatientDO.setRegisterNo(serialNo);
            String conNo = (String) res.get("@times");
            outpatientDO.setConNo(conNo);
            outpatientDO.setXtgzh(xtgzh);
            outpatientDO.setRealOrder(realOrder);
            outpatientDO.setAdmDate(new Date());
            logger.info("挂号流水 @serial_no: " + serialNo + " @times: " + conNo);
            outpatientDao.save(outpatientDO);

            //存储就诊记录
            WlyyPatientRegisterDO registerDO = new WlyyPatientRegisterDO();

            registerDO.setDoctor(outpatientDO.getDoctor());
            registerDO.setDoctorName(outpatientDO.getDoctorName());
            registerDO.setDept(outpatientDO.getDept());
            registerDO.setDeptName(outpatientDO.getDeptName());
            registerDO.setRealOrder(realOrder);
            registerDO.setXtgzh(xtgzh);
            registerDO.setPatient(outpatientDO.getPatient());
            registerDO.setPatientName(outpatientDO.getPatientName());
            registerDO.setRegisterNo(serialNo);
            registerDO.setConNo(conNo);
            registerDO.setCreateTime(new Date());
            registerDO.setDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));

            patientRegisterDao.save(registerDO);

            //调用电子病历注册
            manageType = 1;//处理类型（1-新增 2-修改 3-删除） 必填
            registDianziBingli(outpatientDO, basePatientDO, manageType, registerDO.getRegisterNo(), registerDO.getConNo());
        }


        //保存日志
        WlyyHttpLogDO log = new WlyyHttpLogDO();
        log.setCode("registerOutPatient");
        log.setName("挂号");
        log.setPatient(outpatientDO.getPatient());
        log.setDoctor(doctor);
        log.setResponse(rs.toString());
        log.setRequest("outPatientId=" + outPatientId + "&doctor=" + doctor);
        log.setStatus(rsCode);
        log.setCreateTime(new Date());
        wlyyHttpLogDao.save(log);
        return res;
    }

    public net.sf.json.JSONObject refundRegisterNo(String outpatientId) throws Exception {
        net.sf.json.JSONObject res = new net.sf.json.JSONObject();
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(outpatientId);
        if(outpatientDO!=null){
            DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(outpatientDO.getDoctor());
            if (StringUtils.isNoneBlank(outpatientDO.getRegisterNo())){
                net.sf.json.JSONObject rs = entranceService.BS10138(outpatientDO.getCardNo(), doctorMappingDO.getMappingCode(), outpatientDO.getDept(), outpatientDO.getRegisterNo(), outpatientDO.getWinNo(), demoFlag);
                res= rs.getJSONObject("resquest");
                logger.info("退号结果 res: " + res.toString());
                String rsCode = res.getString("@RESULT");
                if (rsCode.equalsIgnoreCase("0")){
                    WlyyPatientRegisterDO wlyyPatientRegisterDO = patientRegisterDao.findByRegisterNo(outpatientDO.getRegisterNo());
                    wlyyPatientRegisterDO.setDel(0);
                    patientRegisterDao.save(wlyyPatientRegisterDO);
                    outpatientDO.setHisStatus(-1);
                    outpatientDao.save(outpatientDO);
                }

                //保存日志
                WlyyHttpLogDO log = new WlyyHttpLogDO();
                log.setCode("refundregisterOutPatient");
                log.setName("退号");
                log.setPatient(outpatientDO.getPatient());
                log.setDoctor(outpatientDO.getDoctor());
                log.setResponse(rs.toString());
                log.setRequest("outPatientId=" + outpatientId + "&doctor=" + outpatientDO.getDoctor());
                log.setStatus(rsCode);
                log.setCreateTime(new Date());
                wlyyHttpLogDao.save(log);
                if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                    String type="";
                    if("1".equalsIgnoreCase(outpatientDO.getType())&&"1".equalsIgnoreCase(outpatientDO.getOutpatientType())){
                        type="9";
                    }else if("2".equalsIgnoreCase(outpatientDO.getType())&&"1".equalsIgnoreCase(outpatientDO.getOutpatientType())){
                        type="16";
                    }else if("1".equalsIgnoreCase(outpatientDO.getType())&&"3".equalsIgnoreCase(outpatientDO.getOutpatientType())){
                        type="1";
                    }
                    else if("2".equalsIgnoreCase(outpatientDO.getType())&&"3".equalsIgnoreCase(outpatientDO.getOutpatientType())){
                        type="17";
                    }
                    if (StringUtils.isNoneBlank(type)){
                        try {
                            sendWxTemplateMsg(wechatId, outpatientDO.getId(),null, type, "doctorRefund", "");
                            String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
                            sendZsMsgFlow("OL_YSTZ",outpatientDO.getId(),"",msgUrl,"医生退诊");
                        }catch (Exception e){
                            e.printStackTrace();
                        }


                    }
                }
            }
        }
        return  res;
    }

    public String registDianziBingli(WlyyOutpatientDO outpatientDO, BasePatientDO basePatientDO, Integer manageType, String RegisterSN, String registerCon) throws Exception {

        //调用电子病历接口注册居民信息
        String patientMappingCode = patientMappingService.findHisPatNoByIdCard(basePatientDO.getIdcard());
        DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
        Map<String, String> params = new HashedMap();
        params.put("type", "PatientInfo");

        String _xmlStr = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<HtRequest>" +
                "<OutRegister>" +
                "<RecordFlow>" + outpatientDO.getId() + "</RecordFlow>" +
                "<RegisterSN>" + RegisterSN + "</RegisterSN>" +
                "<TreatDate>" + DateUtil.getStringDate("yyyyMMdd") + "</TreatDate>" +
                "<RegisterDeptCode>" + outpatientDO.getDept() + "</RegisterDeptCode>" +
                "<RegisterDeptName>" + outpatientDO.getDeptName() + "</RegisterDeptName>" +
                "<RegisterDoctorID>" + doctorMappingDO.getMappingCode() + "</RegisterDoctorID>" +
                "<RegisterDoctorName>" + doctorMappingDO.getDoctorName() + "</RegisterDoctorName>" +
                "<DutyID></DutyID>" +
                "<DutyName></DutyName>" +
                "<OutPatientTime></OutPatientTime>" +
                "<NumClassCode></NumClassCode>" +
                "<NumClassName></NumClassName>" +
                "<JoinGroupCode></JoinGroupCode>" +
                "<JoinGroupName></JoinGroupName>" +
                "<NumClassNO></NumClassNO>" +
                "<AppointmentDateTime></AppointmentDateTime>" +
                "<AppointSN></AppointSN>" +
                "<Pid>" + patientMappingCode + "</Pid>" +
                "<CardNO>" + outpatientDO.getCardNo() + "</CardNO>\n" +
                "<PatientName>" + basePatientDO.getName() + "</PatientName>" +
                "<SexCode>" + basePatientDO.getSex() + "</SexCode>";
        if (basePatientDO.getSex()!=null&&1 == basePatientDO.getSex()) {
            _xmlStr = _xmlStr + "<Sex>男</Sex>";
        } else {
            _xmlStr = _xmlStr + "<Sex>女</Sex>";
        }
        _xmlStr = _xmlStr + "<Age>" + IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()) + "</Age>" +
                "<AgeDesc>" + IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()) + "岁</AgeDesc>" +
                "<PatientClass></PatientClass>" +
                "<FeeTypeCode></FeeTypeCode>" +
                "<FeeTypeName></FeeTypeName>" +
                "<MedicalInsuranceType></MedicalInsuranceType>" +
                "<IsFirst>N</IsFirst>" +
                "<RegisterDateTime>20200121</RegisterDateTime>" +
                "<RegisterUserID>" + patientMappingCode + "</RegisterUserID>" +
                "<RegisterUserName></RegisterUserName>" +
                "<OutStatus>20</OutStatus>" +
                "<ModifierID></ModifierID>" +
                "<Modifier></Modifier>" +
                "<ModifyTime></ModifyTime>" +
                "<RetreatDateTime></RetreatDateTime>" +
                "<RetreatUserID></RetreatUserID>" +
                "<RetreatUserName></RetreatUserName>" +
                "<PaymentMethodCode></PaymentMethodCode>" +
                "<PaymentMethod></PaymentMethod>" +
                "<RegisterFee></RegisterFee>" +
                "<MedicalFee></MedicalFee>" +
                "<OtherFee></OtherFee>" +
                "<TotalFee></TotalFee>" +
                "<MedicalFloor>N</MedicalFloor>" +
                "<MedicalAddress></MedicalAddress>" +
                "<LastDeptCode></LastDeptCode>" +
                "<LastDeptName></LastDeptName>" +
                "<LastDoctorID></LastDoctorID>" +
                "<LastDoctorName></LastDoctorName>" +
                "<LastTreatDateTime></LastTreatDateTime>" +
                "<LastOpid></LastOpid>" +
                "<NumTypeCode>0</NumTypeCode>" +
                "<NumTypeName></NumTypeName>" +
                "<RegisterSource>1</RegisterSource>" +
                "<AcctNO></AcctNO>" +
                "<IsAcct>N</IsAcct>" +
                "<ManageType>" + manageType + "</ManageType>" +
                "<Times>" + registerCon + "</Times>" +
                "</OutRegister>" +
                "<PatientInfo>" +
                "<RecordFlow>" + outpatientDO.getId() + "</RecordFlow>" +
                "<PID>" + patientMappingCode + "</PID></PatientInfo></HtRequest>";


//            String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
//                    "<HtRequest >" +
//                    "<PatientInfo>" +
//                    "<RecordFlow>"+outPatientId+"</RecordFlow >" +
//                    "<PID>"+patientMappingCode+"</PID>" +
//                    "<InsuranceNo>"+basePatientDO.getIdcard()+"</InsuranceNo>" +
//                    "<PatientName>"+basePatientDO.getName()+"</PatientName>" +
//                    "<TmpFlag>正式</TmpFlag>" +
//                    "<LastName>"+basePatientDO.getName().substring(1,basePatientDO.getName().length())+"</LastName>" +
//                    "<FirstName>"+basePatientDO.getName().substring(0,1)+"</FirstName>" +
//                    "<PY>"+ PinYinUtils.getUpEname(basePatientDO.getName())+"</PY>" +
//                    "<WB></WB>" +
//                    "<SexCode>"+basePatientDO.getSex()+"</SexCode>";
//            if(1 == basePatientDO.getSex()){
//                xmlStr = xmlStr + "<Sex>男</Sex>";
//            }else{
//                xmlStr = xmlStr +  "<Sex>女</Sex>";
//            }
//
//            xmlStr = xmlStr +    "<DateOfBirth>"+DateUtil.dateToStrShort(IdCardUtil.getBirthdayForIdcard(basePatientDO.getIdcard()))+"</DateOfBirth>" +
//                    "<TimeOfBirth></TimeOfBirth>" +
//                    "<MarriageStatusCode></MarriageStatusCode>" +
//                    "<MarriageStatus></MarriageStatus>" +
//                    "<OccupationCode></OccupationCode>" +
//                    "<Occupation></Occupation>" +
//                    "<NationalityCode></NationalityCode>" +
//                    "<Nationality></Nationality>" +
//                    "<CountryCode>CN</CountryCode>" +
//                    "<Country>中国</Country>" +
//                    "<FormalSchoolingCode></FormalSchoolingCode>" +
//                    "<FormalSchooling></FormalSchooling>" +
//                    "<Religion></Religion>" +
//                    "<BirthPlaceCode></BirthPlaceCode>" +
//                    "<BirthPlace></BirthPlace>" +
//                    "<NativePlaceCode></NativePlaceCode>" +
//                    "<NativePlace></NativePlace>" +
//                    "<BloodType></BloodType>" +
//                    "<CertTypeCode>111</CertTypeCode>" +
//                    "<CertType>身份证</CertType>" +
//                    "<CertNo>"+basePatientDO.getIdcard()+"</CertNo>" +
//                    "<PatientClassCode></PatientClassCode>" +
//                    "<PatientClass></PatientClass>" +
//                    "<FeeTypeCode></FeeTypeCode>" +
//                    "<FeeType></FeeType>" +
//                    "<Company></Company>" +
//                    "<PublicExpenseNo></PublicExpenseNo>" +
//                    "<ContractUnitCode></ContractUnitCode> " +
//                    "<ContractUnit></ContractUnit>" +
//                    "<BusinessAddressCode></BusinessAddressCode>" +
//                    "<BusinessAddress></BusinessAddress>" +
//                    "<BusinessPostCode></BusinessPostCode>" +
//                    "<BusinessPhone></BusinessPhone>" +
//                    "<HomeAddressCode></HomeAddressCode>" +
//                    "<HomeAddress></HomeAddress>" +
//                    "<HomePostCode></HomePostCode>" +
//                    "<MobilePhone></MobilePhone>" +
//                    "<Contact></Contact>" +
//                    "<RelationCode></RelationCode>" +
//                    "<Relation></Relation>" +
//                    "<ContactEmail></ContactEmail>" +
//                    "<ContactMethod></ContactMethod>" +
//                    "<VIPType></VIPType>" +
//                    "<OperatorID></OperatorID>" +
//                    "<Operator></Operator>" +
//                    "<OperatorTime>0</OperatorTime>" +
//                    "<Available></Available>" +
//                    "<ManageType>"+manageType+"</ManageType>" +
//                    "<InsuranceTypeCode></InsuranceTypeCode>" +
//                    "<InsuranceType></InsuranceType>" +
//                    "<RegisteredAddressCode></RegisteredAddressCode>" +
//                    "<RegisteredAddress></RegisteredAddress>" +
//                    "<ContactAddressCode></ContactAddressCode>" +
//                    "<ContactAddress></ContactAddress>" +
//                    "<RegisteredPostCode></RegisteredPostCode>" +
//                    "<ContactPostcode></ContactPostcode>" +
//                    "<BloodType></BloodType>" +
//                    "<RhBloodType></RhBloodType>" +
//                    "</PatientInfo>" +
//                    "</HtRequest>";
        String returnValue = "";
        params.put("xmlStr", _xmlStr);

        returnValue = WebserviceUtil.post("http://192.10.33.34:9080/HtMzWebService/services/Manage",
                "http://business.htemr.haitaiinc.com",
                "manageAdt",
                params);

        logger.info("调用电子病历注册接口请求成功，返回值xmlstr:" + returnValue);

        return returnValue;
    }

    /**
     * 获取诊断
     *
     * @param pyKey
     * @return
     * @throws Exception
     */
    public JSONArray getICD10(String pyKey) throws Exception {
        return entranceService.MS25001(pyKey, demoFlag);
    }

    /**
     * 获取药品
     *
     * @return
     */
    public JSONArray getDrugDictionary(String chargeCode, String pyKey, String winNo, String groupNo) throws Exception {
        return entranceService.MS53001(chargeCode, pyKey, "0", winNo, "0", groupNo, demoFlag);
    }

    /**
     * 获取药品用法
     */
    public JSONArray getDrugUse(String drugNo, String pyKey) throws Exception {
        return entranceService.BS10110(drugNo, pyKey, demoFlag);
    }

    /**
     * 医院频次
     *
     * @return
     */
    public JSONArray getDrugFrequency() throws Exception {
        return entranceService.MS30012(demoFlag);
    }

    /**
     * 检查模板选择接口
     *
     * @param bz_code
     * @param flag
     * @return
     * @throws Exception
     */
    public JSONArray getJcmb(String bz_code, String tc_no, String flag) throws Exception {
        return entranceService.BS25033(bz_code, tc_no, flag, demoFlag);

    }

    /**
     * 检验选择接口
     *
     * @param bz_code
     * @param flag
     * @return
     * @throws Exception
     */
    public JSONArray getJymb(String bz_code, String tc_no, String flag) throws Exception {
        return entranceService.BS20030(bz_code, tc_no, flag, demoFlag);
    }

    /**
     * 套餐选择接口
     *
     * @param bz_code
     * @param flag
     * @return
     * @throws Exception
     */
    public JSONArray getTcxz(String bz_code, String tc_no, String flag) throws Exception {
        return entranceService.MS02017(bz_code, tc_no, flag, demoFlag);

    }

    /**
     * 套餐子项目接口
     *
     * @param parent_code 检查检验项目的charge_code
     * @return
     * @throws Exception
     */
    public JSONArray getTcChild(String parent_code) throws Exception {
        return entranceService.MS02015(parent_code, demoFlag);
    }

    /**
     * 项目子项目接口
     *
     * @param zd_charge_code
     * @return
     * @throws Exception
     */
    public JSONArray getInsChild(String zd_charge_code) throws Exception {
        return entranceService.MS02016(zd_charge_code, demoFlag);
    }


    /**
     * 获取检查检验
     *
     * @return
     */
    public JSONArray getInspectionDictionary(String pyKey, String codes, String winNo) throws Exception {
        JSONArray rs = entranceService.MS25002(pyKey, codes, winNo, demoFlag);
        if (rs != null && rs.size() > 0) {

            //设置科室翻译名称字典，减少循环层级降低循环次数
            List<DictHospitalDeptDO> depts = dictHospitalDeptDao.findByOrgCode("350211A1002");
            Map<String, String> deptDictMap = new HashedMap();
            for (DictHospitalDeptDO dp : depts) {
                deptDictMap.put(dp.getCode(), dp.getName());
            }

            //翻译执行科室
            for (int i = 0; i < rs.size(); i++) {
                JSONObject dict = (JSONObject) rs.get(i);
                String dept = dict.getString("exec_unit");
                if (StringUtils.isNotBlank(dept)) {
                    String deptName = deptDictMap.get(dept);
                    if (StringUtils.isNotBlank(deptName)) {
                        dict.put("exec_unit_name", deptName);
                    } else {
                        dict.put("exec_unit_name", "");
                    }
                }
            }
        }
        return rs;
    }

    /**
     * 下诊断，线上开方
     *
     * @param outPatientId
     * @param advice
     * @param type          1带处方，2不带处方
     * @param infoJsons
     * @param diagnosisJson
     * @return
     */
    public Map<String, Object> makeDiagnosis(String outPatientId,String prescriptionId, String advice, String type, String infoJsons, String diagnosisJson, String inspectionJson, String emrJson,String hisId) throws Exception {

        Map<String, Object> result = new HashedMap();

        //获取门诊记录
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outPatientId);
        //设置医嘱
        outpatientDO.setAdvice(advice);

        //========================处方操作=============================================================
        //创建处方记录
        WlyyPrescriptionDO  prescriptionDO= new WlyyPrescriptionDO();
        /*List<WlyyPrescriptionDO> prescriptionDOs = prescriptionDao.findByOutpatientId(outPatientId);*/
        List<WlyyPrescriptionDO> wlyyPrescriptionDO1 = new ArrayList<>();
        if(StringUtils.isNotBlank(prescriptionId)){
            wlyyPrescriptionDO1 = prescriptionDao.findById(prescriptionId);
            prescriptionDO =wlyyPrescriptionDO1.get(0);
        }else{
            if (StringUtils.isNotBlank(hisId)){
                prescriptionDO.setHisId(hisId);
            }
            prescriptionDO.setOutpatientId(outPatientId);
            prescriptionDO.setType(1);
            prescriptionDO.setDept(outpatientDO.getDept());
            prescriptionDO.setCreateTime(new Date());
            prescriptionDO.setDeptName(outpatientDO.getDeptName());
            prescriptionDO.setHospital(outpatientDO.getHospital());
            prescriptionDO.setHospitalName(outpatientDO.getHospitalName());
            prescriptionDO.setStatus(10);
            prescriptionDO.setIdcard(outpatientDO.getIdcard());
            prescriptionDO.setPatientCode(outpatientDO.getPatient());
            prescriptionDO.setPatientName(outpatientDO.getPatientName());
            prescriptionDO.setDoctor(outpatientDO.getDoctor());
            prescriptionDO.setDoctorName(outpatientDO.getDoctorName());
            prescriptionDO.setPayStatus(0);
            if (wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
                prescriptionDO.setAdmNo(outpatientDO.getAdmNo());
            }
        }

        WlyyPrescriptionDO prescription = prescriptionDao.save(prescriptionDO);

        //========================处方操作结束=============================================================
        if(!StringUtils.isNotBlank(prescriptionId)){
            //加入处方状态变更流水日志
            prescriptionLogService.addPrescriptionLog(prescription.getId(), 10, 2, outpatientDO.getDoctor(), outpatientDO.getDoctorName(), "", new Date());
        }


        //============================下诊断==============================================================
        //删除之前诊断
        List<WlyyPrescriptionDiagnosisDO> ds = prescriptionDiagnosisDao.findByPrescriptionId(prescription.getId(), 1);
        if (ds != null && ds.size() > 0) {
            prescriptionDiagnosisDao.deleteByPrescriptionId(prescription.getId());
        }

        List<WlyyPrescriptionDiagnosisDO> diagnosisDOs = (List<WlyyPrescriptionDiagnosisDO>) com.alibaba.fastjson.JSONArray.parseArray(diagnosisJson, WlyyPrescriptionDiagnosisDO.class);
        String Icd10 = "";
        String Icd10Name = "";
        for (WlyyPrescriptionDiagnosisDO diagnosisDO : diagnosisDOs) {
            if ("1".equals(diagnosisDO.getType())) {
                Icd10 = diagnosisDO.getCode() + "," + Icd10;
                Icd10Name += diagnosisDO.getName() + "," + Icd10Name;
            } else {
                Icd10 += diagnosisDO.getCode() + ",";
                Icd10Name += diagnosisDO.getName() + ",";
            }
            diagnosisDO.setDel(1);
            diagnosisDO.setPrescriptionId(prescription.getId());
        }
        prescriptionDiagnosisDao.save(diagnosisDOs);

        //存储icd10
        Icd10 = Icd10.substring(0, Icd10.length() - 1);
        Icd10Name = Icd10Name.substring(0, Icd10Name.length() - 1);
        outpatientDO.setIcd10(Icd10);
        outpatientDO.setIcd10Name(Icd10Name);
        outpatientDao.save(outpatientDO);
        //============================下诊断end==============================================================

        //=====================电子病历=================================================start
        prescriptionEmrDao.deleteByPrescriptionId(prescription.getId());
        if (StringUtils.isNotBlank(emrJson)) {
            WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = com.alibaba.fastjson.JSONObject.parseObject(emrJson, WlyyPrescriptionEmrDO.class);
            wlyyPrescriptionEmrDO.setDel(1);
            wlyyPrescriptionEmrDO.setPrescriptionId(prescription.getId());
            prescriptionEmrDao.save(wlyyPrescriptionEmrDO);
        }

        //=====================电子病历=================================================end
        //=====================保存日志 start=========================================================
        List<WlyyPrescriptionCheckDO> prescriptionCheckDOS = prescriptionCheckDao.findByStatus(prescription.getId(), 5);
        if (prescriptionCheckDOS == null || prescriptionCheckDOS.size() == 0) {
            savePrescriptionCheck(prescription.getDoctor(), "草稿", 6, prescription.getId());
        }



        //=====================保存日志 end=========================================================
        //判断是否有检查检验或药品开方
        if ("1".equals(type)) {

            //doctor转换为his医生
            DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
            if (doctorMappingDO == null) {
                throw new RuntimeException("未找到医生映射信息");
            }


            //===================药品操作======================================================
            // 删除原有药品信息
            List<WlyyPrescriptionInfoDO> oldInfos = prescriptionInfoDao.findByPrescriptionId(prescription.getId(), 1);
            if (oldInfos != null && oldInfos.size() > 0) {
                prescriptionInfoDao.deleteByPrescriptionId(prescription.getId());
            }

            //存储药品，构建his开方入参
            if (StringUtils.isNotBlank(infoJsons)) {
                //药品
                List<WlyyPrescriptionInfoDO> infoDOs = (List<WlyyPrescriptionInfoDO>) com.alibaba.fastjson.JSONArray.parseArray(infoJsons, WlyyPrescriptionInfoDO.class);

                for (WlyyPrescriptionInfoDO info : infoDOs) {

                    info.setDel(1);
                    info.setPrescriptionId(prescription.getId());


                }
                //保存药品信息
                prescriptionInfoDao.save(infoDOs);
                logger.info("123");
                Double price = getInfoFee(infoDOs);
                logger.info("12312313213" + price);
                //计算药品费用
                prescription.setDrugFee(price);
            }
            //=====================药品操作=======================================================================


            //=====================检查检验=======================================================================
            //存储检查检验,构建his开方入参
            //删除之前检查检验
            List<WlyyInspectionDO> inspectionDels = wlyyInspectionDao.findByOutpatientId(outPatientId);
            if (inspectionDels != null && inspectionDels.size() > 0) {
                wlyyInspectionDao.deleteByPrescriptionId(prescription.getId());
            }

            if (StringUtils.isNotBlank(inspectionJson)) {
                List<WlyyInspectionDO> inspections = (List<WlyyInspectionDO>) com.alibaba.fastjson.JSONArray.parseArray(inspectionJson, WlyyInspectionDO.class);
                for (WlyyInspectionDO ins : inspections) {
                    ins.setDel(1);
                    ins.setCreateTime(new Date());
                    ins.setPrescriptionId(prescription.getId());
                    ins.setOutpatientId(outPatientId);
                    /*if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                        String code = ins.getCode();
                        com.alibaba.fastjson.JSONArray jsonArray = ykyyEntranceService.findZlxm("",code,"","","");
                        if (jsonArray!=null&&jsonArray.size()>0){
                            com.alibaba.fastjson.JSONObject deptobject = jsonArray.getJSONObject(0);
                            String deptNo = deptobject.getString("dept");
                            ins.setDept(StringUtils.isNoneBlank(ins.getDept())?ins.getDept():deptNo);
                            String yqdm = deptobject.getString("yqdm");
                            ins.setOrgCode(StringUtils.isNoneBlank(ins.getOrgCode())?ins.getOrgCode():yqdm);
                            ins.setOrgName("1001".equalsIgnoreCase(ins.getOrgCode())?"思北院区":"五缘院区");
                        }
                    }*/
                    System.out.println("____outpatientId=="+outPatientId);
                }
                //保存检查检验。
                wlyyInspectionDao.save(inspections);


                //计算检查检验费用
                prescription.setInspectFee(getInsFee(inspections));
            }
            //=====================检查检验=======================================================================


            //保存挂号费用
            prescription.setRegFee(outpatientDO.getFee());
            prescription.setPrescribeTime(new Date());
            //保存费用
            prescription = prescriptionDao.save(prescription);
            if (wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
                outpatientDO.setStatus("2");
                outpatientDao.save(outpatientDO);
                //先下单
                businessOrderService.savePrescriptionOrder(prescription.getId());
                /*if(!demoFlag) {
                    //同步his
                    ykyyEntranceService.findByRealOrder(prescription.getId(), demoFlag);
                    List<WlyyPrescriptionDO> prescriptionDOList = prescriptionDao.findById(prescription.getId());
                    if (prescriptionDOList != null && prescriptionDOList.size() != 0) {
                        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDOList.get(0);
                        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientDO.getId());
                        logger.info("cfsb", wlyyPrescriptionDO.getRealOrder());
                        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKTCONTROL");
                        if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

                        } else {
                            ykyyService.updateDrugorderInfo(businessOrderDO.getOrderNo(), wlyyPrescriptionDO.getOrderId(), wlyyPrescriptionDO.getRealOrder());
                        }
                        List<WlyyPrescriptionInfoDO> list = prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
                        if (list!=null&&list.size()>0){
                            ykyySMSService.sendSmsByTempcode("prescription_remind", outpatientDO, wlyyPrescriptionDO, "");
                        }
                    }
                }*/
                /*if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                    if (StringUtils.isNotBlank(inspectionJson)) {
                        if (StringUtils.isNotBlank(infoJsons)) {
                            List<WlyyPrescriptionInfoDO> infoDOs = (List<WlyyPrescriptionInfoDO>) com.alibaba.fastjson.JSONArray.parseArray(infoJsons, WlyyPrescriptionInfoDO.class);
                            if (infoDOs != null && infoDOs.size() > 0) {

                            } else {
                                prescription.setStatus(20);
                            }
                        } else {
                            prescription.setStatus(20);

                            sendWxTemplateMsg(wechatId, outpatientDO.getId(), null, "", "prescriptionPayRemind", prescription.getId());
                        }
                    }
                }*/
                prescriptionDao.save(prescription);
                result.put("code", 1);
                result.put("mes", "诊断完成");
                result.put("prescriptionId",prescription.getId());
                return result;
            }else if (wechatId.equalsIgnoreCase("sd_tnzyy_wx")) {
                outpatientDO.setStatus("2");
                outpatientDao.save(outpatientDO);
                logger.info("开始同步");
                //先下单
                businessOrderService.savePrescriptionOrder(prescription.getId());
                if(!demoFlag){
                    //同步his
                    tnyyEntranceService.findByRealOrder(prescription.getId(),demoFlag);
                    List<WlyyPrescriptionDO> prescriptionDOList = prescriptionDao.findById(prescription.getId());
                    if (prescriptionDOList != null && prescriptionDOList.size() != 0) {
                        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDOList.get(0);
                        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientDO.getId());
                        logger.info("cfsb", wlyyPrescriptionDO.getRealOrder());
                    }
                }
                result.put("code", 1);
                result.put("mes", "诊断完成");
                result.put("prescriptionId",prescription.getId());
                return result;
            } else if (wechatId.equalsIgnoreCase("xm_zsyy_wx")) {
                Double price = prescription.getDrugFee();
                businessOrderService.recharge(prescription.getId(), "处方收费", "4", "处方收费", prescription.getPatientCode(), prescription.getPatientName(), prescription.getDoctor(), price);
                //上传his开方
                //sendHisDiagnosis(jsonData, outpatientDO, prescription)
                //zsSynHis(prescription.getId());
                Map<String, Object> result1 = new HashedMap();
                result1.put("code", 1);
                result1.put("mes", "开方提交成功");
                result1.put("prescriptionId",prescription.getId());
                return result1;
            } else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")) {
                Double price = prescription.getDrugFee();
                businessOrderService.recharge(prescription.getId(), "处方收费", "4", "处方收费", prescription.getPatientCode(), prescription.getPatientName(), prescription.getDoctor(), price);
                //上传his开方
                //sendHisDiagnosis(jsonData, outpatientDO, prescription)
                //zsSynHis(prescription.getId());
                //同步检查检验
                List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescription.getId(),1);
                if (inspectionDOS != null && inspectionDOS.size() > 0) {
                    syCheckParam(outpatientDO.getId());
                }
                Map<String, Object> result1 = new HashedMap();
                result1.put("code", 1);
                result1.put("mes", "开方提交成功");
                result1.put("prescriptionId",prescription.getId());
                return result1;
            }else {
                result.put("code", 1);
                result.put("mes", "诊断完成");
                result.put("prescriptionId",prescription.getId());
                return result;
            }


        } else {
            outpatientDO.setStatus("2");
            outpatientDao.save(outpatientDO);
            result.put("code", 1);
            result.put("mes", "诊断完成");
            result.put("prescriptionId",prescription.getId());
            return result;
        }


    }
    /**
     * 组装检查检验项目参数
     *
     * @param outpatientId
     * @return
     */
    public void syCheckParam(String outpatientId) throws  Exception{
        String condition ="";
        condition = "<IoFlag>"+0+"</IoFlag>";
        StringBuffer inspectionList = new StringBuffer();
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(outpatientId);
        String applyDoctor = "";
        if (null!=outpatientDO){
            DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(outpatientDO.getDoctor());
            if (null!=doctorMappingDO){
                applyDoctor = doctorMappingDO.getMappingCode();
            }
            condition += "<PayCardNo>"+outpatientDO.getCardNo()+"</PayCardNo>";
            condition += "<NullahNumber>"+outpatientDO.getRegisterNo()+"</NullahNumber>";
            condition += "<ApplyDept>"+outpatientDO.getDept()+"</ApplyDept>";
            condition += "<ApplyDoctor>"+applyDoctor+"</ApplyDoctor>";
            List<WlyyInspectionDO>  wlyyInspectionDOS = wlyyInspectionDao.findByOutpatientId(outpatientDO.getId());
            String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<root>"+condition+"</root>";
            Map resultMap =  xzzxEntranceService.checkSyncHis("0",outpatientDO.getCardNo(),outpatientDO.getRegisterNo(),outpatientDO.getDept(),applyDoctor,wlyyInspectionDOS.toString());
            logger.info("同步his检查检验返回结果："+resultMap.get("success"));
        }

    }

    /**
     * 计算药品费用
     *
     * @param infoDOs
     * @return
     */
    public Double getInfoFee(List<WlyyPrescriptionInfoDO> infoDOs) {
        DecimalFormat df = new DecimalFormat("#.00");
        Double fee = 0D;
        if (infoDOs != null && infoDOs.size() > 0) {

            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);
                BigDecimal total = new BigDecimal(0);
                BigDecimal quantity = new BigDecimal(info.getQuantity());
                BigDecimal price = new BigDecimal(info.getPackRetprice());
                total = total.add(quantity.multiply(price));
                Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                fee += f1;
            }
            logger.error("getInfoFee===========:" + fee);
        }
        return fee;
    }

    /**
     * 计算检查检验费用
     *
     * @param inspections
     * @return
     */
    public Double getInsFee(List<WlyyInspectionDO> inspections) {
        DecimalFormat df = new DecimalFormat("#.00");
        Double fee = 0D;
        try {
            if (inspections != null && inspections.size() > 0) {
                for (WlyyInspectionDO ins : inspections) {
              /*      Double chargeAmount = Double.parseDouble(ins.getChargeAmount());
                    fee += chargeAmount * ins.getQuantity();*/
                    BigDecimal total = new BigDecimal(0);
                    BigDecimal quantity = new BigDecimal(ins.getChargeAmount());
                    BigDecimal price = new BigDecimal(ins.getQuantity());
                    total = total.add(quantity.multiply(price));
                    Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    fee += f1;
                }
            }
        } catch (Exception e) {
            logger.error("getInsFee:" + e.toString());
        }
        fee = Double.parseDouble(df.format(fee));
        return fee;
    }

    /**
     * 计算挂号费用
     *
     * @param doctor
     * @return
     */
    public Double getChargeFee(String doctor) {
        DecimalFormat df = new DecimalFormat("0.00");
        Double fee = 0D;
        try {
            BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
            WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getChargeType(), "6");

            return chargeDictDO.getReqFee();
        } catch (Exception e) {
            logger.error("getChargeFee:" + e.toString());

        }
        fee = Double.parseDouble(df.format(fee));
        return fee;
    }

    /**
     * 上传his开方
     *
     * @param jsonData
     * @param outpatientDO
     * @param prescription
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendHisDiagnosis(com.alibaba.fastjson.JSONArray jsonData, WlyyOutpatientDO outpatientDO, WlyyPrescriptionDO prescription) throws Exception {
        Map<String, Object> result = new HashedMap();
        //调用his开方接口
        net.sf.json.JSONObject jsonObject = entranceService.BS10112(jsonData.toJSONString(), demoFlag);
        //如果无法解析his系统报文，his系统报错
        if (jsonObject == null) {
            //记录http日志
            WlyyHttpLogDO log = new WlyyHttpLogDO();
            log.setCode("makeDiagnosis");
            log.setName("下诊断");
            log.setPatient(outpatientDO.getPatient());
            log.setDoctor(outpatientDO.getDoctor());
            log.setResponse("his系统异常，无法解析返回值");
            log.setRequest(jsonData.toJSONString());
            log.setStatus("-99");
            log.setCreateTime(new Date());
            wlyyHttpLogDao.save(log);
            //开方失败
            //更新处方状态
            prescription.setStatus(13);
            prescriptionDao.save(prescription);
            //记录开发失败日志
            prescriptionLogService.addPrescriptionLog(prescription.getId(), 13, 2, outpatientDO.getDoctor(), outpatientDO.getDoctorName(), "", new Date());
            //开方失败返回值
            result.put("code", -1);
            result.put("mes", "开方失败，his系统异常");

            return result;
        }

        logger.info("调用his开方接口: " + jsonObject.toString());
        //判断返回结果
        String rs = jsonObject.getString("@RESULT");
        //保存日志
        WlyyHttpLogDO log = new WlyyHttpLogDO();
        log.setCode("makeDiagnosis");
        log.setName("下诊断");
        log.setPatient(outpatientDO.getPatient());
        log.setDoctor(outpatientDO.getDoctor());
        log.setResponse(jsonObject.toString());
        log.setRequest(jsonData.toJSONString());
        log.setStatus(rs);
        log.setCreateTime(new Date());
        wlyyHttpLogDao.save(log);

        if ("0".equals(rs)) {
            String admNo = jsonObject.getString("@ADM_NO");
            String realOrder = jsonObject.getString("@real_order");
            String voucherNo = jsonObject.getString("@xtgzh0");
            prescription.setAdmNo(admNo);
            prescription.setRealOrder(realOrder);
            prescription.setVoucherNo(voucherNo);
            prescriptionDao.save(prescription);
            outpatientDO.setAdmNo(admNo);
            outpatientDao.save(outpatientDO);

            result.put("code", 1);
            result.put("voucherNo", voucherNo);
            result.put("mes", "开方提交成功");

            return result;
        } else {
            //开方失败
            result.put("code", -1);
            result.put("mes", jsonObject.getString("@MSG"));
            //更新处方状态
            prescription.setStatus(13);
            prescriptionDao.save(prescription);
            //记录开发失败日志
            prescriptionLogService.addPrescriptionLog(prescription.getId(), 13, 2, outpatientDO.getDoctor(), outpatientDO.getDoctorName(), "", new Date());

            return result;
        }
    }

    /**
     * 设置检查检验his入参
     *
     * @param jsonData
     * @param doctorMappingDO
     * @param outpatientDO
     * @param inspectionDO
     * @param Icd10
     */
    public void setInspectionParam(com.alibaba.fastjson.JSONArray jsonData, DoctorMappingDO doctorMappingDO, WlyyOutpatientDO outpatientDO, WlyyPrescriptionDO prescriptionDO, WlyyInspectionDO inspectionDO, String Icd10) {

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        if (StringUtils.isNotBlank(prescriptionDO.getRealOrder())) {
            json.put("realOrder", prescriptionDO.getRealOrder());
        }
        json.put("cardNo", outpatientDO.getCardNo());
        json.put("doctor", doctorMappingDO.getMappingCode());
        json.put("dept", outpatientDO.getDept());

        json.put("frequency", inspectionDO.getFrequency()); //组号
        json.put("quantity", inspectionDO.getQuantity()); //数量
        json.put("serialNo", outpatientDO.getRegisterNo()); //挂号流水号-必输
        json.put("groupNo", "00"); //-库房号
        json.put("serial", "00"); //药品序列号-必输

        json.put("winNo", outpatientDO.getWinNo());
        json.put("chargeFlag", 2); //项目类别-必输  1-药品 2检验检查
        /**
         *  code;//项目编码',
         *  name;//(检查方法)',
         *  information;//病史与体征',
         *  checkEquip;//类别',
         *  checkPart;//部位',
         *  adresult;//辅助检查治疗',
         *  goal;//检查目的',
         *  opview;//手术所见-病理申请单必填',
         *  specimenName;//标本名称-病理申请单必填',
         *  specimenNum;//标本数量-病理申请单必填',
         *  ywjcResult;//以往检查结果-病理申请单选填',
         *  ywjcDate;//以往检查时间-病理申请单选填 格式：yyyy-mm-dd',
         *  blzd;//病理诊断-病理申请单选填',
         *  fixationfluid;//固定液
         */
        json.put("parentCode", inspectionDO.getParentCode()); //父节点
        json.put("chargeCode", inspectionDO.getCode()); //项目编码
        json.put("name", inspectionDO.getName()); //挂号流水号-必输
        json.put("information", inspectionDO.getInformation());//库房号-必输
        json.put("checkEquip", inspectionDO.getCheckEquip()); //药品序列号-必输
        json.put("checkPart", inspectionDO.getCheckPart());
        json.put("adresult", inspectionDO.getAdresult());
        json.put("goal", inspectionDO.getGoal());
        json.put("opview", inspectionDO.getOpview());
        json.put("specimenName", inspectionDO.getSpecimenName());
        json.put("specimenNum", inspectionDO.getSpecimenNum());
        json.put("ywjcResult", inspectionDO.getYwjcResult());
        json.put("ywjcDate", inspectionDO.getYwjcDate());
        json.put("blzd", inspectionDO.getBlzd());
        json.put("fixationfluid", inspectionDO.getFixationfluid());
        //设置诊断
        setIcd10(json, Icd10);
        jsonData.add(json);
        logger.info("json:" + json.toString());
    }

    /**
     * 设置药品his入参
     *
     * @param jsonData
     * @param doctorMappingDO
     * @param outpatientDO
     * @param info
     * @param Icd10
     */
    public void setInfoJsonParam(com.alibaba.fastjson.JSONArray jsonData, DoctorMappingDO doctorMappingDO, WlyyOutpatientDO outpatientDO, WlyyPrescriptionDO prescriptionDO, WlyyPrescriptionInfoDO info, String Icd10) {

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();

        if (StringUtils.isNotBlank(prescriptionDO.getRealOrder())) {
            json.put("realOrder", prescriptionDO.getRealOrder());
        }
        json.put("cardNo", outpatientDO.getCardNo());
        json.put("doctor", doctorMappingDO.getMappingCode());
        json.put("dept", outpatientDO.getDept());
        json.put("chargeCode", info.getDrugNo());
        json.put("winNo", outpatientDO.getWinNo());
        json.put("chargeFlag", 1); //项目类别-必输  1-药品 2检验检查
        json.put("quantity", info.getQuantity()); //数量-必输
        json.put("serialNo", outpatientDO.getRegisterNo()); //挂号流水号-必输
        json.put("groupNo", info.getGroupNo());//库房号-必输
        json.put("serial", info.getSerial()); //药品序列号-必输

        json.put("dosage", info.getDosage());
        json.put("unit", info.getUnit());
        json.put("usage", info.getUsageCode());
        json.put("supplyCode", info.getSupplyCode());
        if (StringUtils.isNotBlank(info.getDays())) {
            json.put("days", info.getDays());
        } else {
            //如果是中草药，贴数为天数，没有默认1天
            json.put("days", StringUtils.isNotBlank(info.getPostCount()) ? info.getPostCount() : "1");
        }
        json.put("frequency", info.getFrequency());
        json.put("comm", info.getComm());

        //设置诊断
        setIcd10(json, Icd10);

        jsonData.add(json);
        logger.info("json:" + json.toString());
    }

    public void setIcd10(com.alibaba.fastjson.JSONObject json, String Icd10) {
        String Icd10s[] = Icd10.split(",");
        for (int i = 0; i < Icd10s.length; i++) {
            if (i == 0) {
                json.put("icdCode", Icd10s[i]);
            } else if (i == 1) {
                json.put("diagTwo", Icd10s[i]);
            } else if (i == 2) {
                json.put("diagThree", Icd10s[i]);
            } else if (i == 3) {
                json.put("diagFour", Icd10s[i]);
            } else if (i == 4) {
                json.put("diagFive", Icd10s[i]);
            }
        }
    }

    /**
     * 导出订单查询
     *
     * @param status
     * @param oneselfPickupFlg
     * @param nameKey
     * @param startTime
     * @param endTime
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop  findExpressageList2(String status, String oneselfPickupFlg, String nameKey, String startTime, String endTime, Integer page, Integer size, String wxId,String patientName) {
        /*String totalSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wlyy_outpatient o " +
                " JOIN wlyy_prescription p ON p.outpatient_id = o.id " +
                " JOIN wlyy_prescription_expressage e ON e.outpatient_id = o.id" +
                " WHERE" +
                " 1=1 ";
        if (StringUtils.isNotBlank(status)) {
            totalSql += " AND p.status in(" + status + ") ";
        }
        if (StringUtils.isNotBlank(oneselfPickupFlg)) {
            totalSql += " AND e.oneself_pickup_flg = " + oneselfPickupFlg+" ";
        }
        if (StringUtils.isNotBlank(nameKey)) {
            totalSql += " AND e.name like '%" + nameKey + "%' ";
        }
        if (StringUtils.isNotBlank(patientName)) {
            totalSql += " AND o.patient_name like '%" + patientName + "%' ";
        }
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    totalSql += " and p.create_time >= str_to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    totalSql += " and p.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }
            } else {
                totalSql += " AND p.create_time >='" + startTime + " 00:00:00'";
            }

        }
        if (StringUtils.isNotBlank(endTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    totalSql += " and p.create_time <= str_to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    totalSql += " and p.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }
            } else {
                totalSql += " AND p.create_time <='" + endTime + " 23:59:59'";
            }

        }
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);

        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }*/
        String sql = "SELECT  ";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sql = sql + "date_format(e.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"expressCreateTime\",";
            } else {
                sql = sql + "to_char(e.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"expressCreateTime\",";
            }

        } else {
            sql = sql + "date_format(e.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"expressCreateTime\",";
        }
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sql = sql + "date_format(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            } else {
                sql = sql + "to_char(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            }

        } else {
            sql = sql + "date_format(p.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
        }
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sql = sql + "date_format(p.pay_time,'YYYY-MM-DD hh24:mi:ss')  AS \"payTime\",";
            } else {
                sql = sql + "to_char(p.pay_time,'YYYY-MM-DD hh24:mi:ss')  AS \"payTime\",";
            }

        } else {
            sql = sql + "date_format(p.pay_time,'%Y-%m-%d %H:%i:%S' )  AS \"payTime\",";
        }
        sql = sql + " e.name as \"name\", " +
                " e.oneself_pickup_flg AS \"oneselfPickupFlg\", " +
                " o.id AS \"outpatientId\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " p.status as \"status\", " +
                " p.id AS \"prescriptionId\" ," +
                " e.id AS \"expressageId\" ," +
                " p.real_order AS \"realOrder\" ," +
                " p.origin_real_order AS \"originRealOrder\"," +
                " o.patient_name as \"patientName\" " +
                " FROM " +
                " wlyy_outpatient o " +
                " JOIN wlyy_prescription p ON p.outpatient_id = o.id " +
                " JOIN wlyy_prescription_expressage e ON e.outpatient_id = o.id " +
                " WHERE" +
                " 1=1";
        if (StringUtils.isNotBlank(status)) {
            sql += " AND p.status in(" + status + ") ";
        }
        if (StringUtils.isNotBlank(oneselfPickupFlg)) {
            sql += " AND e.oneself_pickup_flg =" + oneselfPickupFlg + " ";
        }
        if (StringUtils.isNotBlank(nameKey)) {
            sql += " AND e.name like '%" + nameKey + "%' ";
        }

        if (StringUtils.isNotBlank(patientName)) {
            sql += " AND o.patient_name like '%" + patientName + "%' ";
        }
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and p.create_time >= str_to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and p.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }
            } else {
                sql += " AND p.create_time >='" + startTime + " 00:00:00'";
            }

        }
        if (StringUtils.isNotBlank(endTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and p.create_time <= str_to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and p.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " AND p.create_time <='" + endTime + " 23:59:59'";
            }
        }
        sql += " order by p.create_time desc ";
        /*       sql += " LIMIT " + (page - 1) * size + "," + size + "";*/
        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql, page, size);
        for (Map<String, Object> map : mapList) {
            if (map.get("prescriptionId") != null) {
                List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(map.get("prescriptionId").toString(), 1);
                map.put("info", wlyyPrescriptionInfoDOS);
                String infoName = "";
                for (WlyyPrescriptionInfoDO info : wlyyPrescriptionInfoDOS) {
                    infoName += info.getDrugName() + "*" + info.getQuantity() + ",";
                }
                map.put("infooName", infoName);
            }
        }
        return MixEnvelop.getSuccessListWithPage2(BaseHospitalRequestMapping.Prescription.api_success, mapList);
    }


    /**
     * 订单查询
     *
     * @param status
     * @param oneselfPickupFlg
     * @param nameKey
     * @param startTime
     * @param endTime
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findExpressageList(String status, String oneselfPickupFlg, String nameKey, String startTime, String endTime, Integer page, Integer size, String wxId,String patientName) {
        String totalSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wlyy_outpatient o " +
                " JOIN wlyy_prescription p ON p.outpatient_id = o.id " +
                " JOIN wlyy_prescription_expressage e ON e.outpatient_id = o.id" +
                " WHERE" +
                " 1=1 ";
        if (StringUtils.isNotBlank(status)) {
            totalSql += " AND p.status in(" + status + ") ";
        }
        if (StringUtils.isNotBlank(oneselfPickupFlg)) {
            totalSql += " AND e.oneself_pickup_flg = " + oneselfPickupFlg+" ";
        }
        if (StringUtils.isNotBlank(nameKey)) {
            totalSql += " AND e.name like '%" + nameKey + "%' ";
        }
        if (StringUtils.isNotBlank(patientName)) {
            totalSql += " AND o.patient_name like '%" + patientName + "%' ";
        }
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    totalSql += " and p.create_time >= str_to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    totalSql += " and p.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }
            } else {
                totalSql += " AND p.create_time >='" + startTime + " 00:00:00'";
            }

        }
        if (StringUtils.isNotBlank(endTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    totalSql += " and p.create_time <= str_to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    totalSql += " and p.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }
            } else {
                totalSql += " AND p.create_time <='" + endTime + " 23:59:59'";
            }

        }
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);

        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        String sql = "SELECT  ";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                sql = sql + "date_format(e.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"expressCreateTime\",";
            }else {
                sql = sql + "to_char(e.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"expressCreateTime\",";
            }

        } else {
            sql = sql + "date_format(e.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"expressCreateTime\",";
        }
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                sql = sql + "date_format(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            }else {
                sql = sql + "to_char(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            }

        } else {
            sql = sql + "date_format(p.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
        }
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                sql = sql + "date_format(p.pay_time,'YYYY-MM-DD hh24:mi:ss')  AS \"payTime\",";
            }else {
                sql = sql + "to_char(p.pay_time,'YYYY-MM-DD hh24:mi:ss')  AS \"payTime\",";
            }

        } else {
            sql = sql + "date_format(p.pay_time,'%Y-%m-%d %H:%i:%S' )  AS \"payTime\",";
        }
        sql = sql + " e.name as \"name\", " +
                " e.oneself_pickup_flg AS \"oneselfPickupFlg\", " +
                " o.id AS \"outpatientId\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " p.status as \"status\", " +
                " p.id AS \"prescriptionId\" ," +
                " e.id AS \"expressageId\" ,"+
                " p.real_order AS \"realOrder\" ,"+
                " p.origin_real_order AS \"originRealOrder\"," +
                " o.patient_name as \"patientName\" "+
                " FROM " +
                " wlyy_outpatient o " +
                " JOIN wlyy_prescription p ON p.outpatient_id = o.id " +
                " JOIN wlyy_prescription_expressage e ON e.outpatient_id = o.id " +
                " WHERE" +
                " 1=1";
        if (StringUtils.isNotBlank(status)) {
            sql += " AND p.status in(" + status + ") ";
        }
        if (StringUtils.isNotBlank(oneselfPickupFlg)) {
            sql += " AND e.oneself_pickup_flg =" + oneselfPickupFlg+" ";
        }
        if (StringUtils.isNotBlank(nameKey)) {
            sql += " AND e.name like '%" + nameKey + "%' ";
        }
        if (StringUtils.isNotBlank(patientName)) {
            sql += " AND o.patient_name like '%" + patientName + "%' ";
        }
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql += " and p.create_time >= str_to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    sql += " and p.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }
            } else {
                sql += " AND p.create_time >='" + startTime + " 00:00:00'";
            }

        }
        if (StringUtils.isNotBlank(endTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql += " and p.create_time <= str_to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    sql += " and p.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " AND p.create_time <='" + endTime + " 23:59:59'";
            }

        }
        sql +=" order by p.create_time desc ";
        /*       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);
            }
        }

        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);

    }

    public Boolean setMailno(String mailno, String expressageId) {
        WlyyPrescriptionExpressageDO expressageDO = prescriptionExpressageDao.findOne(expressageId);
        expressageDO.setMailno(mailno);
        prescriptionExpressageDao.save(expressageDO);
        return true;
    }


    public void pushListWrite(OutputStream os, List<Map<String, Object>> ls) throws Exception {
        WritableWorkbook wwb = jxl.Workbook.createWorkbook(os);
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);

            String[] header = {"订单日期", "处方编号", "就诊人姓名", "收货人", "订单药品", "配送方式", "支付时间", "是否开方", "订单状态"};//"订单日期", "收货人", "诊断结果", "配送方式", "订单状态"
            int k = 0;
            for (String h : header) {
                addCell(ws, 0, k, h);//表名，行，列，header
                k++;
            }

            int i = 1;
            String n = " ";

            for (Map<String, Object> m : ls) {
                String createTime = "";
                if (m.get("createTime") == null) {
                     createTime = "否";
                }else {
                    createTime = "是";
                }

                String opf = "";
                if (m.get("oneselfPickupFlg") == null) {
                    opf = null;
                }else {
                    String opff = m.get("oneselfPickupFlg").toString();
                    if (opff.equals("1")){
                        opf = "自取";
                    }else if (opff.equals("0")){
                        opf = "快递配送";
                    }else {
                        opf = "其他";
                    }
                }

                String status = "";
                if (m.get("status") == null) {
                    status = null;
                }else{
                    String statuss = m.get("status").toString();
                    if (statuss.equals("-4")) {
                        status = "已作废";
                    }else if (statuss.equals("-3")) {
                        status = "支付过期取消";
                    }else if (statuss.equals("-2")){
                        status = "患者自己取消";
                    }else if (statuss.equals("-1")){
                        status = "医生取消";
                    }else if (statuss.equals("0")){
                        status = "候诊中";
                    }else if (statuss.equals("10")) {
                        status = "诊断中";
                    }else if (statuss.equals("11")) {
                        status = "药师审核失败 / 调整中";
                    }else if (statuss.equals("12")) {
                        status = "药师审核完成";
                    }else if (statuss.equals("13")) {
                        status = "开方失败/调整中";
                    }else if (statuss.equals("20")) {
                        status = "诊断完成/开方成功/待支付";
                    }else if (statuss.equals("30")) {
                        status = "支付成功/等待配药";
                    }else if (statuss.equals("31")) {
                        status = "配药成功/等待取药";
                    }else if (statuss.equals("32")) {
                        status = "配送中";
                    }else if (statuss.equals("100")) {
                        status = "已完成/未评价";
                    }else if (statuss.equals("101")) {
                        status = "已完成/已经评价";
                    }else {
                        status = null;
                    }
                }

                addCell(ws, i, 0, m.get("createTime")!=null?m.get("createTime").toString():n);
                addCell(ws, i, 1, m.get("realOrder")!=null?m.get("realOrder").toString():n);
                addCell(ws, i, 2, m.get("patientName")!=null?m.get("patientName").toString():n);
                addCell(ws, i, 3, m.get("name")!=null?m.get("name").toString():n);
                addCell(ws, i, 4, m.get("infooName")!=null?m.get("infooName").toString():n);
                addCell(ws, i, 5, opf!=null?opf:n);
                addCell(ws, i, 6, m.get("payTime")!=null?m.get("payTime").toString():n);
                addCell(ws, i, 7, createTime!=null?createTime:n);
                addCell(ws, i, 8, status!=null?status:n);
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }

    public void searchRecordWrite(OutputStream os, List<Map<String, Object>> list) throws Exception{
        WritableWorkbook wwb = jxl.Workbook.createWorkbook(os);
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);

            String[] header = {"患者姓名","问诊医生","就诊科室","问诊类型","发起时间","接诊时间","结束时间","咨询问题","是否开方","咨询状态"};
            int k = 0;
            for (String h : header) {
                addCell(ws, 0, k, h);//表名，行，列，header
                k++;
            }

            int i = 1;
            String n = " ";
            for (Map<String, Object> m : list) {
                String status = "";
                if(m.get("STATUS") == null){
                    status = null;
                }else{
                    if (m.get("STATUS").equals("1")){
                        status += "候诊中";
                    }else if (m.get("STATUS").equals("2")){
                        status += "就诊中";
                    }else if (m.get("STATUS").equals("3")){
                        status += "结束";
                    }else {
                        status += "取消";
                    }
                }

                String payy = "";
                if (m.get("pay") == null) {
                    payy = null;
                }else {
                    if (Integer.parseInt(m.get("pay").toString()) >= 20) {
                        payy += "是";
                    }else if (Integer.parseInt(m.get("pay").toString()) < 20){
                        payy += "否";
                    }
                }

                String type = "";
                if (m.get("type") == null) {

                }else {
                    if(m.get("type").equals("1")) {
                        type = "在线复诊";
                    }else if (m.get("type").equals("2")) {
                        type = "协同门诊";
                    }else if (m.get("type").equals("3")) {
                        type = "专家咨询";
                    }
                }

                addCell(ws, i, 0, m.get("pname")!=null?m.get("pname").toString():n);
                addCell(ws, i, 1, m.get("dname")!=null?m.get("dname").toString():n);
                addCell(ws, i, 2, m.get("dept")!=null?m.get("dept").toString():n);
                addCell(ws, i, 3, type.toString()!=null?type.toString():n);
                addCell(ws, i, 4, m.get("ctime")!=null?m.get("ctime").toString():n);
                addCell(ws, i, 5, m.get("rtime")!=null?m.get("rtime").toString():n);
                addCell(ws, i, 6, m.get("etime")!=null?m.get("etime").toString():n);
                addCell(ws, i, 7, m.get("des")!=null?m.get("des").toString():n);
                addCell(ws, i, 8, payy!=null?payy:n);
                addCell(ws, i, 9, status.toString()!=null?status.toString():n);
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }

    public void pushYktCardChargeWrite(OutputStream os, List<Map<String, Object>> list) throws Exception{
        WritableWorkbook wwb = jxl.Workbook.createWorkbook(os);
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);

            String[] header = {"序号","充值时间","商户订单号","医院订单号","患者姓名","证件号码","就诊卡号","手机号码","金额","状态","业务类型","咨询方式"};
            int k = 0;
            for (String h : header) {
                addCell(ws, 0, k, h);//表名，行，列，header
                k++;
            }

            int i = 1;
            String n = "";


            for (Map<String, Object> m : list) {
                String odry = "";
                String orderCategory = "";
                String odte = "";
                String status ="";
                String pay = "";

                if (m.get("orderCategory")==null){
                    odry = null;
                }else {
                    if(m.get("orderType") == null) {
                        odte = null;
                    }else{
                        String orderType =  m.get("orderType").toString();
                        orderCategory = m.get("orderCategory").toString();
                        if (orderCategory.equals("1")) {
                            odry += "专家咨询";
                            if (orderType.equalsIgnoreCase("1")) {
                                odte += "图文";
                            }else if (orderType.equalsIgnoreCase("3")) {
                                odte += "视频";
                            }
                        }else if (orderCategory.equals("2")) {
                            odry += "在线复诊";
                            if (orderType.equalsIgnoreCase("1")) {
                                odte += "图文";
                            }else if (orderType.equalsIgnoreCase("3")) {
                                odte += "视频";
                            }
                        }else if (orderCategory.equals("4")) {
                            odry += "处方";
                            odte += "处方";
                        }else if (orderCategory.equals("5")) {
                            odry += "就诊卡充值";
                            odte += "就诊卡充值";
                        }else {
                            odry += " ";
                        }
                    }
                }


                if (m.get("status") == null) {
                    status = null;
                }else {
                    String statuss = m.get("status").toString();
                    if (statuss.equals("0")){
                        status = "未支付";
                    }else if (statuss.equals("1")) {
                        status = "已支付";
                    }else if (statuss.equals("2")) {
                        status = "未支付";
                    }else if (statuss.equals("3")) {
                        status = "交易关闭";
                    }else if (statuss.equals("4")) {
                        status = "交易完成";
                    }else if (statuss.equals("5")) {
                        status = "交易进行中";
                    }else if (statuss.equals("6")) {
                        status = "退款申请";
                    }else if (statuss.equals("9")) {
                        status = "退款完成";
                    }
                }



                if (m.get("payPrice") == null) {
                    pay = null;
                }else{
                    pay = m.get("payPrice").toString();
                }

                String time = "";
                if (m.get("payTime") == null) {
                    time = null;
                }else {
                    time = m.get("payTime").toString();
                }

                addCell(ws, i, 0, m.get("id")!=null?m.get("id").toString():n);
                addCell(ws, i, 1, time!=null?time:n);
                addCell(ws, i, 2, (String) m.get("orderNo")!=null?(String) m.get("orderNo"):n);
                addCell(ws, i, 3, (String) m.get("ykOrderNo")!=null?(String) m.get("ykOrderNo"):n);
                addCell(ws, i, 4, (String) m.get("patientName")!=null?(String) m.get("patientName"):n);
                addCell(ws, i, 5, (String) m.get("idcard")!=null?(String) m.get("idcard"):n);
                addCell(ws, i, 6, (String) m.get("medicard")!=null?(String) m.get("medicard"):n);
                addCell(ws, i, 7, (String) m.get("mobile")!=null?(String) m.get("mobile"):n);
                addCell(ws, i, 8, pay!=null?pay:n);
                addCell(ws, i, 9, status!=null?status:n);
                addCell(ws, i, 10, odry!=null?odry:n);
                addCell(ws, i, 11, odte!=null?odte:n);
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }


    /**
     * @return
     */
    public String getOneselfPickupFlgString(Integer oneselfPickupFlg) {
        if (1 == oneselfPickupFlg) {
            return "自取";
        } else if (0 == oneselfPickupFlg) {
            return "快递";
        } else {
            return "其他";
        }
    }

    /**
     * @param status
     * @return
     */
    public String getStatusName(Integer status) {
        if (31 == status) {
            return "待配送";
        } else if (32 == status) {
            return "配送中";
        } else if (100 == status) {
            return "已完成";
        } else {
            return "其他";
        }
    }

    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data) throws WriteException {
        Label label = new Label(column, row, data);
        ws.addCell(label);
    }

    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data, String memo) throws WriteException {
        Label label = new Label(column, row, data);
        if (!org.springframework.util.StringUtils.isEmpty(memo)) {
            WritableCellFeatures cellFeatures = new WritableCellFeatures();
            cellFeatures.setComment(memo);
            label.setCellFeatures(cellFeatures);
        }
        ws.addCell(label);
    }

    public List<WlyyChargeDictVO> findByDeptTypeCode(String deptTypeCode) {
        List<WlyyChargeDictDO> dictDOs = new ArrayList<>();
        if(StringUtils.isNoneBlank(deptTypeCode)){
            dictDOs = wlyyChargeDictDao.findByDeptTypeCode(deptTypeCode);
        }else {
            dictDOs = wlyyChargeDictDao.findAllDict();
        }
        List<WlyyChargeDictVO> dictVOs = new ArrayList<>();
        return convertToModels(dictDOs, dictVOs, WlyyChargeDictVO.class);
    }


//      过时
//    public List<WlyyDoctorWorkTimeVO> findDoctorWorkTime(String doctor) {
//        //获取医生排班规则
//        List<WlyyHospitalSysDictDO> list = sysDictDao.findByDictName("Scheduling");
//
//        Calendar ncTime = Calendar.getInstance();
//        ncTime.setTime(new Date());
//
//        Calendar scTime = Calendar.getInstance();
//        scTime.setTime(new Date());
//
//        Calendar ecTime = Calendar.getInstance();
//        ecTime.setTime(new Date());
//
//        //设置几天号源，及最后天号源的开放时间
//        int days = Integer.parseInt(findHospitalSysDictValue(list, "OpenDays"));
//        String closeTime = findHospitalSysDictValue(list, "CloseTime");
//
//        //比较当前时间是否超过开放时间
//        if (DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM_SS).after(DateUtil.strToDate(closeTime, DateUtil.HH_MM))) {
//            //当前时间超过开放时间，可以预约最后一天全部号源
//            ecTime.add(Calendar.DAY_OF_MONTH, days);
//            ecTime.set(ecTime.get(Calendar.YEAR), ecTime.get(Calendar.MONTH), ecTime.get(Calendar.DATE), 23, 59, 59);
//        } else {
//            //当前时间没超过开放时间，可以预约最后一天前一天全部号源
//            ecTime.add(Calendar.DAY_OF_MONTH, days > 1 ? days - 1 : 0);
//            ecTime.set(ecTime.get(Calendar.YEAR), ecTime.get(Calendar.MONTH), ecTime.get(Calendar.DATE), 23, 59, 59);
//        }
//
//
//        List<WlyyDoctorWorkTimeDO> times = doctorWorkTimeDao.findDoctorWorkTime(doctor, scTime.getTime(), ecTime.getTime());
//
//        workTimeFilter(list, times);
//
//        List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
//
//        convertToModels(times, timeVOs, WlyyDoctorWorkTimeVO.class);
//
//        if (timeVOs != null && timeVOs.size() > 0) {
//            for (WlyyDoctorWorkTimeVO timeVO : timeVOs) {
//                timeVO.setCount(findWorkTimeCount(timeVO.getId()));
//            }
//        }
//        return timeVOs;
//    }

//    public List<WlyyDoctorWorkTimeDO> workTimeFilter(List<WlyyHospitalSysDictDO> sys, List<WlyyDoctorWorkTimeDO> times) {
//
//        if (times != null && times.size() > 0) {
//            //上午号源开放的最早天数
//            int AMCloseDays = Integer.parseInt(findHospitalSysDictValue(sys, "AMCloseDays"));
//            //每一天上午的最早预约的过号时间
//            String AMCloseTime = findHospitalSysDictValue(sys, "AMCloseTime");
//            //下午号源开放的最早天数
//            int PMCloseDays = Integer.parseInt(findHospitalSysDictValue(sys, "PMCloseDays"));
//            //每一天下午的最早预约的过号时间
//            String PMCloseTime = findHospitalSysDictValue(sys, "PMCloseTime");
//
//            Iterator it = times.iterator();
//            while (it.hasNext()) {
//                //设置上午过号时间
//                Calendar scAMTime = Calendar.getInstance();
//                scAMTime.setTime(new Date());
//                scAMTime.add(Calendar.DAY_OF_MONTH, AMCloseDays);
//
//                //设置下午午过号时间
//                Calendar scPMTime = Calendar.getInstance();
//                scPMTime.setTime(new Date());
//                scPMTime.add(Calendar.DAY_OF_MONTH, PMCloseDays);
//
//                WlyyDoctorWorkTimeDO time = (WlyyDoctorWorkTimeDO) it.next();
//
//                Boolean filter = true;
//
//                //1.【上午的排班中】 且 【排班结束时间】如果在【开放时间】前，则移除
//                if (filter && "1".equals(time.getTimeType()) && time.getEndTime().before(scAMTime.getTime())) {
//                    it.remove();
//                    filter = false;
//                }
//
//                //2.【下午午的排班中】 且 【排班结束时间】如果在【开放时间】前，则移除该排班
//                if (filter && "2".equals(time.getTimeType()) && time.getEndTime().before(scPMTime.getTime())) {
//                    it.remove();
//                    filter = false;
//                }
//
//                //3.如果【当前时间】过了【上午放号时间】，则移除所有上午的排班
//                if (filter && "1".equals(time.getTimeType()) &&
//                        DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM_SS).after(DateUtil.strToDate(AMCloseTime, DateUtil.HH_MM))) {
//                    scAMTime.set(scAMTime.get(Calendar.YEAR), scAMTime.get(Calendar.MONTH), scAMTime.get(Calendar.DATE), 12, 00, 00);
//
//                    if (time.getEndTime().before(scAMTime.getTime())) {
//                        it.remove();
//                        filter = false;
//                    }
//                }
//                //4.如果【当前时间】过了【下午午放号时间】，则移除所有下午的排班
//                if (filter && "2".equals(time.getTimeType()) &&
//                        DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM_SS).after(DateUtil.strToDate(PMCloseTime, DateUtil.HH_MM))) {
//                    scPMTime.set(scAMTime.get(Calendar.YEAR), scAMTime.get(Calendar.MONTH), scAMTime.get(Calendar.DATE), 12, 00, 00);
//
//                    if (time.getEndTime().before(scPMTime.getTime())) {
//                        it.remove();
//                    }
//                }
//            }
//        }
//        return times;
//    }


    public String findHospitalSysDictValue(List<WlyyHospitalSysDictDO> list, String dictCode) {

        if (list != null && list.size() > 0) {
            for (WlyyHospitalSysDictDO sysDictDO : list) {
                if (dictCode.equals(sysDictDO.getDictCode())) {
                    return sysDictDO.getDictValue();
                }
            }
        }
        return "";
    }

    /**
     * 获取卡信息
     *
     * @param cardNo
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject getCardInfo(String cardNo, boolean demoFlag) throws Exception {
        return entranceService.qutpatientBalance(cardNo, demoFlag);
    }

    /**
     * 新排班号源详情
     *
     * @param id
     * @return
     */
    public List<Map<String, Object>> findWorkTimeInfo(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);

        Long ss = timeDO.getEndTime().getTime() - timeDO.getStartTime().getTime();
        Long s = ss / timeDO.getSourceNumber();

        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());

        List<Map<String, Object>> rs = new ArrayList<>();

        //1.根据当前时间，去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
            }
            //加上时间间隔
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
        }

        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);

        //2.根据时间间隔拆分号源
        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"));
            //加上时间间隔
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
            //如果结束时间大于排班时间则不再拆分号源
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
            }
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));

            //如果号源被预约了，标记为true
            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"))) {
                        registered = true;
                    }
                }
            }
            t.put("registered", registered);
            rs.add(t);
        }

        return rs;
    }

    /**
     * 计算号源数目
     *
     * @param id
     * @return
     */
    public Integer findWorkTimeInfoCout(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);

        if (timeDO.getSourceNumber() == null || timeDO.getStartTime() == null || timeDO.getEndTime() == null) {
            return 0;
        }

        Long ss = timeDO.getEndTime().getTime() - timeDO.getStartTime().getTime();
        Long s = ss / timeDO.getSourceNumber();

        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());

        List<Map<String, Object>> rs = new ArrayList<>();

        //1.根据当前时间，去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
            }
            //加上时间间隔
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
        }

        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);

        //2.根据时间间隔拆分号源
        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"));
            //加上时间间隔
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
            //如果结束时间大于排班时间则不再拆分号源
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
            }
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));

            //如果号源被预约了，标记为true
            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"))) {
                        registered = true;
                    }
                }
            }
            if (!registered) {
                rs.add(t);
            }
        }
        return rs.size();
    }

    @Deprecated
    public List<Map<String, Object>> findWorkTimeInfoOld(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());

        List<Map<String, Object>> rs = new ArrayList<>();

        //1.根据当前时间，去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
            }
            //加上时间间隔
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
        }

        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);

        //2.根据时间间隔拆分号源
        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"));
            //加上时间间隔
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
            //如果结束时间大于排班时间则不再拆分号源
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
            }
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));

            //如果号源被预约了，标记为true
            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"))) {
                        registered = true;
                    }
                }
            }
            t.put("registered", registered);
            rs.add(t);
        }

        return rs;
    }

    public Integer findWorkTimeCount(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());

        List<Map<String, Object>> rs = new ArrayList<>();

        //1.根据当前时间，去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
            }
            //加上时间间隔
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
        }

        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);

        //2.根据时间间隔拆分号源
        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"));
            //加上时间间隔
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());

            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
            }
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));

            if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                Boolean registered = false;
                for (WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs) {
                    if (t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(), "yyyy-MM-dd HH:mm:ss"))) {
                        registered = true;
                    }
                }
                if (!registered) {
                    rs.add(t);
                }
            } else {
                rs.add(t);
            }
        }

        return rs.size();
    }

    public Map<String, Object> findDoctorInfo(String doctor, String withWork,String patient) {
        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());// 咨询在线状态
            rs.put("img",doctorDO.getImg());//风采图
            rs.put("visitHospitalName",doctorDO.getVisitHospitalName());//出诊医院
            rs.put("visitHospital",doctorDO.getVisitHospital());
            rs.put("background",doctorDO.getBackground());//背景图
            rs.put("backgroundId",doctorDO.getBackgroundId());//背景图id
            rs.put("visitDeptName",doctorDO.getVisitDeptName());//出诊科室
            rs.put("visitDept",doctorDO.getVisitDept());
            rs.put("learning",doctorDO.getLearning());
            rs.put("sex",doctorDO.getSex());
            rs.put("popularity",doctorDO.getPopularity());
            rs.put("qrcode",doctorDO.getQrcode());
            List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
            String sqlCharge = "SELECT\n" +
                    "\tm.req_fee as \"twfzFee\",\n" +
                    "\ta.req_fee as \"spfzFee\",\n" +
                    "\tb.req_fee as \"spzxFee\",\n" +
                    "\tv.req_fee as \"twzxFee\",\n" +
                    "\tg.req_fee as \"jyzxFee\",\n" +
                    "\td.req_fee as \"xtzxFee\"\n" +
                    "FROM\n" +
                    "\tbase_doctor t\n" +
                    "LEFT JOIN wlyy_charge_dict m ON t.twfz_charge_type = m.charge_type and m.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict a ON t.spfz_charge_type = a.charge_type and a.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict b ON t.spzx_charge_type = b.charge_type and b.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict v ON t.twzx_charge_type = v.charge_type and v.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict d ON t.xtfz_charge_type = d.charge_type and d.is_del='1'\n" +
                    " LEFT JOIN wlyy_charge_dict g ON t.jyzx_charge_type = g.charge_type and g.is_del='1'\n" +
                    "WHERE t.id = '"+doctorDO.getId()+"' ";
            chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);
            //System.out.println(chargeDictDOLists.get(1));
            rs.put("chargeTypeList",chargeDictDOLists);
            //机构科室信息
            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());
                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);
                }
            } else {
                rs.put("hospital", null);
                rs.put("winNo", null);
                rs.put("deptName", null);
                rs.put("dept", null);
                rs.put("workTime", null);
            }

            //医保是否有处方权
            if(healthCareService.isHospitalFlag()){
                String doctorAuthenticationUrl = entranceHealthCareUrl + "doctorAuthentication?doctorId="+doctorDO.getId();
                String infoResponse = httpClientUtil.get(doctorAuthenticationUrl,"GBK");
                com.alibaba.fastjson.JSONObject doctorAuthentication = com.alibaba.fastjson.JSONObject.parseObject(infoResponse);
                if(doctorAuthentication.getInteger("status")==200){
                    rs.put("is_prescribe", doctorAuthentication.get("obj"));//is_prescribe	是否具备处方权	1-有处方权，0无处方权
                }else {
                    rs.put("is_prescribe",0);
                }
            }else{
                rs.put("is_prescribe", 0);//is_prescribe	是否具备处方权	1-有处方权，0无处方权
            }

            //医生角色
            String sql = "SELECT " +
                    " t. CODE AS \"roleCode\", " +
                    " t. NAME AS \"roleName\"" +
                    " FROM " +
                    " base_doctor_role r " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " WHERE " +
                    " 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);
            }
            //医生预约量
            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);
            if (wlyyOutpatientDOs != null && wlyyOutpatientDOs.size() > 0) {
                rs.put("outpatientCount", wlyyOutpatientDOs.size());
            } else {
                rs.put("outpatientCount", 0);
            }
//
//            //协同门诊量
//            Integer coordinationCout = outpatientDao.countByDoctorAndStatusAndOutpatientType(doctor,"2","2");
//            rs.put("coordinationCout",coordinationCout);
            //医生关注
            if(StringUtils.isNotBlank(patient)){
                List<BaseDoctorPatientFollowDO> doctorPatientFollowDOS = baseOrgPatientDao.findByDoctorAndPatient(doctor,patient);
                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);
            if (zjList != null && zjList.size() > 0) {
                rs.put("zjCount", zjList.size());
            } else {
                rs.put("zjCount", 0);
            }

            //查询医生各项评价平均分
            String sqlscore = "SELECT " +
                    "AVG(a.score) AS \"score\"," +
                    "a.score_type AS \"score_type\" " +
                    "FROM base_evaluate a,base_evaluate_score b " +
                    "WHERE " +
                    "a.relation_code=b.id " +
                    "AND b.doctor='" + doctor + "' " +
                    "GROUP BY a.score_type ORDER BY  a.score_type ASC ";
            List<Map<String, Object>> listscore = jdbcTemplate.queryForList(sqlscore);

            Double doctorScore = new Double("0");

            if (listscore != null && listscore.size() > 0) {
                for (Map<String, Object> _listscore : listscore) {
                    doctorScore += Double.parseDouble(_listscore.get("score").toString());
                }
            }
            doctorScore = doctorScore / 3;
            rs.put("doctorScore", doctorScore);

            if (listscore != null && listscore.size() > 0) {
                rs.put("scoreDoctor", listscore);
            } else {
                rs.put("scoreDoctor", null);
            }
            int count = baseBannerDoctorDao.getTotalBannerCount(doctor);
            rs.put("bannerCount",count);

            //查询评价明细
            String sqlScoreList = "SELECT " +
                    "a.score as \"score\"," +
                    "b.score as \"doctorscore\"," +
                    "a.score_type as \"score_type\"," +
                    "a.content as \"content\"," +
                    "b.create_time as \"create_time\"," +
                    "c.type as \"type\"," +
                    "c.name as \"patientname\"," +
                    "b.id as \"id\"," +
                    "c.photo as \"patientphoto\"," +
                    "b.type as \"niming\" " +
                    "FROM " +
                    "base_evaluate a " +
                    "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 + "' order by b.create_time DESC ";
            List<Map<String, Object>> scoreList = jdbcTemplate.queryForList(sqlScoreList);
            if (scoreList != null && scoreList.size() > 0) {
//                Set<String> datelist = new HashSet<>();

               /* 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 (id == null) {
                            continue;
                        }

                        if (waitinglist.keySet().contains(id)) {
                            waitinglist.get(id).add(scorepatient);
                        } else {
                            List<Map<String, Object>> _cu = new ArrayList<>();
                            _cu.add(scorepatient);
                            waitinglist.put(id, _cu);
                        }
                    }
                }*/
                List<com.alibaba.fastjson.JSONArray> waitinglist = new ArrayList<>();
                List<BaseSensitiveDO> listSensitive = (List<BaseSensitiveDO>) baseSensitiveDao.findAll();
                if (scoreList != null && scoreList.size() > 0) {
                    List<String> stringList = new ArrayList<>();
                    for (Map<String, Object> scorepatient : scoreList) {
                        String id = (String) scorepatient.get("id");
                        if (id == null) {
                            continue;
                        }

                        if (!stringList.contains(id)){
                            stringList.add(id);
                        }
                        String content = (String)scorepatient.get("content");
                        if (StringUtils.isNotEmpty(content)){
                            String replace = baseSensitiveFilterWordsService.filterSensitiveWords(content,listSensitive);
                            scorepatient.put("content",replace);
                        }

                    }
                    for (String str:stringList){
                        com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
                        for (Map<String, Object> scorepatient : scoreList){
                            String id = (String) scorepatient.get("id");
                            if (id!=null&&str.equalsIgnoreCase(id)){
                                array.add(scorepatient);
                            }
                        }
                        waitinglist.add(array);
                    }
                }

                rs.put("scoreList", waitinglist);
            } else {
                rs.put("scoreList", null);
            }
        }

        return rs;
    }

    public BaseDoctorDO updateDoctorInfo(String id, String img,String background,String expertise,String visitHospital,String visitHospitalName,String visitDept,String visitDeptName,String backgroundId,String name,Integer sex,String learning,String introduce,String photo){
        if (StringUtils.isNoneBlank(id)){
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(id);
            baseDoctorDO.setImg(img);
            baseDoctorDO.setBackground(background);
            baseDoctorDO.setExpertise(expertise);
            baseDoctorDO.setVisitHospital(visitHospital);
            baseDoctorDO.setVisitHospitalName(visitHospitalName);
            baseDoctorDO.setVisitDept(visitDept);
            baseDoctorDO.setVisitDeptName(visitDeptName);
            baseDoctorDO.setBackgroundId(backgroundId);
            baseDoctorDO.setName(name);
            baseDoctorDO.setLearning(learning);
            baseDoctorDO.setSex(sex);
            baseDoctorDO.setIntroduce(introduce);
            baseDoctorDO.setPhoto(photo);
            return baseDoctorDao.save(baseDoctorDO);
        }else {
            return null;
        }
    }

    public Map<String, Object> findDoctorBaseInfo(String 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());// 咨询在线状态
            rs.put("img",doctorDO.getImg());//风采图
            rs.put("visitHospitalName",doctorDO.getVisitHospitalName());//出诊医院
            rs.put("visitHospital",doctorDO.getVisitHospital());
            rs.put("background",doctorDO.getBackground());//背景图
            rs.put("backgroundId",doctorDO.getBackgroundId());//背景图id
            rs.put("visitDeptName",doctorDO.getVisitDeptName());//出诊科室
            rs.put("visitDept",doctorDO.getVisitDept());
            rs.put("learning",doctorDO.getLearning());
            rs.put("sex",doctorDO.getSex());
            rs.put("qrcode",doctorDO.getQrcode());
            //号别
            String deptTyepCode = "";
            if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                deptTyepCode = "6";
                List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(doctor);
                if (null!=depts&&depts.size()>0){
                    BaseDoctorHospitalDO baseDoctorHospitalDO = depts.get(0);
                    String deptcode =  baseDoctorHospitalDO.getDeptCode();
                    String hosptitalCode = baseDoctorHospitalDO.getOrgCode();
                    List<DictHospitalDeptDO> dictHospitalDeptDO = dictHospitalDeptDao.findByOrgCodeAndCode(hosptitalCode,deptcode);
                    if(null!=dictHospitalDeptDO&&dictHospitalDeptDO.size()>0){
                        if (StringUtils.isNotBlank(dictHospitalDeptDO.get(0).getDeptTypeCode())){
                            deptTyepCode = dictHospitalDeptDO.get(0).getDeptTypeCode();
                        }
                    }

                }
            }
            /*List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
            String chargeType = doctorDO.getChargeType();
            if (StringUtils.isNotBlank(chargeType)){
                if (chargeType.contains(",")){
                    chargeType = chargeType.replace(",","','");
                }
                String sqlCharge = "select charge_type as \"chargeType\",charge_name as \"chargeName\"," +
                        "req_fee  as \"reqFee\",zj_fee  as \"zjFee\",xt_fee  as \"xtFee\",dept_type_code as \"deptTypeCode\" " +
                        " from wlyy_charge_dict where 1=1";
                sqlCharge+=" and charge_type in ( '"+chargeType+"')";
                if(StringUtils.isNoneBlank(deptTyepCode)){
                    sqlCharge+=" and dept_type_code in ( '"+deptTyepCode+"')";
                }
                chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);
            }
            rs.put("chargeTypeList",chargeDictDOLists);*/
            List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
            String sqlCharge = "SELECT\n" +
                    "\tm.req_fee as \"twfzFee\",\n" +
                    "\ta.req_fee as \"spfzFee\",\n" +
                    "\tb.req_fee as \"spzxFee\",\n" +
                    "\tv.req_fee as \"twzxFee\",\n" +
                    "\tg.req_fee as \"jyzxFee\",\n" +
                    "\td.req_fee as \"xtzxFee\"\n" +
                    "FROM\n" +
                    "\tbase_doctor t\n" +
                    "LEFT JOIN wlyy_charge_dict m ON t.twfz_charge_type = m.charge_type and m.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict a ON t.spfz_charge_type = a.charge_type and a.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict b ON t.spzx_charge_type = b.charge_type and b.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict v ON t.twzx_charge_type = v.charge_type and v.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict d ON t.xtfz_charge_type = d.charge_type and d.is_del='1'\n" +
                    " LEFT JOIN wlyy_charge_dict g ON t.jyzx_charge_type = g.charge_type and g.is_del='1'\n" +
                    "WHERE t.id = '"+doctorDO.getId()+"'";
            chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);
            rs.put("chargeTypeList",chargeDictDOLists);
            //机构科室信息
            List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByDoctorCode(doctorDO.getId());
            List<BaseDoctorHospitalDO> hospitalDOList = new ArrayList<>();
            for (BaseDoctorHospitalDO doctorHospitalDO : hospitalDOs) {
                String orgCode = doctorHospitalDO.getOrgCode();
                BaseOrgDO org = baseOrgDao.findByCode(orgCode);
                if (org != null) {
                    doctorHospitalDO.setWinNo(org.getWinNo());
                    doctorHospitalDO.setHisId(org.getHisId());
                    hospitalDOList.add(doctorHospitalDO);
                }
            }
            if (hospitalDOList != null && hospitalDOList.size() > 0) {
                rs.put("hospital", hospitalDOList.get(0));
                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());
                }
            } else {
                rs.put("hospital", null);
                rs.put("winNo", null);
                rs.put("deptName", null);
                rs.put("deptCode", null);
            }


            //多科室兼容
            rs.put("hospitalList", hospitalDOList);

            //医保是否有处方权
            if(healthCareService.isHospitalFlag()){
                String doctorAuthenticationUrl = entranceHealthCareUrl + "doctorAuthentication?doctorId="+doctorDO.getId();
                String infoResponse = httpClientUtil.get(doctorAuthenticationUrl,"GBK");
                com.alibaba.fastjson.JSONObject doctorAuthentication = com.alibaba.fastjson.JSONObject.parseObject(infoResponse);
                if(doctorAuthentication.getInteger("status")==200){
                    rs.put("is_prescribe", doctorAuthentication.get("obj"));//is_prescribe	是否具备处方权	1-有处方权，0无处方权
                }else {
                    rs.put("is_prescribe",0);
                }
            }else{
                rs.put("is_prescribe", 0);//is_prescribe	是否具备处方权	1-有处方权，0无处方权
            }

            //医生角色
            String sql = "SELECT " +
                    " t.CODE AS \"roleCode\", " +
                    " t.NAME AS \"roleName\"" +
                    " FROM " +
                    " base_doctor_role r " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " WHERE " +
                    " r.doctor_code = '" + doctor + "'";
            logger.info(sql);
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

            if (list != null && list.size() > 0) {
                rs.put("roles", list);
            } else {
                rs.put("roles", null);
            }

            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue");
            if (wlyyHospitalSysDictDO.getPyCode().equalsIgnoreCase("open")) {
                //密码过期
                rs.put("authPw", baseDoctorService.findDoctorPwlimitDate(doctor));
            }

        }

        return rs;
    }

    /**
     * 居民取消复诊或者医生拒绝接诊
     *
     * @param outPatientId
     * @param cancelType
     * @param cancelValue
     * @param cancelRemark
     * @param operator     1居民 2医生
     * @return
     */
    public Map<String, Object> cancelOutPatient(String outPatientId, String cancelType, String cancelValue, String cancelRemark, Integer operator, String wxId) {

        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", "医生已经接诊，无法取消");
                    return rs;
                } else {
                    roomDO.setVisitStatus(-1);
                    hospitalWaitingRoomDao.save(roomDO);
                }
            }
        }
        //更改门诊状态
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outPatientId);
        wlyyOutpatientDO.setStatus("-1");
        //报错拒诊操作人
        wlyyOutpatientDO.setOperator(userAgent.getUID());
        wlyyOutpatientDO.setEndTime(new Date());
        String description = null;
        if (1 == operator) {
            //居民取消
            wlyyOutpatientDO.setPatientCancelRemark(cancelRemark);
            wlyyOutpatientDO.setPatientCancelType(cancelType);
            wlyyOutpatientDO.setPatientCancelValue(cancelValue);
            String type="";
            if("1".equalsIgnoreCase(wlyyOutpatientDO.getType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                type="9";
            }else if("2".equalsIgnoreCase(wlyyOutpatientDO.getType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                type="16";
            }else if("1".equalsIgnoreCase(wlyyOutpatientDO.getType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                type="1";
            }
            else if("2".equalsIgnoreCase(wlyyOutpatientDO.getType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                type="17";
            }else if("2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                type="12";
            }
            description = "居民取消";
            if (StringUtils.isNoneBlank(type)){
                sendWxTemplateMsg(wxId, outPatientId,null, type, "patientCancel", "");
            }
        } else {
            //医生拒绝接诊
            wlyyOutpatientDO.setDoctorCancelRemark(cancelRemark);
            wlyyOutpatientDO.setDoctorCancelType(cancelType);
            wlyyOutpatientDO.setDoctorCancelValue(cancelValue);
            description = "医生拒绝接诊";

            //系统消息 医生取消复诊
            SystemMessageDO messageDO = new SystemMessageDO();
            messageDO.setTitle("医生取消复诊");
            messageDO.setType("12");
            messageDO.setSender(wlyyOutpatientDO.getDoctor());
            messageDO.setSenderName(wlyyOutpatientDO.getDoctorName());
            messageDO.setRelationCode(wlyyOutpatientDO.getId());
            messageDO.setReceiver(wlyyOutpatientDO.getPatient());
            messageDO.setReceiverName(wlyyOutpatientDO.getPatientName());
            net.sf.json.JSONObject data = new net.sf.json.JSONObject();


            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.getOutpatientType())||"2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                    if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        data.put("type", "9");
                        msg += wlyyOutpatientDO.getPatientName() + ",您好！ 您有一个图文复诊已被医生取消，取消原因：" + cancelValue + "。取消说明：" + cancelRemark + "。";
                        sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, "9", "doctorRefuseRemind", cancelRemark);
                    }
                    if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        data.put("type", "16");
                        msg += wlyyOutpatientDO.getPatientName() + ",您好！ 您有一个视频复诊已被医生取消，取消原因：" + cancelValue + "。取消说明：" + cancelRemark + "。";
                        sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, "16", "doctorRefuseRemind", cancelRemark);
                    }
                }else {
                    if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        data.put("type", "1");
                        msg += wlyyOutpatientDO.getPatientName() + ",您好！ 您有一个图文咨询已被医生取消，取消原因：" + cancelValue + "。取消说明：" + cancelRemark + "。";
                        sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, "1", "doctorRefuseRemind", cancelRemark);
                    }
                    if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        data.put("type", "17");
                        msg += wlyyOutpatientDO.getPatientName() + ",您好！ 您有一个视频咨询已被医生取消，取消原因：" + cancelValue + "。取消说明：" + cancelRemark + "。";
                        sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, "17", "doctorRefuseRemind", cancelRemark);
                    }
                }

                data.put("msg", msg);
                messageDO.setData(data.toString());
                systemMessageService.saveMessage(messageDO);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //推送消息到眼科通
            BasePatientDO patient = basePatientDao.findById(wlyyOutpatientDO.getPatient());
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), messageDO.getTitle(), data.get("msg").toString());
            }

        }

        outpatientDao.save(wlyyOutpatientDO);

        //删除门诊号源
        List<WlyyPatientRegisterTimeDO> list = patientRegisterTimeDao.findByOutpatientId(wlyyOutpatientDO.getId());
        if (list != null && list.size() > 0) {
            patientRegisterTimeDao.delete(list);
        }
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outPatientId);
        try {
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                businessOrderService.orderRefund(wxId, wlyyOutpatientDO.getConsumer(), businessOrderDO.getOrderNo(), businessOrderDO.getPayPrice(), description);
                //眼科接诊时更新眼科通状态
                if (!flag){
                    if (businessOrderDO!=null){
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(),"2");
                    }
                }
            } else if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
/*
                businessOrderService.ylzOrderRefund(wxId, wlyyOutpatientDO.getPatient(), businessOrderDO.getOrderNo(), businessOrderDO.getPayPrice(), description);
*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        rs.put("code", 1);
        rs.put("mes", "取消成功");
        rs.put("patientName",wlyyOutpatientDO.getPatientName());
        rs.put("doctor",wlyyOutpatientDO.getDoctor());
        rs.put("doctorName",wlyyOutpatientDO.getDoctorName());
        rs.put("patientCode",wlyyOutpatientDO.getPatient());
        return rs;
    }

    /**
     * 发送微信模板消息  本地无法测试消息是否发送成功
     * @param wxId
     * @param outpatientId
     * @param type
     * @param titelType
     * @param remindMsg
     */
    public void sendWxTemplateMsg(String wxId, String outpatientId,ConsultTeamDo consultTeam,  String type, String titelType, String remindMsg) {

        BaseDoctorDO consDoctorDO = new BaseDoctorDO();
        BasePatientDO consPatientDO = new BasePatientDO();
        BaseDoctorHospitalDO hospitalDO = new BaseDoctorHospitalDO();
        //获取咨询的信息
        String msgUrl="";
        if (consultTeam!=null){
            consDoctorDO = baseDoctorDao.findById(consultTeam.getDoctor());
            consPatientDO = basePatientDao.findById(consultTeam.getPatient());
            List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(consultTeam.getDoctor());
            if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()>=0){
                hospitalDO=doctorHospitalDOS.get(0);
            }
        }

        WlyyOutpatientDO outpatientDO = new WlyyOutpatientDO();
        BaseDoctorDO doctorDO = new BaseDoctorDO();
        BasePatientDO patientDO = new BasePatientDO();
        if (StringUtils.isNotEmpty(outpatientId)){
            outpatientDO = outpatientDao.findById(outpatientId);
            doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
            patientDO = basePatientDao.findById(outpatientDO.getConsumer());
        }

        logger.info("titelType:"+titelType+"&&remindMsg:"+remindMsg+"&&type"+type);


        String contentMsg = "";
        String first = "";
        String remark = "";
        if ("doctorRefuseRemind".equalsIgnoreCase(titelType)) {
            //医生拒绝接诊
            if ("9".equals(type)) {
                contentMsg = "医生已取消您的复诊申请，取消原因:"+remindMsg;
                first = outpatientDO.getConsumerName() + "，您好！您的图文复诊已取消";
            }
            if ("16".equals(type)) {
                contentMsg = "医生已取消您的复诊申请，取消原因:"+remindMsg;
                first = outpatientDO.getConsumerName() + "，您好！您的视频复诊已取消";
            }
            if ("1".equals(type)) {
                contentMsg = "医生已取消您的复诊申请，取消原因:"+remindMsg;
                first = outpatientDO.getConsumerName() + "，您好！您的图文咨询已取消";
            }
            if ("17".equals(type)) {
                contentMsg = "医生已取消您的复诊申请，取消原因:"+remindMsg;
                first = outpatientDO.getConsumerName() + "，您好！您的视频咨询已取消";
            }
            logger.info("doctorRefuseRemind医生拒诊入参:outpatientId="+outpatientId);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        } else if("outPatientTimeOutRemind".equalsIgnoreCase(titelType)) {
            //医生未接诊时患者等待时间过长的模板提示
            contentMsg = "您邀请的医师暂无应答，您可以选择继续等待或者取消邀请。";
            first = outpatientDO.getConsumerName() + "，您好！";
            logger.info("outPatientTimeOutRemind:outpatientId="+outpatientId+"contentMsg"+contentMsg);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        }else if("doctorPick".equalsIgnoreCase(titelType)) {
            if ("9".equals(type)) {
                contentMsg = "您发起的图文复诊已被"+outpatientDO.getDoctorName()+"接诊，请留意医生发送的消息。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的图文复诊，医生已接诊";
            }
            if ("16".equals(type)) {
                contentMsg =  "您发起的视频复诊已被"+outpatientDO.getDoctorName()+"接诊，请留意医生发送的消息。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的视频复诊，医生已接诊";
            }
            if ("1".equals(type)) {
                contentMsg =  "您发起的图文咨询已被"+outpatientDO.getDoctorName()+"接诊，请留意医生发送的消息。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的图文咨询，医生已接诊";
            }
            if ("17".equals(type)) {
                contentMsg = "您发起的视频咨询已被"+outpatientDO.getDoctorName()+"接诊，请留意医生发送的消息。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的视频咨询，医生已接诊";
            }
            if ("12".equals(type)) {
                contentMsg = "您发起的专科协同已被"+outpatientDO.getDoctorName()+"接诊，请留意医生发送的消息。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的专科协同，医生已接诊";
                return;
            }
            if ("15".equals(type)) {
                contentMsg = "您发起的家医咨询已被"+outpatientDO.getDoctorName()+"接诊，请留意医生发送的消息。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的家医咨询，医生已接诊";
            }
            logger.info("doctorPick诊查费支付成功推送模板消息:outpatientId="+outpatientId);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        } else if("doctorRefund".equalsIgnoreCase(titelType)) {
            if ("9".equals(type)) {
                contentMsg = "金额已退到门诊预交金。如需退款（18元）请到门诊收费处退款。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的图文复诊已退号";
            }
            if ("16".equals(type)) {
                contentMsg =  "金额已退到门诊预交金。如需退款（18元）请到门诊收费处退款。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的视频复诊已退号";
            }
            if ("1".equals(type)) {
                contentMsg =  "金额已退到门诊预交金。如需退款（18元）请到门诊收费处退款。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的图文咨询已退号";
            }
            if ("17".equals(type)) {
                contentMsg = "金额已退到门诊预交金。如需退款（18元）请到门诊收费处退款。";
                first = outpatientDO.getConsumerName() + "，您好！您发起的视频咨询已退号";
            }
            logger.info("doctorRefund:outpatientId="+outpatientId);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        } else if("patientCancel".equalsIgnoreCase(titelType)) {
            if ("9".equals(type)) {
                contentMsg = "您发起的图文复诊已被您取消。由于订单取消将不做扣费处理。";
                first = outpatientDO.getConsumerName() + "，您好！您的图文复诊已被您取消，您可重新发起";
            }
            if ("16".equals(type)) {
                contentMsg =  "您发起的视频复诊已被您取消。由于订单取消将不做扣费处理。";
                first = outpatientDO.getConsumerName() + "，您好！您的视频复诊已被您取消，您可重新发起";
            }
            if ("1".equals(type)) {
                contentMsg =  "您发起的图文咨询已被您取消。由于订单取消将不做扣费处理。";
                first = outpatientDO.getConsumerName() + "，您好！您的图文咨询已被您取消，您可重新发起";
            }
            if ("17".equals(type)) {
                contentMsg = "您发起的视频咨询已被您取消。由于订单取消将不做扣费处理。";
                first = outpatientDO.getConsumerName() + "，您好！您的视频咨询已被您取消，您可重新发起";
            }
            if ("12".equals(type)) {
                return;
            }
            logger.info("patientCancel诊查费支付成功推送模板消息:outpatientId="+outpatientId);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        }else if("systemCancelRemind".equalsIgnoreCase(titelType)){
            //超过24小时未接诊，系统取消
            if ("9".equals(type)) {
                contentMsg = "由于订单取消将不做扣费处理。如需退款（18元）请到门诊收费处退款。";
                first = outpatientDO.getConsumerName() + "，您好！您的图文复诊因超过24小时未接诊已自动取消图文咨询。";
            }
            if ("16".equals(type)) {
                contentMsg = "由于订单取消将不做扣费处理。如需退款（18元）请到门诊收费处退款。";
                first = outpatientDO.getConsumerName() + "，您好！您的视频复诊因超过24小时未接诊已自动取消视频咨询。";
            }
            logger.info("系统取消接诊入参:outpatientId="+outpatientId);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        } else if ("payRemind".equalsIgnoreCase(titelType)) {
            //患者发起时提醒患者支付诊费消息
            if ("9".equals(type)) {
                contentMsg = "请您先完成预交金充值发起在线问诊，点击详情进行预交金充值，如您已完成请忽略本条信息。";//您有一个图文复诊订单待支付，点击完成支付，如您已支付请忽略本条信息
                first = outpatientDO.getConsumerName() + "，您好！您有一笔未完成的在线问诊订单，请及时处理。";//您有一个图文复诊订单待支付，请及时支付。
                msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
                logger.info("图文复诊订单待支付微信消息模板推送开始");
            } else if ("16".equals(type)) {
                contentMsg = "请您先完成预交金充值发起在线问诊，点击详情进行预交金充值，如您已完成请忽略本条信息。";//您有一个视频复诊订单待支付，点击完成支付，如您已支付请忽略本条信息
                first = outpatientDO.getConsumerName() + "，您好！您有一笔未完成的在线问诊订单，请及时处理。";//您有一个视频复诊订单待支付，请及时支付。
                msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
                logger.info("视频复诊订单待支付微信消息模板推送开始");
            }else if ("1".equals(type)) {
                contentMsg = "您有一个图文咨询订单待支付，点击完成支付，如您已支付请忽略本条信息";
                msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
                first = outpatientDO.getConsumerName() + "，您好！您有一个图文咨询订单待支付，请及时支付。";
                logger.info("图文咨询订单待支付微信消息模板推送开始");
            } else if ("17".equals(type)) {
                contentMsg = "您有一个视频咨询订单待支付，点击完成支付，如您已支付请忽略本条信息";
                msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
                first =  outpatientDO.getConsumerName() + "，您好！您有一个视频咨询订单待支付，请及时支付。";
                logger.info("视频咨询订单待支付微信消息模板推送开始");
            }else {
                return;
            }
        } else if ("paySuccess".equalsIgnoreCase(titelType)) {
            if ("9".equals(type)) {
                contentMsg = "您已成功发起图文复诊，请耐心等待医生接单。如长时间未接诊，建议选择其他医生";
                first = outpatientDO.getConsumerName() + "，您好！您已成功发起图文复诊";
            }else if ("16".equals(type)) {
                contentMsg =  "您已成功发起视频复诊，请耐心等待医生接单。如长时间未接诊，建议选择其他医生";
                first = outpatientDO.getConsumerName() + "，您好！您已成功发起视频复诊";
            }else if ("1".equals(type)) {
                contentMsg =  "您已成功发起图文咨询，请耐心等待医生接单。如长时间未接诊，建议选择其他医生";
                first = outpatientDO.getConsumerName() + "，您好！您已成功发起图文咨询";
            }else if ("17".equals(type)) {
                contentMsg = "您已成功发起视频咨询，请耐心等待医生接单。如长时间未接诊，建议选择其他医生";
                first = outpatientDO.getConsumerName() + "，您好！您已成功发起视频咨询";
            }else {
                return;
            }
            logger.info("paySuccess诊查费支付成功推送模板消息:outpatientId="+outpatientId);
            msgUrl="/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientId;
        }else if ("prescriptionPayRemind".equalsIgnoreCase(titelType)) {
            //开具处方后向患者发送支付提醒
            first = outpatientDO.getConsumerName() + "，您好！ 医生已为您开具处方，请及时支付。";
            contentMsg = "医生已为您开具处方，请及时支付。";
            remark = "点击完成支付，如您已支付请忽略本条信息";
            msgUrl="/ims-wx/index.html#/returnVisit/prescriptionDetail?outpatientId="+outpatientId+"&id="+remindMsg;
            logger.info("处方支付微信消息模板推送开始");
        } else if ("videoOrderRemind".equalsIgnoreCase(titelType)) {
            //视频复诊预约提醒
            if ("16".equals(type)) {
                msgUrl="/ims-wx/index.html#/returnVisit/preChat?type=16&outpatientId="+outpatientId;
                if (StringUtils.isNoneBlank(outpatientDO.getDoctorName())){
                    first = "您的视频复诊已预约成功。";
                    contentMsg = "预计" + outpatientDO.getDoctorName() + "医生将于" + DateUtil.dateToStrLong(outpatientDO.getRegisterDate()) + " 与您进行视频复诊。请留意微信公众号消息。";
                }else {
                    first = outpatientDO.getPatientName()+"您好！您已成功发起快速视频复诊。";
                    contentMsg = "您已预约" + DateUtil.dateToStrLong(consultTeam.getCzrq()) +  "的视频复诊 与您进行视频复诊。请留意微信公众号消息。请耐心等待医生接单。如长时间无医生接单，建议选择医生发起视频复诊";
                }
                logger.info("视频复诊已预约成功微信消息模板推送开始");
            } else if ("17".equals(type)) {
                if (StringUtils.isNotEmpty(outpatientId)){
                    msgUrl="/ims-wx/index.html#/returnVisit/preChat?type=17&outpatientId="+outpatientId;
                    if (StringUtils.isNoneBlank(outpatientDO.getDoctorName())){
                        first = "您的视频咨询已预约成功。";
                        contentMsg = "预计" + outpatientDO.getDoctorName() + "医生将于" + DateUtil.dateToStrLong(outpatientDO.getRegisterDate()) + " 与您进行视频咨询。请留意微信公众号消息。";

                    }else{
                        first = outpatientDO.getPatientName()+"您好！您已成功发起快速视频咨询。";
                        contentMsg = "您已预约" + DateUtil.dateToStrLong(outpatientDO.getRegisterDate()) +  "的视频咨询 与您进行视频咨询。请留意微信公众号消息。请耐心等待医生接单。如长时间无医生接单，建议选择医生发起视频咨询";
                    }

                }else{
                    msgUrl="/ims-wx/index.html#/zx/prechat?consultCode="+consultTeam.getConsult();
                    contentMsg = "预计" + consDoctorDO.getName() + "医生将于" + DateUtil.dateToStrLong(outpatientDO.getRegisterDate()) + " 与您进行视频咨询。请留意微信公众号消息。";

                }
                logger.info("视频咨询已预约成功微信消息模板推送开始");
            }
            remark = "咨询开始时，医生将邀请您进行视频通话，请您关注消息提醒，及时接受医生视频邀请。";
        } else if ("evaluateRemind".equalsIgnoreCase(titelType)) {
            //服务评价提醒
            if (consultTeam.getType()!=null&&1==consultTeam.getType()){
                first = consultTeam.getName() + "，您好！您有1条图文咨询已结束，请及时对咨询医生进行评价。";
                logger.info("图文咨询服务评价微信消息模板推送开始");
            }else if (consultTeam.getType()!=null&&9==consultTeam.getType()){
                first = consultTeam.getName() + "，您好！您有1条图文复诊已结束，请及时对咨询医生进行评价。";
                logger.info("图文复诊服务评价微信消息模板推送开始");
            }else if (consultTeam.getType()!=null&&16==consultTeam.getType()){
                first = consultTeam.getName() + "，您好！您有1条视频复诊已结束，请及时对咨询医生进行评价。";
                logger.info("视频复诊服务评价微信消息模板推送开始");
            }else if (consultTeam.getType()!=null&&17==consultTeam.getType()){
                first = consultTeam.getName() + "，您好！您有1条视频咨询已结束，请及时对咨询医生进行评价。";
                logger.info("视频咨询服务评价微信消息模板推送开始");
            }else {
                return;
            }
            contentMsg = "请对" + consDoctorDO.getName() + "医生的服务进行评价";
            msgUrl="/ims-wx/index.html#/fuwupingjia?consultCode="+consultTeam.getConsult();
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)||"sd_tnzyy_wx".equalsIgnoreCase(wxId)) {
            List<BasePatientWechatDo> ps = new ArrayList<BasePatientWechatDo>();
            if (StringUtils.isNotEmpty(outpatientId)){
                ps = basePatientWechatDao.findByWechatIdAndPatientId(wxId, outpatientDO.getConsumer());
            }
            if (consultTeam!=null){
                ps = basePatientWechatDao.findByWechatIdAndPatientId(wxId, consultTeam.getPatient());
            }

            if (ps.isEmpty()) {
                logger.info("该用户" + outpatientDO.getConsumerName() + "没有openid,无法推送模版消息，用户ID：" + outpatientDO.getPatient() + "wechatId:" + wxId);
                return;
            }
            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.getConsumerName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                }
                newConfig.setKeyword1( outpatientDO.getHospitalName());
                newConfig.setKeyword2(outpatientDO.getDoctorName());
                newConfig.setKeyword3( doctorDO.getFee());
                newConfig.setPagepath(newConfig.getPagepath() + "" + outpatientDO.getId());
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("眼科微信消息模板推送 医生拒诊开始");
                logger.info("极光消息推送 医生拒诊开始");
                wxTempalteJPush("cancel_remind",outpatientDO,null,"","","","");
                /*String res = wxTempalteJPush(outpatientDO.getConsumer(),newConfig.getFirst(),"医生拒绝了你的问诊",type,outpatientDO.getId());
                logger.info("JPUSH res==="+res);*/
            }else if("outPatientTimeOutRemind".equals(titelType)){
                //就诊等待过长提示
                scene="jzddgcts";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_outpatient_timeout_remind", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setPagepath(newConfig.getPagepath() + "" + outpatientDO.getId());
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("就诊等待过长提示");
            } else if ("payRemind".equalsIgnoreCase(titelType)) {
                //诊费支付提示
                scene = "zxzfts";
                //就诊支付
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_pay_notice_jz", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getConsumerName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                    newConfig.setKeyword1( "图文复诊支付");
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                    newConfig.setKeyword1( "视频复诊支付");
                }
                if ("1".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文咨询"));
                    newConfig.setKeyword1("图文咨询支付");
                } else if ("17".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频咨询"));
                    newConfig.setKeyword1("视频咨询支付");
                }
                newConfig.setKeyword2(outpatientDO.getHospitalName());
                newConfig.setKeyword3(outpatientDO.getDoctorName());
                String path = "returnVisit/record?outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath()+URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("眼科微信消息模板推送 就诊支付提醒开始");
                logger.info("极光消息推送 就诊支付提醒开始");
                wxTempalteJPush("outpatient_pay",outpatientDO,null,"","","","");
            } else if ("paySuccess".equalsIgnoreCase(titelType)) {
                //诊费支付成功提示
                scene = "zfcgtx";
                //就诊支付
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_pay_success", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getConsumerName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                    newConfig.setKeyword1( "图文复诊支付");
                    newConfig.setRemark(config.getRemark().replace("key2","图文复诊"));
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                    newConfig.setRemark(config.getRemark().replace("key2","视频复诊"));
                    newConfig.setKeyword1( "视频复诊支付");
                }
                if ("1".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文咨询"));
                    newConfig.setRemark(config.getRemark().replace("key2","图文咨询"));
                    newConfig.setKeyword1("图文咨询支付");
                } else if ("17".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频咨询"));
                    newConfig.setRemark(config.getRemark().replace("key2","视频咨询"));
                    newConfig.setKeyword1("视频咨询支付");
                }
                newConfig.setKeyword2(outpatientDO.getHospitalName());
                newConfig.setKeyword3(outpatientDO.getDoctorName());
                String path = "returnVisit/record?outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath() +URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
            } else if ("doctorPick".equalsIgnoreCase(titelType)) {
                //诊费支付成功提示
                scene = "ysjzts";
                //就诊支付
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_doctor_pick", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getConsumerName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                    newConfig.setKeyword1( "图文复诊接诊");
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                    newConfig.setKeyword1( "视频复诊接诊");
                }
                if ("1".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文咨询"));
                    newConfig.setKeyword1("图文咨询接诊");
                } else if ("17".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频咨询"));
                    newConfig.setKeyword1("视频咨询接诊");
                }
                newConfig.setRemark(config.getRemark().replace("key1",outpatientDO.getDoctorName()));
                newConfig.setKeyword2(outpatientDO.getHospitalName());
                newConfig.setKeyword3(outpatientDO.getDoctorName());
                String path = "returnVisit/record?outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath() +URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
            }else if ("patientCancel".equalsIgnoreCase(titelType)) {
                scene = "hzqxfz";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_patient_cancel", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getConsumerName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                }else if ("1".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文咨询"));
                } else if ("17".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频咨询"));
                }
                newConfig.setKeyword1( outpatientDO.getHospitalName());
                newConfig.setKeyword2(outpatientDO.getDoctorName());
                newConfig.setKeyword3(outpatientDO.getFee()==null?"0":outpatientDO.getFee().toString());
                String path = "returnVisit/record?outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath() + URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("眼科微信消息模板推送");
            }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.getConsumerName()));
                newConfig.setKeyword1( "处方支付");
                newConfig.setKeyword2(outpatientDO.getHospitalName());
                newConfig.setKeyword3(outpatientDO.getDoctorName());
                String path = "returnVisit/preChat?type=16&outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath()+URLEncoder.encode(path) );
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("眼科微信消息模板推送 处方支付提醒开始");
                logger.info("极光消息推送 医生拒诊开始");
                wxTempalteJPush("prescription_pay",outpatientDO,null,"","","",remindMsg);
            }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", "视频复诊"));
                }
                if ("17".equals(type)) {
                    newConfig.setFirst(config.getFirst().replaceFirst("key1", "视频咨询"));
                }
                newConfig.setKeyword1( outpatientDO.getConsumerName());
                newConfig.setKeyword2( outpatientDO.getDeptName());
                newConfig.setKeyword3( outpatientDO.getDoctorName());
                newConfig.setKeyword4(DateUtil.dateToStrLong(outpatientDO.getRegisterDate()));
                newConfig.setKeyword5(generalDoctorWaitingNumber(doctorDO.getId(), wxId, outpatientId));
                String path = "returnVisit/record?outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath() +URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("眼科微信消息模板推送 视频问诊预约提醒开始");
            } 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", consPatientDO.getName()));
                newConfig.setKeyword2(hospitalDO.getOrgName());
                newConfig.setKeyword3(consDoctorDO.getName());
                String path = "fuwupingjia?consultCode="+consultTeam.getConsult();
                newConfig.setPagepath(newConfig.getPagepath()+URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + consultTeam.getConsult());
                logger.info("极光消息推送 医生拒诊开始");
                wxTempalteJPush("give_score",null,consultTeam,"","","","");
                logger.info("眼科微信消息模板推送 服务评价提醒开始");
            } else if ("systemCancelRemind".equalsIgnoreCase(titelType)) {
                //系统24小时取消复诊提醒
                scene = "xtqxfz";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_system_cancel", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getConsumerName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                }else if ("1".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文咨询"));
                } else if ("17".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频咨询"));
                }
                newConfig.setKeyword1( outpatientDO.getHospitalName());
                newConfig.setKeyword2(outpatientDO.getDoctorName());
                newConfig.setKeyword3(outpatientDO.getFee()==null?"0":outpatientDO.getFee().toString());
                String path = "returnVisit/record?outpatientId="+outpatientDO.getId();
                newConfig.setPagepath(newConfig.getPagepath() +URLEncoder.encode(path));
                //发起微信消息模板推送
                newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
                logger.info("眼科微信消息模板推送 系统拒诊开始");
            }
            logger.info("=======setUrl========" + newConfig.getUrl());
            WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
            for (BasePatientWechatDo one : ps) {
                logger.info("发送的消息="+ com.alibaba.fastjson.JSONObject.toJSONString(newConfig));
                try {
                    logger.info("调用眼科微信模板消息接口的入参：AccessToken="+wxAccessTokenDO.getAccessToken()+"---Openid="+one.getOpenid());
                    weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), one.getOpenid(), newConfig);
                    logger.info("发送成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("发送失败，error="+e.getMessage());
                }

                //保存发送模板记录,
                WxPushLogDO wxPushLogDO = new WxPushLogDO();
                wxPushLogDO.setCreateTime(new Date());
                wxPushLogDO.setOpenid(one.getOpenid());
                wxPushLogDO.setReceiver(outpatientDO.getPatient());
                wxPushLogDO.setWechatId(wechatId);
                wxPushLogDO.setReceiverName(outpatientDO.getConsumerName());
                wxPushLogDO.setScene(scene);
                wxPushLogDao.save(wxPushLogDO);
            }

        } else if ("xm_xzzx_wx".equalsIgnoreCase(wxId)) {
            String responseMsg="";
            //String prefix="https://www.xmheart.com";
            String prefix = "https://ih.xmheart.com/hlwyy";
            if(StringUtils.isNotEmpty(outpatientId)){
                responseMsg = xzzxEntranceService.sendMes(wxId,
                        patientDO.getId(),
                        patientDO.getIdcard(),
                        first,
                        contentMsg,
                        remark,
                        prefix+msgUrl);
            }
            if (consultTeam!=null&&consPatientDO!=null){
                responseMsg = xzzxEntranceService.sendMes(wxId,
                        consPatientDO.getId(),
                        consPatientDO.getIdcard(),
                        first,
                        contentMsg,
                        remark,
                        prefix+msgUrl);
            }
            logger.info("url="+prefix+msgUrl);
            String msg="first："+first+"contentMsg："+contentMsg+"remark："+remark;
            logger.info("发送的信息="+msg);
            logger.info("XZZX_Msg_" + titelType + "=" + responseMsg);

        } else if ("xm_zsyy_wx".equalsIgnoreCase(wxId)) {
            String responseMsg="";
            String prefix="https://hlwyy.xmzsh.com";
            if(StringUtils.isNotEmpty(outpatientId)){
                responseMsg = entranceService.ehospitalNotice(
                        patientDO.getName(),
                        patientDO.getIdcard(),
                        patientDO.getMobile(),
                        first,
                        prefix+msgUrl,
                        contentMsg,
                        remark
                );
                System.out.println("结束发送模板消息");
            }
            if (consultTeam!=null&&consPatientDO!=null){
                responseMsg = entranceService.ehospitalNotice(
                        consPatientDO.getName(),
                        consPatientDO.getIdcard(),
                        consPatientDO.getMobile(),
                        first,
                        prefix+msgUrl,
                        contentMsg,
                        remark
                );
            }
            logger.info("url="+prefix+msgUrl);
            String msg="first："+first+"-----contentMsg："+contentMsg+"-----remark："+remark;
            logger.info("发送的信息="+msg);
            logger.info("ZSYY_Msg" + titelType + "=" + responseMsg);
        }
    }

    /**
     * 发送顺丰物流提醒模板消息
     * @param outpatientId
     */
    public void sendSFWxTemplate(String outpatientId,String prescriptionId,String routeCode){
        String contentMsg = "";
        String first = "";
        String remark = "";
        String patientId = "";
        String drugName = "";
        String remindMsg="";
        String patienName = "";
        String mailNo ="";
        String msgUrl ="";
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
        List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId,1);
        if (wlyyOutpatientDO!=null){
            patientId = wlyyOutpatientDO.getConsumer();
        }
        if (wlyyPrescriptionInfoDOS!=null&&wlyyPrescriptionInfoDOS.size()>0){
            drugName = wlyyPrescriptionInfoDOS.get(0).getDrugName();
        }
        List<WlyyPrescriptionExpressageDO> wlyyPrescriptionExpressageDOS =prescriptionExpressageDao.findByOutpatientId(outpatientId);
        if (wlyyPrescriptionExpressageDOS!=null&&wlyyPrescriptionExpressageDOS.size()>0){
            mailNo = wlyyPrescriptionExpressageDOS.get(0).getMailno();
        }
        switch (routeCode) {
            case "50":
                remindMsg = "已发出";
                break;
            case "204":
                remindMsg = "已在派件";
                break;
            case "80":
                remindMsg = "已签收";
                break;
            case "8000":
                remindMsg = "已签收";
                break;
        }
        BasePatientDO basePatientDO = basePatientDao.findById(patientId);
        if (basePatientDO!=null){
            patienName = basePatientDO.getName();
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)||"sd_tnzyy_wx".equalsIgnoreCase(wechatId)){
            List<BasePatientWechatDo> ps = new ArrayList<BasePatientWechatDo>();
            if (StringUtils.isNotEmpty(outpatientId)){
                ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId, patientId);
            }
            if (ps.isEmpty()) {
                logger.info("该用户" + patienName + "没有openid,无法推送模版消息，用户ID：" + patientId + "wechatId:" + wechatId);
                return;
            }
            WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
            String scene = "sfxxtx";
            WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_sf_msg_notice", scene, 1);
            BeanUtils.copyProperties(config, newConfig);

            newConfig.setFirst(config.getFirst().replace("key1",remindMsg));
            newConfig.setKeyword1(config.getKeyword1().replace("key1",patienName).replace("key2",drugName));
            newConfig.setKeyword2("顺丰快递");
            newConfig.setKeyword3(mailNo);
            newConfig.setKeyword4(remindMsg);
            newConfig.setRemark(config.getRemark());
            String path = "returnVisit/logistics?outpatientId="+outpatientId+"&prescriptionCode="+prescriptionId;

            newConfig.setPagepath(newConfig.getPagepath()+ URLEncoder.encode(path));
            newConfig.setUrl(newConfig.getUrl().replace("key1",outpatientId).replace("key2",prescriptionId));
            logger.info("=======setUrl========" + newConfig.getUrl());
            WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
            for (BasePatientWechatDo one : ps) {
                logger.info("发送的消息="+ com.alibaba.fastjson.JSONObject.toJSONString(newConfig));
                try {
                    logger.info("调用眼科微信模板消息接口的入参：AccessToken="+wxAccessTokenDO.getAccessToken()+"---Openid="+one.getOpenid());
                    weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), one.getOpenid(), newConfig);
                    logger.info("发送成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("发送失败，error="+e.getMessage());
                }

                //保存发送模板记录,
                WxPushLogDO wxPushLogDO = new WxPushLogDO();
                wxPushLogDO.setCreateTime(new Date());
                wxPushLogDO.setOpenid(one.getOpenid());
                wxPushLogDO.setReceiver(patientId);
                wxPushLogDO.setWechatId(wechatId);
                wxPushLogDO.setReceiverName(patienName);
                wxPushLogDO.setScene(scene);
                wxPushLogDao.save(wxPushLogDO);
            }
            //发送极光消息推送
           wxTempalteJPush("logistics_remind",wlyyOutpatientDO,null,drugName,mailNo,remindMsg,prescriptionId);
        }else {
            first = "您好，您的处方订单物流"+remindMsg;
            contentMsg = "患者"+wlyyOutpatientDO.getPatientName()+"的处方药品订单，"+drugName+"等，当前"+remindMsg+"。物流方：「顺丰快递」，物流单号："+mailNo+"。";
            logger.info("推送物流模板消息参数first："+first+"====contentMsg:"+contentMsg);
            msgUrl="/ims-wx/index.html#/returnVisit/logistics?outpatientId="+outpatientId+"&prescriptionCode="+prescriptionId;
            String responseMsg = "";
            if ("xm_xzzx_wx".equalsIgnoreCase(wechatId)) {
                //String prefix="https://www.xmheart.com";
                String prefix = "https://ih.xmheart.com/hlwyy";
                if(StringUtils.isNotEmpty(outpatientId)){
                    responseMsg = xzzxEntranceService.sendMes(wechatId,
                            patientId,
                            basePatientDO.getIdcard(),
                            first,
                            contentMsg,
                            remark,
                            prefix+msgUrl);
                }
                logger.info("url="+prefix+msgUrl);
                String msg="first："+first+"contentMsg："+contentMsg+"remark："+remark;
                logger.info("发送的信息="+msg);
                logger.info("心脏模板消息发送返回结果："+responseMsg);
            } else if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)) {
                String prefix = "https://hlwyy.xmzsh.com";
                if (StringUtils.isNotEmpty(outpatientId)) {
                    responseMsg = entranceService.ehospitalNotice(
                            patienName,
                            basePatientDO.getIdcard(),
                            basePatientDO.getMobile(),
                            first,
                            prefix + msgUrl,
                            contentMsg,
                            remark
                    );
                    logger.info("中山发送模板消息返回结果="+responseMsg);
                    System.out.println("结束发送模板消息");
                }
            }
            //保存发送模板记录,
            WxPushLogDO wxPushLogDO = new WxPushLogDO();
            wxPushLogDO.setCreateTime(new Date());
            wxPushLogDO.setReceiver(patientId);
            wxPushLogDO.setWechatId(wechatId);
            wxPushLogDO.setReceiverName(patienName);
            wxPushLogDO.setRequest(first+contentMsg+msgUrl);
            wxPushLogDO.setResponse(responseMsg);
            wxPushLogDO.setTempName("顺丰推送的物流消息");
            wxPushLogDao.save(wxPushLogDO);
        }



    }
    //核算检测预约模板消息
    public void sendNatWxTemplat(String name,String idcard,String mobile,String time,String orderNo,String relationName){
        String first = "";
        String contentMsg = "";
        String msgUrl="";
        String remark="";
        String responseMsg="";
        if ("natAppointmentRemind".equalsIgnoreCase(relationName)){
            first = "尊敬的用户"+name+"，您已完成线上自助核酸检测开单预约";
            contentMsg = "申请人："+name+";预约时间："+time+";发票流水号："+orderNo;
            remark="请您持核酸开单预约信息和结算发票号、医保卡、就诊卡、电子健康卡，提前15分钟至我院五号楼北侧（急诊部后侧）核酸检测点2号窗口绑定检测。";
        }
        if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)) {
            String prefix = "https://hlwyy.xmzsh.com";
            responseMsg = entranceService.ehospitalNotice(
                    name,
                   idcard,
                    mobile,
                    first,
                    prefix + msgUrl,
                    contentMsg,
                    remark);
                logger.info("中山发送模板消息返回结果="+responseMsg);
                System.out.println("结束发送模板消息");
        }else if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)) {
            String prefix = "https://hlwyy.xmzsh.com";
                responseMsg = entranceService.ehospitalNotice(
                        name,
                        idcard,
                        mobile,
                        first,
                        prefix + msgUrl,
                        contentMsg,
                        remark
                );
                logger.info("心脏发送模板消息返回结果="+responseMsg);
                System.out.println("结束发送模板消息");
        }
        //保存发送模板记录,
        WxPushLogDO wxPushLogDO = new WxPushLogDO();
        wxPushLogDO.setCreateTime(new Date());
        wxPushLogDO.setWechatId(wechatId);
        wxPushLogDO.setReceiverName(name);
        wxPushLogDO.setRequest(first+contentMsg+msgUrl);
        wxPushLogDO.setResponse(responseMsg);
        wxPushLogDO.setTempName("核算检测预约模板消息");
        wxPushLogDao.save(wxPushLogDO);

    }

    public List<WlyyHospitalSysDictDO> findCancelReasonList() {
        return sysDictDao.findByDictName("PatientCancel");
    }

    /**
     * 獲取快速咨詢時間
     *
     * @return
     */
    public List<Map<String, Object>> findFastRegisterDate() {
        int days = 7;
        String AMStartTime = "8:00";
        String AMEndTime = "12:00";
        String PMStartTime = "14:00";
        String PMEndTime = "17:00";

        //设置上午过号时间
        Calendar scTime = Calendar.getInstance();
        scTime.setTime(new Date());

        Calendar ecTime = Calendar.getInstance();
        ecTime.setTime(new Date());

        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));

            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"));

            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"));
            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));

            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"));

            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"));
            times.add(time2);
            //生成下一天
            scTime.add(Calendar.DAY_OF_MONTH, 1);
        }

        if (DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM).after(DateUtil.strToDate(AMEndTime, DateUtil.HH_MM))) {
            times.remove(0);
        }
        if (DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM).after(DateUtil.strToDate(PMEndTime, DateUtil.HH_MM))) {
            times.remove(0);
        }
        return times;
    }
    /**
     * 医生可接单列表(图文复诊、视频复诊、协同门诊)
     *
     * @param doctor
     * @param type   1：图文诊室，2:视频诊室（视频复诊、协同门诊）
     * @return
     * @query_status 0:图文复诊候诊 1:图文复诊抢单列表
     * @dept 部门
     */
    public List<Map<String, Object>> findWaitingRoomOutpatientByDoctor(String doctor, Integer type, Integer query_status, String dept,String sex,String keyword,String ageGroup,String patient) {

        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "outpatient.patient_name AS \"outPatientName\"," +
                "outpatient.patient AS \"outPatient\"," +
                "patient.sex AS \"sex\"," +
                "patient.idcard AS \"idcard\"," +
                "patient.photo AS \"photo\"," +
                "outpatient.mobile AS \"mobile\"," +
                "patient.birthday AS \"birthday\"," +
                "room.consult_type AS \"consult_type\"," +
                "outpatient.consumer as \"consumer\", " +
                "outpatient.consumer_name as \"consumerName\"," +
                "outpatient.consumer_mobile as \"consumerMobile\", "+
                "outpatient.create_time as \"create_date\", ";
        if ("xm_ykyy_wx".equals(wechatId)) {
            if(flag){
                sql += "date_format(room.reservation_time ,'yyyy-MM-dd hh24:mi:ss' ) AS \"timedate_format\",";
            }else {
                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\"," +
                "outpatient.description AS \"description\"," +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.origin_con_no AS \"origin_con_no\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "room.patient_id=patient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.status = 0 ";
        //视频复诊，协同门诊 医生抢单
        if (type == 2) {
            sql += "AND room.doctor IS NULL ";
        } else {
            //图文复诊候诊列表
            if (0 == query_status) {
                sql += "AND room.doctor='" + doctor + "' ";
            } else {
                //图文复诊医生抢单列表
                sql += "AND room.doctor IS NULL  ";
            }

        }

        //协同门诊
        if (3 == type) {
            sql += " AND room.reservation_type=2 ";
        } else if (4==type){
            //专家咨询
            sql += " AND room.reservation_type=3 AND room.consult_type =1";
        } else if (1==type) {
            //在线复诊
            sql += " AND room.reservation_type=1 AND room.consult_type =1";
        }else if (2==type) {//视频复诊
            //在线复诊
            sql += " AND room.reservation_type !=3 AND room.consult_type =2";
        } else if(0==type) {
            sql += " AND room.consult_type =1";
        } else {
            sql += " AND room.reservation_type !=2";
        }

        if (StringUtils.isNoneBlank(dept)) {
            sql += " AND outpatient.dept='" + dept + "' ";
        }
        if(StringUtils.isNoneBlank(sex)){
            sql += " AND patient.sex=" + sex + " ";
        }if(StringUtils.isNoneBlank(keyword)){
            sql += " AND outpatient.patient_name like '%" + keyword + "%' ";
        }
        if(StringUtils.isNoneBlank(patient)){
            sql += " AND (outpatient.patient= '" + patient + "' or outpatient.consumer ='"+patient+"') ";
        }
        if(StringUtils.isNoneBlank(ageGroup)){
            String[] age = ageGroup.split(",");
            Calendar nowBegin = Calendar.getInstance();
            Calendar nowEnd = Calendar.getInstance();
            nowBegin.add(Calendar.YEAR,-Integer.parseInt(age[0]));
            nowEnd.add(Calendar.YEAR,-Integer.parseInt(age[1]));
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String beginAge =  sf.format(nowBegin.getTime());
            String endAge =  sf.format(nowEnd.getTime());
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and patient.birthday > '" + endAge + "' and patient.birthday<'" + beginAge + "'";
                }else {
                    sql+=" and patient.birthday > to_date('" + endAge + "', 'yyyy-mm-dd') and patient.birthday < to_date('" + beginAge + "','yyyy-mm-dd')";
                }
            }else{
                sql+=" and patient.birthday > '" + endAge + "' and patient.birthday<'" + beginAge + "'";
            }

        }

        logger.info("接口名称：findWaitingRoomOutpatientByDoctor-->sql="+sql);
        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");
                Integer patientAge = 0;
                Integer patientSex = 3;
                if (null!=outpatient.get("outPatient")){
                   BasePatientDO basePatientDO = basePatientDao.findById(outpatient.get("outPatient").toString());
                   if (null!=basePatientDO){
                       if (StringUtils.isNotBlank(basePatientDO.getIdcard())){
                           patientAge = DateUtil.getAgeForIdcard(basePatientDO.getIdcard());
                           outpatient.put("patientAge", DateUtil.getAgeForIdcard(basePatientDO.getIdcard()));
                           patientSex =basePatientDO.getSex();
                       }
                   }
                }
                outpatient.put("patientAge", patientAge);
                outpatient.put("patientSex", patientSex);
                outpatient.put("age", DateUtil.getAgeForIdcard(idcard));
            }
        }

        return list;
    }

    public List<Map<String, Object>> findWaitingRoomPatient(String dept, Integer type) {

        String sql = "SELECT " +
                "patient.id AS \"id\"," +
                "patient.name AS \"name\"," +
                "patient.sex AS \"sex\"," +
                "patient.idcard AS \"idcard\"," +
                "patient.photo AS \"photo\"," +
                "waitingroom.reservation_type AS \"type\"," +
                "waitingroom.consult_type AS \"consult_type\"," +
                "waitingroom.reservation_time AS \"reservation_time\" " +
                "FROM " +
                "wlyy_hospital_waiting_room waitingroom," +
                "base_patient patient " +
                "WHERE waitingroom.consult_type=2 AND doctor IS NOT NULL ";

        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));
            }
        }

        return list;
    }

    public JSONObject findWaitingRoomStatusCount(String dept, String wxId) {

        String totalSql = "SELECT count(id) AS \"total\" FROM wlyy_hospital_waiting_room WHERE visit_status=1 ";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                totalSql += " and reservation_time >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                totalSql += " and reservation_time <= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                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);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }

        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);

        return result;
    }

    public List<JSONObject> findClinicRoomList(String dept, String date, String consult_status, String wxId) {
        if (StringUtils.isBlank(date)) {
            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 + "'";

        if (StringUtils.isNoneBlank(dept)) {
            doctorsql = doctorsql + " and dept = '" + dept + "' ";
        }
        doctorsql = doctorsql + " GROUP BY doctor,doctor_name,dept,dept_name";

        List<Map<String, Object>> doctorlist = jdbcTemplate.queryForList(doctorsql);

        HashMap<String, JSONObject> result = new HashMap<>();

        for (int i = 0; i < doctorlist.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            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", "");
            }
            jsonObject.put("visit_status", 1);
            jsonObject.put("visit_count", 0);
            jsonObject.put("offline_count",0);
            jsonObject.put("ending_count",0);
            jsonObject.put("patient_name", "");
            jsonObject.put("time_cost", 0);

            result.put((String) doctorlist.get(0).get("doctor"), jsonObject);
        }

        //获取预约了今天的候诊居民
        String waitingSql = "SELECT count(op.id) AS \"waitCount\"," +
                "room.doctor AS \"doctor\", " +
                "room.doctor_name AS \"doctorName\" " +
                "FROM wlyy_outpatient op,wlyy_hospital_waiting_room room " +
                "WHERE op.status=0 AND room.outpatient_id=op.id AND room.consult_type=2 " +
                "AND room.doctor IS NOT NULL ";
        if (StringUtils.isNoneBlank(dept)) {
            waitingSql = waitingSql + " and op.dept = '" + dept + "' ";
        }

        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                waitingSql += " AND room.reservation_time >= str_to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                waitingSql += " AND room.reservation_time <= str_to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
            }else {
                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) {
            //根据身份证计算年龄
            for (Map<String, Object> waitObj : waitinglist) {
                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("visit_count", waitCount);
                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", doctor);
                        jsonObject.put("visit_status", 1);
                        jsonObject.put("visit_count", waitCount);
                        jsonObject.put("offline_count", 0);
                        jsonObject.put("ending_count", 0);
                        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);
                    }
                }
            }
        }


        //已结束
        String endSql = "SELECT count(op.id) AS \"endCount\"," +
                "room.doctor AS \"doctor\", " +
                "room.doctor_name AS \"doctorName\" " +
                "FROM wlyy_outpatient op,wlyy_hospital_waiting_room room " +
                "WHERE op.status=3 AND room.outpatient_id=op.id AND room.consult_type=2 " +
                "AND room.doctor IS NOT NULL ";
        if (StringUtils.isNoneBlank(dept)) {
            endSql = endSql + " and op.dept = '" + dept + "' ";
        }

        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                endSql += " AND room.reservation_time >= str_to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                endSql += " AND room.reservation_time <= str_to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
            }else {
                endSql += " AND room.reservation_time >= to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                endSql += " AND room.reservation_time <= to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
            }

        } else {
            endSql = endSql + "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>> endlist = jdbcTemplate.queryForList(endSql);
        if (endlist != null && endlist.size() > 0) {
            //根据身份证计算年龄
            for (Map<String, Object> endObj : endlist) {
                String doctor = (String) endObj.get("doctor");
                if (StringUtils.isNoneBlank(doctor)) {
                    Long endCount = Long.parseLong(endObj.get("endCount").toString());
                    if (result.keySet().contains(doctor)) {
                        result.get(doctor).put("ending_count", endCount);
                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", doctor);
                        jsonObject.put("visit_status", 1);
                        jsonObject.put("visit_count",0);
                        jsonObject.put("offline_count", 0);
                        jsonObject.put("ending_count", endCount);
                        if (StringUtils.isNoneBlank((String) endObj.get("doctorName"))) {
                            jsonObject.put("doctor_name", (String) endObj.get("doctorName"));
                        } else {
                            jsonObject.put("doctor_name", "");
                        }
                        jsonObject.put("patient_name", "");
                        jsonObject.put("time_cost", 0);
                        result.put(doctor, jsonObject);
                    }
                }
            }
        }

        //离线
        String disconnectSql = "SELECT count(op.id) AS \"disconnectCount\"," +
                "room.doctor AS \"doctor\", " +
                "room.doctor_name AS \"doctorName\" " +
                "FROM wlyy_outpatient op,wlyy_hospital_waiting_room room ," +
                "base_patient p " +
                "WHERE  room.outpatient_id=op.id AND room.consult_type=2  AND p.id = op.patient" +
                " AND room.doctor IS NOT NULL and (p.on_line=0 OR p.on_line IS NULL) ";
        if (StringUtils.isNoneBlank(dept)) {
            disconnectSql = disconnectSql + " and op.dept = '" + dept + "' ";
        }

        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                disconnectSql += " AND room.reservation_time >= str_to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                disconnectSql += " AND room.reservation_time <= str_to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
            }else {
                disconnectSql += " AND room.reservation_time >= to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                disconnectSql += " AND room.reservation_time <= to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
            }

        } else {
            disconnectSql = disconnectSql + "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>> disconnectlist = jdbcTemplate.queryForList(disconnectSql);
        if (disconnectlist != null && disconnectlist.size() > 0) {
            //根据身份证计算年龄
            for (Map<String, Object> endObj : endlist) {
                String doctor = (String) endObj.get("doctor");
                if (StringUtils.isNoneBlank(doctor)) {
                    Long disconnectCount = Long.parseLong(endObj.get("disconnectCount").toString());
                    if (result.keySet().contains(doctor)) {
                        result.get(doctor).put("offline_count", disconnectCount);
                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", doctor);
                        jsonObject.put("visit_status", 1);
                        jsonObject.put("ending_count",0);
                        jsonObject.put("visit_count",0);
                        jsonObject.put("offline_count", disconnectCount);
                        if (StringUtils.isNoneBlank((String) endObj.get("doctorName"))) {
                            jsonObject.put("doctor_name", (String) endObj.get("doctorName"));
                        } else {
                            jsonObject.put("doctor_name", "");
                        }
                        jsonObject.put("patient_name", "");
                        jsonObject.put("time_cost", 0);
                        result.put(doctor, jsonObject);
                    }
                }
            }
        }


        //获取进行中的居民
        String onlineSql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"patient_name\"," +
                "patient.sex AS \"sex\"," +
                "patient.idcard AS \"idcard\"," +
                "patient.photo AS \"photo\"," +
                "patient.birthday AS \"birthday\"," +
                "room.consult_type AS \"consult_type\",";
        if ("xm_ykyy_wx".equals(wxId)) {
            if(flag){
                onlineSql = onlineSql + "date_format(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",ceil((sysdate-to_date(date_format(room.reservation_time,'YYYY-MM-DD hh24:mi:ss'),'YYYY-MM-DD hh24:mi:ss'))* 24 * 60) AS \"time_cost\",";
            }else {
                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 {
            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\", " +
                "room.doctor_name AS \"doctorName\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +
                "wlyy_outpatient outpatient," +
                "wlyy_consult_team consult " +
                "WHERE " +
                "room.patient_id=patient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND consult.status=0 " +
                "AND room.consult_type=2 ";
        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";
*/
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            if (flag){
                onlineSql += " AND room.reservation_time >= str_to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                onlineSql += " AND room.reservation_time <= str_to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') ";
            }else {
                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<Map<String, Object>> onlines = new ArrayList<>();
            for (Map<String, Object> onlineObj : onlinelist) {
                String doctor = (String) onlineObj.get("doctor");
                if (doctors != null && doctors.size() != 0) {
                    if (!doctors.contains(doctor)) {
                        doctors.add(doctor);
                        onlines.add(onlineObj);
                    }
                } else {
                    doctors.add(doctor);
                    onlines.add(onlineObj);
                }
            }
            for (Map<String, Object> onlineObj : onlines) {
                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 {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", doctor);

                        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);
                    }
                }
            }
        }

        List<JSONObject> finalresult = new ArrayList<>();

        for (JSONObject jsonObject : result.values()) {

            //离线：在线状态=离线
            //空闲：在线状态=在线 and 接诊状态=空闲
            //接诊中：在线状态=在线 and 接诊状态=接诊中

            //过滤空闲或者接诊中的居民
            if (StringUtils.isBlank(consult_status)) {
                finalresult.add(jsonObject);
            } else {
                if ("0".equals(consult_status)) {
                    //只显示在线
                } else if ("1".equals(consult_status) && "1".equals(jsonObject.getString("visit_status"))) {
                    //空闲
                    finalresult.add(jsonObject);
                } else if ("2".equals(consult_status) && "2".equals(jsonObject.getString("visit_status"))) {
                    //接诊
                    finalresult.add(jsonObject);
                } else {
                }
            }
        }
        Integer room_no = 1;
        for (JSONObject jsonObject : finalresult) {
            String roomname = "";
            if (room_no < 10) {
                roomname = "0" + room_no + "诊室";
            } else {
                roomname = room_no + "诊室";
            }
            jsonObject.put("room_name", roomname);
            room_no++;
        }

        return finalresult;
    }

    public WlyyDoctorClinicRoomDO findClinicRoomStatus(String id) {
        return wlyyDoctorClinicRoomDao.findOne(id);
    }

    /**
     * 获取快速咨询时间分段
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public List<Map<String, Object>> findByTimeSlot(String startTime, String endTime) {
        int interval = 30;
        List<Map<String, Object>> times = new ArrayList<>();
        //设置上午过号时间
        Calendar scTime = Calendar.getInstance();
        scTime.setTime(DateUtil.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss"));

        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"));
                times.add(time);
            } else {
                scTime.add(Calendar.MINUTE, interval);
            }
        }
        return times;
    }

    /**
     * 根据疾病名称，热门部门查询医生
     *
     * @param orgCode         机构码
     * @param dept            部门CODE
     * @param diseaseKey      疾病名称
     * @param jobTitleNameKey
     * @param outpatientType
     * @param keyName
     * @param workingTime
     * @param consutlSort
     * @return
     */
    @Transactional(readOnly = true)
    public MixEnvelop 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){
            page --;

        if (pagesize <= 0) {
            pagesize = 10;
        }*/
        //testHikar();
        long statr = new Date().getTime();
        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.expertise AS \"expertise\"," +
                " d.introduce AS \"introduce\"," +
                " d.job_title_code AS \"jobTitleCode\", " +
                " d.job_title_name AS \"jobTitleName\"," +
                " d.charge_type AS \"chargeType\"," +
                " h.dept_code AS \"deptCode\"," +
                " h.dept_name AS \"deptName\"," +
                " dw.workTotal AS \"workTotal\","+
                " d.consult_status AS \"consultStatus\"," +
                " d.outpatient_type AS \"outpatientType\"," +
                " a.total AS \"consultTotal\"," +
                " d.twfz_charge_type AS \"TWFZ_CHARGE_TYPE\"," +
                " d.spfz_charge_type AS \"SPFZ_CHARGE_TYPE\"," +
                " d.spzx_charge_type AS \"SPZX_CHARGE_TYPE\"," +
                " d.xtfz_charge_type AS \"XTFZ_CHARGE_TYPE\"," +
                " d.twzx_charge_type AS \"TWZX_CHARGE_TYPE\"," +
                " d.jyzx_charge_type AS \"JYZX_CHARGE_TYPE\"," +
                " h.org_name AS \"orgName\"," +
                " h.org_code AS \"orgCode\" " ;
        if(StringUtils.isNoneBlank(patientid)){
            sql+=" , follow.id AS \"followid\" " ;
        }
        sql+=" FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " Left join ( select count(id) as total,doctor from wlyy_outpatient where status = 3 GROUP BY doctor ) a on a.doctor = d.id ";
        Map<String, Object> params = new HashedMap();
        Date date = new Date();
        sql+="LEFT JOIN (SELECT  COUNT(t1.doctor) as workTotal, t1.doctor FROM  wlyy_doctor_work_time t1   WHERE   " +
                "t1.start_time <=:startTime  AND t1.end_time >=:endTime GROUP BY t1.doctor) dw ON dw.doctor=d.id ";
        sql+="LEFT JOIN (\n" +
                "\tSELECT\n" +
                "\t\tAVG(a.score) AS score,\n" +
                "\t\tb.doctor AS doctor\n" +
                "\tFROM\n" +
                "\t\tbase_evaluate a,\n" +
                "\t\tbase_evaluate_score b\n" +
                "\tWHERE\n" +
                "\t\ta.relation_code = b.id\n" +
                "\tGROUP BY\n" +
                "\t\tb.doctor\n" +
                ") evaluate ON evaluate.doctor = d.id";
        params.put("startTime", date);
        params.put("endTime", date);
        if(StringUtils.isNoneBlank(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)) {
                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.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 ";
        }


        sql += " WHERE  1=1 and h.del = '1' ";


        if (StringUtils.isNotBlank(chargType)) {
            if ("all".equals(chargType)) {
                //不过滤
            } else {
                sql += " AND d.charge_type = :chargType";
                params.put("chargType", chargType);
            }
        }
        List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOS  = wlyyHospitalSysDictDao.findByDictCode("isDoctorWork");
        boolean isNeedDoctorWord = true;
        if(wlyyHospitalSysDictDOS!=null&&wlyyHospitalSysDictDOS.size()>0){
            for(WlyyHospitalSysDictDO wlyyHospitalSysDictDO:wlyyHospitalSysDictDOS){
                if (!"1".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
                    isNeedDoctorWord = false;
                    break;
                }
            }
        }
        if (StringUtils.isNotBlank(iswork) && "1".equals(iswork)&&isNeedDoctorWord) {
            logger.info("iswork:" + iswork);
            sql += " AND (" +
                    " EXISTS ( " +
                    " SELECT " +
                    "  1 " +
                    " FROM " +
                    "  wlyy_doctor_work_time t " +
                    " WHERE " +
                    "  t.doctor = d.id " +
                    " AND t.start_time <=:startTime" +
                    " AND t.end_time >=:endTime" +
                    " ) OR " +
                    " d.consult_status = '1') ";
            params.put("startTime", date);
            params.put("endTime", date);
        }
        if (StringUtils.isNotBlank(orgCode)) {
            sql += " AND  h.org_code =:orgCode";
            params.put("orgCode", orgCode);
        }
        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(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(outpatientType)) {
            if (outpatientType.contains("or")) {
                String[] outpatientTypeArray = outpatientType.split("or");
                sql += " AND ( ";

                for (int i = 0; i < outpatientTypeArray.length; i++) {
                    sql += " d.outpatient_type like'%" + outpatientTypeArray[i] + "%'";
                    if (i != outpatientTypeArray.length - 1) {
                        sql += " or ";
                    }
                }
                sql += " ) ";
            } else {
                sql += " AND d.outpatient_type like'%" + outpatientType + "%'";
            }
        } 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(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("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            if (flag){
                sql += " and d.del='1' order by d.consult_status DESC ,evaluate.score desc,a.total " + consutlSort;
            }else{
                sql += " and d.del='1' order by d.consult_status desc nulls last ,evaluate.score desc nulls last ,a.total " + consutlSort;
                sql+=" NULLS LAST,\n" +
                        "\tD.id DESC";
            }
        }else {
            sql += " and d.del='1' order by d.consult_status DESC ,evaluate.score desc,a.total " + consutlSort;
        }
        String sqlCount = "select count(1) as \"total\" from ( "+sql+" ) t";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params, page, pagesize);
        List<WlyyHospitalSysDictDO> doctorFrontList = wlyyHospitalSysDictDao.findByDictNameOrderBySort("doctorFrontList",orgCode);
        List<Map<String,Object>> frontDoctor = new ArrayList<>();
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            sql= sql.replace("AS \"id\"","AS \"ID\"");
        }
        String sqlCharge = "SELECT t.id as \"id\",\n" +
                "\tm.req_fee as \"twfzFee\",\n" +
                "\ta.req_fee as \"spfzFee\",\n" +
                "\tb.req_fee as \"spzxFee\",\n" +
                "\tv.req_fee as \"twzxFee\",\n" +
                "\tg.req_fee as \"jyzxFee\",\n" +
                "\td.req_fee as \"xtzxFee\"\n" +
                "FROM\n" +
                "\t  ("+sql+")  t \n" +
                "LEFT JOIN wlyy_charge_dict m ON t.twfz_charge_type = m.charge_type and m.is_del='1'\n" +
                "LEFT JOIN wlyy_charge_dict a ON t.spfz_charge_type = a.charge_type and a.is_del='1'\n" +
                "LEFT JOIN wlyy_charge_dict b ON t.spzx_charge_type = b.charge_type and b.is_del='1'\n" +
                "LEFT JOIN wlyy_charge_dict v ON t.twzx_charge_type = v.charge_type and v.is_del='1'\n" +
                "LEFT JOIN wlyy_charge_dict d ON t.xtfz_charge_type = d.charge_type and d.is_del='1'\n" +
                " LEFT JOIN wlyy_charge_dict g ON t.jyzx_charge_type = g.charge_type and g.is_del='1'\n"+
                " where t.id is not null";
        List<Map<String,Object>> chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge, params);
        //查询医生各项评价平均分
        String sqlscore = "select t.doctor as \"id\" ,sum(t.score)/3 as\"score\" from ("+
                "SELECT " +
                "AVG(a.score) AS \"score\"," +
                "a.score_type AS \"score_type\"," +
                "b.doctor as \"doctor\" " +
                "FROM ("+sql+") m , base_evaluate a,base_evaluate_score b " +
                "WHERE " +
                " m.id = b.doctor and " +
                "a.relation_code=b.id " +
                "GROUP BY a.score_type,b.doctor ORDER BY  a.score_type ASC ) t GROUP BY  t.doctor";
        List<Map<String, Object>> listscore = hibenateUtils.createSQLQuery(sqlscore, params);

        /*list.stream().forEach(e->{
            if (null==e.get("consultStatus")){
                e.put("consultStatus",0);
            }
            if (null==e.get("workTotal")){
                e.put("workTotal",0);
            }
        });

        list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("workTotal"))).reversed().thenComparing(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("consultStatus")))).reversed());*/
        List<Map<String,Object>>  resultList = new ArrayList<>();
        resultList.addAll(list) ;
        for (Map<String,Object> map:list){
            String doctor = map.get("id").toString();
            /*List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
            if(null!=map.get("chargeType")){
                String chargeType = map.get("chargeType").toString();
                if (chargeType.contains(",")){
                    chargeType = chargeType.replace(",","','");
                }
                String sqlCharge = "select charge_type as \"chargeType\",charge_name as \"chargeName\"," +
                        "req_fee  as \"reqFee\",zj_fee  as \"zjFee\",xt_fee  as \"xtFee\",dept_type_code as \"deptTypeCode\" " +
                        " from wlyy_charge_dict where 1=1";
                sqlCharge+=" and charge_type in ( '"+chargeType+"')";
                if (StringUtils.isNoneBlank(deptTyepCode)){
                    sqlCharge+=" and dept_type_code in ( '"+deptTyepCode+"')";
                }
                chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);
            }
            map.put("chargeTypeList",chargeDictDOLists);*/
            List<Map<String,Object>> doctorChargeDictDOLists = new ArrayList<>();
            for (Map<String ,Object> chargMap:chargeDictDOLists){
                if(doctor.equalsIgnoreCase(chargMap.get("id").toString())){
                    doctorChargeDictDOLists.add(chargMap);
                }
            }
            map.put("chargeTypeList",doctorChargeDictDOLists);


            Double doctorScore = new Double("0");

            if (listscore != null && listscore.size() > 0) {
                for (Map<String, Object> _listscore : listscore) {
                    if (_listscore.get("id").toString().equalsIgnoreCase(doctor)){
                        doctorScore = Double.parseDouble(_listscore.get("score").toString());
                    }
                }
            }
            map.put("doctorScore", doctorScore);
            if (doctorFrontList!=null&&doctorFrontList.size()>0){
                for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:doctorFrontList){
                    if(doctor.equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                        map.put("doctorFrontSort",wlyyHospitalSysDictDO.getSort());
                        logger.info("doctorFrontSort"+wlyyHospitalSysDictDO.getSort());
                        logger.info("doctorId"+wlyyHospitalSysDictDO.getDictCode());
                        frontDoctor.add(map);
                        resultList.remove(map);
                    }
                }
            }

        }
        List<Map<String, Object>> listCount = hibenateUtils.createSQLQuery(sqlCount, params);
        Long count = 0L;
        if(listCount!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(listCount.get(0).get("total"));
        }
        if (frontDoctor!=null&&frontDoctor.size()>0){
            frontDoctor.sort(Comparator.comparing((Map<String, Object> h) -> ((Integer) h.get("doctorFrontSort"))));
            logger.info("size"+frontDoctor.size());
            for (Map<String, Object> map:resultList){
                logger.info("id  =="+map.get("id").toString());
                frontDoctor.add(map);
            }
        }
        logger.info("findDoctorByHospitalAndDiseaseAndDept end:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
        logger.info("sql:" + sql);
        MixEnvelop envelop =new MixEnvelop();
        envelop.setDetailModelList(frontDoctor);
        envelop.setTotalCount(count.intValue());
        envelop.setPageSize(pagesize);
        envelop.setCurrPage(page);
        System.out.println("new"+(new Date().getTime()-statr));
        return envelop;
    }
    /**
     * 根据疾病名称，热门部门查询医生
     *
     * @param orgCode         机构码
     * @param dept            部门CODE
     * @param diseaseKey      疾病名称
     * @param jobTitleNameKey
     * @param outpatientType
     * @param keyName
     * @param workingTime
     * @param consutlSort
     * @return
     */
    @Transactional(readOnly = true)
    public MixEnvelop findDoctorByHospitalAndDiseaseAndDept2(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){
            page --;

        if (pagesize <= 0) {
            pagesize = 10;
        }*/
        long statr = new Date().getTime();
        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.expertise AS \"expertise\"," +
                " d.introduce AS \"introduce\"," +
                " d.job_title_code AS \"jobTitleCode\", " +
                " d.job_title_name AS \"jobTitleName\"," +
                " d.charge_type AS \"chargeType\"," +
                " h.dept_name AS \"deptName\"," +
                " dw.workTotal AS \"workTotal\","+
                " d.consult_status AS \"consultStatus\"," +
                " d.outpatient_type AS \"outpatientType\"," +
                " a.total AS \"consultTotal\"," +
                " h.org_name AS \"orgName\"," +
                " h.org_code AS \"orgCode\" " ;
        if(StringUtils.isNoneBlank(patientid)){
            sql+=" , follow.id AS \"followid\" " ;
        }
        sql+=" FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " Left join ( select count(id) as total,doctor from wlyy_outpatient where status = 3 GROUP BY doctor ) a on a.doctor = d.id ";
        Map<String, Object> params = new HashedMap();
        Date date = new Date();
        sql+="LEFT JOIN (SELECT  COUNT(t1.doctor) as workTotal, t1.doctor FROM  wlyy_doctor_work_time t1   WHERE   " +
                "t1.start_time <=:startTime  AND t1.end_time >=:endTime GROUP BY t1.doctor) dw ON dw.doctor=d.id ";
        sql+="LEFT JOIN (\n" +
                "\tSELECT\n" +
                "\t\tAVG(a.score) AS score,\n" +
                "\t\tb.doctor AS doctor\n" +
                "\tFROM\n" +
                "\t\tbase_evaluate a,\n" +
                "\t\tbase_evaluate_score b\n" +
                "\tWHERE\n" +
                "\t\ta.relation_code = b.id\n" +
                "\tGROUP BY\n" +
                "\t\tb.doctor\n" +
                ") evaluate ON evaluate.doctor = d.id";
        params.put("startTime", date);
        params.put("endTime", date);
        if(StringUtils.isNoneBlank(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)) {
                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.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 ";
        }


        sql += " WHERE  1=1 and h.del = '1' ";


        if (StringUtils.isNotBlank(chargType)) {
            if ("all".equals(chargType)) {
                //不过滤
            } else {
                sql += " AND d.charge_type = :chargType";
                params.put("chargType", chargType);
            }
        }
        List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOS  = wlyyHospitalSysDictDao.findByDictCode("isDoctorWork");
        boolean isNeedDoctorWord = true;
        if(wlyyHospitalSysDictDOS!=null&&wlyyHospitalSysDictDOS.size()>0){
            for(WlyyHospitalSysDictDO wlyyHospitalSysDictDO:wlyyHospitalSysDictDOS){
                if (!"1".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictValue())){
                    isNeedDoctorWord = false;
                    break;
                }
            }
        }
        if (StringUtils.isNotBlank(iswork) && "1".equals(iswork)&&isNeedDoctorWord) {
            logger.info("iswork:" + iswork);
            sql += " AND (" +
                    " EXISTS ( " +
                    " SELECT " +
                    "  1 " +
                    " FROM " +
                    "  wlyy_doctor_work_time t " +
                    " WHERE " +
                    "  t.doctor = d.id " +
                    " AND t.start_time <=:startTime" +
                    " AND t.end_time >=:endTime" +
                    " ) OR " +
                    " d.consult_status = '1') ";
            params.put("startTime", date);
            params.put("endTime", date);
        }
        if (StringUtils.isNotBlank(orgCode)) {
            sql += " AND  h.org_code =:orgCode";
            params.put("orgCode", orgCode);
        }
        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(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(outpatientType)) {
            if (outpatientType.contains("or")) {
                String[] outpatientTypeArray = outpatientType.split("or");
                sql += " AND ( ";

                for (int i = 0; i < outpatientTypeArray.length; i++) {
                    sql += " d.outpatient_type like'%" + outpatientTypeArray[i] + "%'";
                    if (i != outpatientTypeArray.length - 1) {
                        sql += " or ";
                    }
                }
                sql += " ) ";
            } else {
                sql += " AND d.outpatient_type like'%" + outpatientType + "%'";
            }
        } 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(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("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            if (flag){
                sql += " and d.del='1' order by d.consult_status DESC ,evaluate.score desc,a.total " + consutlSort;
            }else{
                sql += " and d.del='1' order by d.consult_status desc nulls last ,evaluate.score desc nulls last ,a.total " + consutlSort;
                sql+=" NULLS LAST,\n" +
                        "\tD.id DESC";
            }
        }else {
            sql += " and d.del='1' order by d.consult_status DESC ,evaluate.score desc,a.total " + consutlSort;
        }
        String sqlCount = "select count(1) as \"total\" from ( "+sql+" ) t";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params, page, pagesize);
        /*list.stream().forEach(e->{
            if (null==e.get("consultStatus")){
                e.put("consultStatus",0);
            }
            if (null==e.get("workTotal")){
                e.put("workTotal",0);
            }
        });

        list.stream().sorted(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("workTotal"))).reversed().thenComparing(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("consultStatus")))).reversed());*/
        String hospital="";
        for (Map<String,Object> map:list){
            String doctor = map.get("id").toString();
            //号别
            List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (null!=depts&&depts.size()>0){
                BaseDoctorHospitalDO baseDoctorHospitalDO = depts.get(0);
                hospital = baseDoctorHospitalDO.getOrgCode();

            }

            /*List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
            if(null!=map.get("chargeType")){
                String chargeType = map.get("chargeType").toString();
                if (chargeType.contains(",")){
                    chargeType = chargeType.replace(",","','");
                }
                String sqlCharge = "select charge_type as \"chargeType\",charge_name as \"chargeName\"," +
                        "req_fee  as \"reqFee\",zj_fee  as \"zjFee\",xt_fee  as \"xtFee\",dept_type_code as \"deptTypeCode\" " +
                        " from wlyy_charge_dict where 1=1";
                sqlCharge+=" and charge_type in ( '"+chargeType+"')";
                if (StringUtils.isNoneBlank(deptTyepCode)){
                    sqlCharge+=" and dept_type_code in ( '"+deptTyepCode+"')";
                }
                chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);
            }
            map.put("chargeTypeList",chargeDictDOLists);*/
            List<Map<String,Object>> chargeDictDOLists = new ArrayList<>();
            String sqlCharge = "SELECT\n" +
                    "\tm.req_fee as \"twfzFee\",\n" +
                    "\ta.req_fee as \"spfzFee\",\n" +
                    "\tb.req_fee as \"spzxFee\",\n" +
                    "\tv.req_fee as \"twzxFee\",\n" +
                    "\tg.req_fee as \"jyzxFee\",\n" +
                    "\td.req_fee as \"xtzxFee\"\n" +
                    "FROM\n" +
                    "\tbase_doctor t\n" +
                    "LEFT JOIN wlyy_charge_dict m ON t.twfz_charge_type = m.charge_type and m.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict a ON t.spfz_charge_type = a.charge_type and a.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict b ON t.spzx_charge_type = b.charge_type and b.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict v ON t.twzx_charge_type = v.charge_type and v.is_del='1'\n" +
                    "LEFT JOIN wlyy_charge_dict d ON t.xtfz_charge_type = d.charge_type and d.is_del='1'\n" +
                    " LEFT JOIN wlyy_charge_dict g ON t.jyzx_charge_type = g.charge_type and g.is_del='1'\n" +
                    "WHERE t.id = '"+map.get("id")+"'";
            chargeDictDOLists =  hibenateUtils.createSQLQuery(sqlCharge);
            map.put("chargeTypeList",chargeDictDOLists);
            //查询医生各项评价平均分
            String sqlscore = "SELECT " +
                    "AVG(a.score) AS \"score\"," +
                    "a.score_type AS \"score_type\" " +
                    "FROM base_evaluate a,base_evaluate_score b " +
                    "WHERE " +
                    "a.relation_code=b.id " +
                    "AND b.doctor='" + doctor + "' " +
                    "GROUP BY a.score_type ORDER BY  a.score_type ASC ";
            List<Map<String, Object>> listscore = jdbcTemplate.queryForList(sqlscore);

            Double doctorScore = new Double("0");

            if (listscore != null && listscore.size() > 0) {
                for (Map<String, Object> _listscore : listscore) {
                    doctorScore += Double.parseDouble(_listscore.get("score").toString());
                }
            }
            doctorScore = doctorScore / 3;
            map.put("doctorScore", doctorScore);
        }
        List<Map<String, Object>> listCount = hibenateUtils.createSQLQuery(sqlCount, params);
        Long count = 0L;
        if(listCount!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(listCount.get(0).get("total"));
        }
        List<WlyyHospitalSysDictDO> doctorFrontList = wlyyHospitalSysDictDao.findByDictNameOrderBySort("doctorFrontList",hospital);
        if (doctorFrontList!=null&&doctorFrontList.size()>0){
            List<Map<String,Object>> frontDoctor = new ArrayList<>();
            if (list!=null&&list.size()>0){
                for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:doctorFrontList){
                    for(Map<String,Object> map: list){
                        if(map.get("id").toString().equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                            map.put("doctorFrontSort",wlyyHospitalSysDictDO.getSort());
                            logger.info("doctorFrontSort",wlyyHospitalSysDictDO.getSort());
                            logger.info("doctorId",wlyyHospitalSysDictDO.getDictCode());
                            frontDoctor.add(map);
                        }
                    }
                }
                for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:doctorFrontList){
                    for(Map<String,Object> map1: list){
                        if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase(map1.get("id").toString())){
                            list.remove(map1);
                            break;
                        }
                    }
                }
                for(Map<String,Object> map1: list){
                    frontDoctor.add(map1);
                }
                list = frontDoctor;
            }
        }


        logger.info("findDoctorByHospitalAndDiseaseAndDept end:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
        logger.info("sql:" + sql);
        MixEnvelop envelop =new MixEnvelop();
        envelop.setDetailModelList(list);
        envelop.setTotalCount(count.intValue());
        envelop.setPageSize(pagesize);
        envelop.setCurrPage(page);
        System.out.println("old"+(new Date().getTime()-statr));
        return envelop;
    }
    /**
     * 获取常见疾病、热门部门、医生拒绝接诊原因 字典
     *
     * @param dictName 字典名称
     * @return
     */
    public List<WlyyHospitalSysDictDO> findHotDeptAndDiseaseDict(String dictName) {
        return wlyyHospitalSysDictDao.findByDictName(dictName);
        /*String sql ="SELECT \"DICT_CODE\" AS \"dict_code\",\"CREATE_USER\" AS \"create_user\",\"UPDATE_USER\" AS \"update_user\",\"UPDATE_TIME\" AS \"update_time\",\"DICT_NAME\" AS \"dict_name\",\"PY_CODE\" AS \"py_code\",\"SAAS_ID\" AS \"saas_id\",\"HOSPITAL\" AS \"hospital\",\"SORT\" AS \"sort\",\"CREATE_USER_NAME\" AS \"create_user_name\",\"ID\" AS \"id\",\"CREATE_TIME\" AS \"create_time\",\"UPDATE_USER_NAME\" AS \"update_user_name\",\"DICT_VALUE\" AS \"dict_value\" from wlyy_hospital_sys_dict where DICT_NAME='"+dictName+"' ORDER BY sort ASC";

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);

        return  list;*/
    }

    /**
     * 查询排班规则
     *
     * @return
     */
    public List<WlyyHospitalSysDictVO> findWorkRule(String dictName, String hospital) {
        List<WlyyHospitalSysDictDO> list = sysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital, dictName);
        List<WlyyHospitalSysDictVO> vos = new ArrayList<>();
        return convertToModels(list, vos, WlyyHospitalSysDictVO.class);
    }

    /**
     * 保存排班规则
     *
     * @param workRoleJsons
     * @return
     */
    public Boolean updateWorkRule(String workRoleJsons) {
        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());
        sysDictDao.delete(list);
        sysDictDao.save(sysDicts);
        return true;
    }

    /**
     * @param type
     * @param codes
     * @param workTimeJson
     * @return
     * @throws Exception
     */
    public Boolean saveDoctorWorkTimeJson(String type, String codes, String workTimeJson, String date) throws Exception {

        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        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);
            wlyyDoctorWorkTimeDOs.add(timeDO);
        }

        //全院医生
        if ("1".equals(type)) {
            String sql = "SELECT " +
                    " DISTINCT " +
                    " d.id AS \"id\", " +
                    " d.name AS \"name\", " +
                    " h.org_code AS \"org_code\", " +
                    " h.org_name AS \"org_name\"" +
                    " FROM " +
                    " base_doctor d " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " WHERE  " +
                    " 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)) {

            String sql = "SELECT " +
                    " DISTINCT " +
                    " d.id AS \"id\", " +
                    " d.name AS \"name\", " +
                    " h.org_code AS \"org_code\", " +
                    " h.org_name AS \"org_name\"" +
                    " FROM " +
                    " base_doctor d " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " 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);
            //医生批量
        } else if ("3".equals(type)) {
            String sql = "SELECT " +
                    " DISTINCT " +
                    " d.id AS \"id\", " +
                    " d.name AS \"name\", " +
                    " h.org_code AS \"org_code\", " +
                    " h.org_name AS \"org_name\"" +
                    " FROM " +
                    " base_doctor d " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " WHERE  " +
                    " 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;
    }

    /**
     * 医生自主保存排班
     *
     * @param codes
     * @param workTimeJson
     * @return
     * @throws Exception
     */
    public Boolean doctorSaveWorkTimeJson(String codes, String workTimeJson, String date) throws Exception {

        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        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);
            wlyyDoctorWorkTimeDOs.add(timeDO);
        }

        //医生自主排班
        String sql = "SELECT " +
                " DISTINCT " +
                " d.id AS \"id\", " +
                " d.name AS \"name\", " +
                " h.org_code AS \"org_code\", " +
                " h.org_name AS \"org_name\"" +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                " WHERE  " +
                " d.id in (" + sqlCode(codes) + ")";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
        List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);
        return doctorSaveWorkTime(workTimeDOs);
    }

    /**
     * 医生自主编辑排班
     *
     * @param workTimeJson
     * @param codes
     * @return
     * @throws Exception
     */
    public Boolean doctorUpdateWorkTimeJson(String workTimeJson, String codes) throws Exception {

        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        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);
            wlyyDoctorWorkTimeDOs.add(timeDO);
        }

        //医生自主排班
        String sql = "SELECT " +
                " DISTINCT " +
                " d.id AS \"id\", " +
                " d.name AS \"name\", " +
                " h.org_code AS \"org_code\", " +
                " h.org_name AS \"org_name\"" +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                " WHERE  " +
                " d.id in (" + sqlCode(codes) + ")";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
        List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);

        return doctorSaveWorkTime(workTimeDOs);
    }


    /**
     * 医生自主删除排班
     *
     * @param code
     * @return
     * @throws Exception
     */
    public Boolean deleteWorkTime(String code) throws Exception {
        doctorWorkTimeDao.delete(code);
        return true;
    }

    public String sqlCode(String codes) {
        String code[] = codes.split(",");
        String rs = "";
        for (String c : code) {
            rs += "'" + c + "',";
        }
        rs = rs.substring(0, rs.length() - 1);
        return rs;
    }

    public List<WlyyDoctorWorkTimeDO> makeDoctorWorkTimeDOList(List<Map<String, Object>> doctors, List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs) {
        List<WlyyDoctorWorkTimeDO> rs = new ArrayList<>();
        if (doctors != null && doctors.size() > 0) {
            //构建医生排班
            for (Map<String, Object> doctor : doctors) {
                for (WlyyDoctorWorkTimeDO time : wlyyDoctorWorkTimeDOs) {
                    WlyyDoctorWorkTimeDO t = new WlyyDoctorWorkTimeDO();
                    t.setDoctor((String) doctor.get("id"));
                    t.setDoctorName((String) doctor.get("name"));
//                    t.setDept((String)doctor.get("dept_code"));
//                    t.setDeptName((String)doctor.get("dept_name"));
                    t.setHospital((String) doctor.get("org_code"));
                    t.setHospitalName((String) doctor.get("org_name"));
                    t.setCreateTime(new Date());

                    t.setType(time.getType());
                    t.setTimeType(time.getTimeType());
                    t.setStartTime(time.getStartTime());
                    t.setEndTime(time.getEndTime());
                    t.setDate(time.getDate());
                    t.setTimeInterval(time.getTimeInterval());
                    t.setSourceNumber(time.getSourceNumber());
                    t.setCreateUser(time.getCreateUser());
                    t.setCreateUserType(time.getCreateUserType());
                    t.setId(time.getId());
                    rs.add(t);
                }
                logger.info(rs.size() + "");
            }
        }
        return rs;
    }

    /**
     * 批量更新医生多月份排班数据
     *
     * @param workTimeDOs
     * @return
     */
    public Boolean saveDoctorWorkTime(List<WlyyDoctorWorkTimeDO> workTimeDOs, String date, List<Map<String, Object>> doctors) {

        if (workTimeDOs != null && workTimeDOs.size() > 0) {
            //按月按医生分组标记排班数据
            List<String> workMonths = new ArrayList<>();

            for (WlyyDoctorWorkTimeDO time : workTimeDOs) {
                //医生工作月份
                String workMonth = time.getDoctor() + "," + time.getDate().substring(0, 7);
                //判断是否是首次插入医生月份数据，如果是首次，则删除该医生当前月份排班数据数据
                if (!workMonths.contains(workMonth)) {
                    workMonths.add(workMonth);
                    List<WlyyDoctorWorkTimeDO> oldTimes = doctorWorkTimeDao.findDoctorWorkTimeByMonth(time.getDoctor(), "%" + time.getDate().substring(0, 7) + "%");
                    doctorWorkTimeDao.delete(oldTimes);
                }
            }
            doctorWorkTimeDao.save(workTimeDOs);
        } else {
            //如果排班数据为空，删除医生月份下排班数据
            if (StringUtils.isNotBlank(date)) {
                String d[] = date.split(",");
                for (String dt : d) {
                    for (Map<String, Object> doc : doctors) {
                        List<WlyyDoctorWorkTimeDO> oldTimes = doctorWorkTimeDao.findDoctorWorkTimeByMonth((String) doc.get("id"), "%" + dt + "%");
                        doctorWorkTimeDao.delete(oldTimes);
                    }
                }
            }
        }
        return true;
    }


    /**
     * 更新医生
     *
     * @param workTimeDOs
     * @return
     */
    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;
                }

                //与医院与自己排班比较  是否冲突  第一组最后时间小于等于第二组最前时间 || 第一组最前时间大于等于第二组最后时间
                if (one.getEndTime().before(workTimeDO.getStartTime()) || one.getStartTime().after(workTimeDO.getEndTime())) {

                } else {
                    throw new Exception("您选择的时间与“开始时间："+DateUtil.dateToStrLong(one.getStartTime())+"-结束时间："+DateUtil.dateToStrLong(one.getEndTime())+"”的医院排班/自己排班冲突，请重新选择！");
                }

            }
            doctorWorkTimeDao.save(workTimeDO);

        }
        return true;
    }


    /**
     * 查询某个医生某个月份排班记录
     *
     * @param doctor
     * @param date
     * @return
     */
    public List<WlyyDoctorWorkTimeVO> findDoctorWorkTimeByMonth(String doctor, String date, String startDate, String endDate) {

        if (StringUtils.isNotBlank(date)) {
            List<WlyyDoctorWorkTimeDO> times = doctorWorkTimeDao.findDoctorWorkTimeByMonth(doctor, "%" + date + "%");
            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"));
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            return convertToModels(times, timeVOs, WlyyDoctorWorkTimeVO.class);
        }
    }

    public Map<String, Object> findPatientInfo(String patient) {
        Map<String, Object> rs = new HashedMap();
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        Boolean flag = healthCareService.isHospitalFlag();
        if (flag){
            try{
                String result = healthCareService.authorizedToEntrace(basePatientDO.getId());
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(result);
                if (object.getString("flag").equalsIgnoreCase("1")){
                    com.alibaba.fastjson.JSONObject encryptData = object.getJSONObject("encrypt_data");
                    String state = encryptData.getString("state");
                    String auth_date = encryptData.getString("auth_date");
                    basePatientDO.setMedicalState(state);
                    basePatientDO = basePatientDao.save(basePatientDO);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01", patient, "1");
        List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wechatId,patient);
        List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOS = wlyyHospitalSysDictDao.findByDictCode("White_list");
        if (wlyyHospitalSysDictDOS!=null&&wlyyHospitalSysDictDOS.size()!=0){
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDOS.get(0);
            String text = wlyyHospitalSysDictDO.getDictValue();
            String str[] = text.split(",");
            List<String> list = new ArrayList<>();
            for (int i=0;i<str.length;i++){
                list.add(str[i]);
            }
            if (list.contains(basePatientDO.getIdcard())){
                rs.put("flag","1");
            }else {
                rs.put("flag","0");
            }
        }else {
            rs.put("flag","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());
        rs.put("cardType",basePatientDO.getCardType());
        rs.put("healthStatus","");
        rs.put("diseaseType","");
        if (patientMedicareCardDO != null) {
            rs.put("ssc", patientMedicareCardDO.getCode());
        } else {
            rs.put("ssc", "");
        }
        if (patientWechatDos!=null&&patientWechatDos.size()!=0){
            BasePatientWechatDo patientWechatDo =patientWechatDos.get(0);
            rs.put("openid",patientWechatDo.getOpenid());
        }else {
            rs.put("openid","");
        }

        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();
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01", patient, "1");
        if (StringUtils.isNoneBlank(name)) {
            basePatientDO.setName(name);
        }
        if (StringUtils.isNoneBlank(idcard)) {
            basePatientDO.setIdcard(idcard);
        }
        if (sex != null) {
            basePatientDO.setSex(sex);
        }

        if (StringUtils.isNoneBlank(province)) {
            basePatientDO.setProvinceCode(province);
        }

        if (StringUtils.isNoneBlank(provinceName)) {
            basePatientDO.setProvinceName(provinceName);
        }

        if (StringUtils.isNoneBlank(city)) {
            basePatientDO.setCityCode(city);
        }

        if (StringUtils.isNoneBlank(cityName)) {
            basePatientDO.setCityName(cityName);
        }

        if (StringUtils.isNoneBlank(townCode)) {
            basePatientDO.setTownCode(townCode);
        }
        if (StringUtils.isNoneBlank(townName)) {
            basePatientDO.setTownName(townName);
        }
        if (StringUtils.isNoneBlank(committeeCode)) {
            basePatientDO.setCommitteeCode(committeeCode);
        }
        if (StringUtils.isNoneBlank(committeeName)) {
            basePatientDO.setCommitteeName(committeeName);
        }
        if (StringUtils.isNoneBlank(address)) {
            basePatientDO.setAddress(address);
        }
        if (StringUtils.isNoneBlank(photo)) {
            basePatientDO.setPhoto(photo);
        }

        if (StringUtils.isNoneBlank(mobile)) {
            basePatientDO.setMobile(mobile);
        }
        basePatientDO = basePatientDao.save(basePatientDO);
        if (patientMedicareCardDO != null) {
            patientMedicareCardDO.setCode(ssc);
            patientMedicareCardDO = basePatientMedicareCardDao.save(patientMedicareCardDO);
        } else {
            patientMedicareCardDO = new PatientMedicareCardDO();
            patientMedicareCardDO.setCode(ssc);
            patientMedicareCardDO.setType("A_01");
            patientMedicareCardDO.setParentType("A");
            patientMedicareCardDO.setDel("1");
            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", "");
        }
        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());
        return rs;
    }


    @Autowired
    private FileUploadService fileUploadService;

   /* public Map<String, Object> test() throws Exception {
        entranceService.MS02014(false);
        return null;
    }*/

    public String test2(String no) throws Exception {
        TransRequest e = new TransRequest();
        e.setMethod("ehc.ehealthcard.auth.query");
        e.setApp_id("1BQA48ETK000A718A8C000001FFAA482");
        e.setTerm_id("35020010001");
        e.setVersion("X.M.0.1");
        e.setTimestamp(DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss"));
        e.setSign_type("MD5");
        e.setEnc_type("AES");
        com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
        bizContent.put("out_authorize_no", no);
        bizContent.put("out_authorize_time", DateUtils.getOutTradeTime());
        e.setBiz_content(JSON.toJSONString(bizContent));
        EhcHandler ehcHandler = new EhcHandler("http://www.mstpay.com:1811/ehcService/gateway.do", "1BQA48ETK000A718A8C000001FFAA482", "35020010001", "1BQA48ETK001A718A8C00000FE996B9B");
        TransResponse re = ehcHandler.execute(e);
        String rs = com.alibaba.fastjson.JSONObject.toJSONString(re);
        return rs;
    }


    /**
     * 获取正在进行中的视频复诊/协同门诊
     *
     * @param doctor
     * @param general_doctor
     * @return
     */
    public List<Map<String, Object>> getVideoPrescriptionByDoctor(String doctor, String general_doctor, String wxId) {
        String condition = "";
        /*if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                condition += "date_format(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            }else {
                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\",";
        }*/
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "patient.sex AS \"sex\"," +
                "patient.idcard AS \"idcard\"," +
                "patient.photo AS \"photo\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.mobile AS \"mobile\"," +
                "room.consult_type AS \"consult_type\"," + "room.reservation_time as \"time\", " +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.origin_con_no AS \"origin_con_no\", " +
                "consult.consult AS \"consult\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +
                "wlyy_outpatient outpatient, " +
                "wlyy_consult_team consult " +
                "WHERE " +
                "room.patient_id=patient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND outpatient.pay_status=1 " +
                "AND outpatient.type =2 " +
                "AND consult.status = 0 ";
        if (StringUtils.isNoneBlank(doctor)) {
            sql = sql + "AND room.doctor='" + doctor + "' " +
                    "AND room.consult_type= 2";
        } else if (StringUtils.isNoneBlank(general_doctor)) {
            sql = sql + "AND room.general_doctor='" + general_doctor + "' " +
                    "AND room.consult_type= 2";
        } else {
        }


        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));
                //转换日期格式
                outpatient.put("time",null==outpatient.get("time")?"":DateUtil.dateToStrLong(DateUtil.strToDateLong(outpatient.get("time").toString())));
                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);//未提醒
            }
        }

        return list;
    }

    public String generalDoctorWaitingNumber(String doctor, String wxId, String outpatientId) {
        String condition = "";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                condition += "date_format(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
                condition += "date_format(room.reservation_time,'YYYY-MM-DD')  AS \"group_date\",";
            }else {
                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' ) AS \"group_date\",";
        }
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "patient.sex AS \"sex\"," +
                "patient.idcard AS \"idcard\"," +
                "patient.photo AS \"photo\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.mobile AS \"mobile\"," +
                "outpatient.mobile AS \"outpatient_mobile\"," +
                "room.consult_type AS \"consult_type\"," + condition +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.origin_con_no AS \"origin_con_no\", " +
                "room.reservation_type AS \"reservation_type\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "room.patient_id=patient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 " +
                "AND outpatient.pay_status = 1 " +
                "AND room.doctor='" + doctor + "' " +
                "AND room.reservation_time is not null " +
                "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.getStringDate("yyyy-MM-dd")+" 00:00:00"+"' ";*/

        if ("xm_ykyy_wx".equals(wxId)) {
            if(flag){
                sql += " AND room.reservation_time >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                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;
            }
        }
        return waitCount.toString();
    }

    public com.alibaba.fastjson.JSONArray getWaitingForVisitVideoPrescriptionByDoctor(String doctor, String wxId,String outpatientType,String keyWord,String patientId) {
        String condition = "";
        if ("xm_ykyy_wx".equals(wxId)) {
            if(flag){
                condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' )  AS \"time\",";
                condition += "date_format(room.reservation_time,'YYYY-MM-DD')  AS \"group_date\",";
            }else{
                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' ) AS \"group_date\",";
        }
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "patient.sex AS \"sex\"," +
                "patient.idcard AS \"idcard\"," +
                "patient.photo AS \"photo\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.mobile AS \"mobile\"," +
                "outpatient.mobile AS \"outpatient_mobile\"," +
                "room.consult_type AS \"consult_type\"," + condition +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.patient_name AS \"outPatientName\"," +
                "outpatient.patient AS \"outPatient\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.origin_con_no AS \"origin_con_no\"," +
                "outpatient.consumer as \"consumer\"," +
                "outpatient.consumer_name as \"consumer_name\"," +
                "outpatient.consumer_mobile as \"consumerMobile\"," +
                "room.reservation_type AS \"reservation_type\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "room.patient_id=patient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 " +
                "AND outpatient.pay_status = 1 " +
                "AND room.doctor='" + doctor + "' " +
                "AND room.reservation_time is not null ";/* +
                "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"+"' ";*/
        if(StringUtils.isNotBlank(outpatientType)&&"1".equalsIgnoreCase(outpatientType)){
            sql+="  AND room.consult_type= 2 and room.reservation_type in (1,2)";
        } else if (StringUtils.isNotBlank(outpatientType)&&"4".equalsIgnoreCase(outpatientType)) {
            sql+="  AND room.consult_type= 2 and room.reservation_type = 3";
        } else if (StringUtils.isNotBlank(outpatientType)&&"2".equalsIgnoreCase(outpatientType)) {
            sql+="  and room.reservation_type = 2 ";
        }else {
            sql += " AND room.consult_type= 2 ";
        }
        if (StringUtils.isNotBlank(keyWord)){
            sql += " AND outpatient.patient_name like '%"+keyWord+"%'";
        }
        if (StringUtils.isNotBlank(patientId)){
            sql += " AND room.patient_id = '"+patientId+"'";
        }
        if ("xm_ykyy_wx".equals(wxId)) {
            if(flag){
                sql += " AND room.reservation_time >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                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);

        Set<String> datelist = new HashSet<>();

        HashMap<String, List<Map<String, Object>>> waitinglist = new HashMap<>();

        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));
                Integer patientAge = 0;
                Integer patientSex = 3;
                if (null!=outpatient.get("outPatient")){
                    BasePatientDO basePatientDO = basePatientDao.findById(outpatient.get("outPatient").toString());
                    if (null!=basePatientDO){
                        if (StringUtils.isNotBlank(basePatientDO.getIdcard())){
                            patientAge = DateUtil.getAgeForIdcard(basePatientDO.getIdcard());
                            outpatient.put("patientAge", DateUtil.getAgeForIdcard(basePatientDO.getIdcard()));
                            patientSex =basePatientDO.getSex();
                        }
                    }
                }
                outpatient.put("patientAge", patientAge);
                outpatient.put("patientSex", patientSex);

                String group_date = (String) outpatient.get("group_date");

                if (waitinglist.keySet().contains(group_date)) {
                    waitinglist.get(group_date).add(outpatient);
                } else {
                    List<Map<String, Object>> _cu = new ArrayList<>();
                    _cu.add(outpatient);
                    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("online_tag", 1);//在线状态

                String outpatient_mobile = (String) outpatient.get("outpatient_mobile");
                if (StringUtils.isNoneBlank(outpatient_mobile)) {
                    outpatient.put("mobile", outpatient_mobile);//复诊有手机号，传递复诊手机号
                }
            }
        }

        Collection<String> keyset = waitinglist.keySet();
        List<String> _list = new ArrayList<String>(keyset);

        //对key键值按字典升序排序
        Collections.sort(_list);
        com.alibaba.fastjson.JSONArray result = new com.alibaba.fastjson.JSONArray();


        for (int i = 0; i < _list.size(); i++) {
            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));
            }
            object.put("data", waitinglist.get(_list.get(i)));
            result.add(object);
        }
        return result;
    }

    /**
     * 医生抢单(视频)
     *
     * @param outpatientCode
     * @param doctor
     */
    public void pickVideoPrescripitonWaitingPeople(String outpatientCode, String doctor) throws Exception {
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outpatientCode);
        if (roomDOs != null && roomDOs.size() > 0) {
            for (WlyyHospitalWaitingRoomDO roomDO : roomDOs) {
                roomDO.setDoctor(doctor);
                roomDO.setDoctorName(baseDoctorDO.getName());
                hospitalWaitingRoomDao.save(roomDO);
            }
        }
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outpatientCode);
        wlyyOutpatientDO.setDoctor(doctor);
        wlyyOutpatientDO.setDoctorName(baseDoctorDO.getName());
        outpatientDao.save(wlyyOutpatientDO);
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            String doctorYktid ="";
            if (baseDoctorDO!=null){
                if(StringUtils.isNoneBlank(baseDoctorDO.getYktDoctorId())){
                    doctorYktid = baseDoctorDO.getYktDoctorId();
                }else {
                    DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(baseDoctorDO.getId());
                    if (doctorMappingDO!=null){
                        String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
                        System.out.println("Continue");
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(doctorResponse);
                        if (jsonObject.getInteger("code")==200){
                            com.alibaba.fastjson.JSONArray array = jsonObject.getJSONArray("data");
                            if (array!=null&&array.size()!=0){
                                doctorYktid=array.getJSONObject(0).getString("DOCTORUSERID");
                            }
                        }
                    }
                }
            }


            String orderNo = "";
            BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientCode);
            if (businessOrderDO!=null){
                orderNo = businessOrderDO.getOrderNo();
            }
            String res = ykyyService.updateDoctorIdByOrderId(doctorYktid,orderNo);
            WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
            if (StringUtils.isNoneBlank(res)){
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(res);
                if (object!=null){
                    wlyyHttpLogDO.setCode(object.getString("code"));
                }
            }
            wlyyHttpLogDO.setName("抢单医生id写入眼科通");
            wlyyHttpLogDO.setCode("update_doctorid_by_orderno");
            wlyyHttpLogDO.setRequest("doctorId="+doctorYktid+";"+"orderNo="+orderNo);
            wlyyHttpLogDO.setDoctor(doctor);
            wlyyHttpLogDO.setResponse(res);
            wlyyHttpLogDO.setCreateTime(new Date());
            wlyyHttpLogDao.save(wlyyHttpLogDO);
        }
        if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)&&StringUtils.isNoneBlank(wlyyOutpatientDO.getDoctor())){
            String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId="+wlyyOutpatientDO.getId();
            sendZsMsgFlow("OL_PAY_SUCCESS",wlyyOutpatientDO.getId(),"",msgUrl,"已支付问诊费");
        }

    }

    /**
     * 复诊视频咨询人数, 协同门诊人数
     *
     * @param doctor
     * @param outpatient_type 1复诊 2协同
     * @return
     */
    public Long doctorIndexConsultCount(String doctor, String outpatient_type) {


        String sql = "SELECT " +
                "count(room.outpatient_id) AS total " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +
                "wlyy_outpatient outpatient, " +
                "wlyy_consult_team consult " +
                "WHERE " +
                "room.patient_id=patient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND consult.status = 0 " +
                "AND outpatient_type.doctor='" + outpatient_type + "'" +
                "AND room.doctor='" + doctor + "' ";
        if ("1".equals(outpatient_type)) {
            sql = sql + " AND room.consult_type= 2 ";
        } else if ("2".equals(outpatient_type)) {
        } else {
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);

        Long videoOnlineCount = 0l;
        if (rstotal != null && rstotal.size() > 0) {
            videoOnlineCount = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        return videoOnlineCount;

    }


    /**
     * 根据门诊唯一号，处方号，到顺丰下单，下单成功返回面单信息
     *
     * @param admNo     门诊唯一号
     * @param realOrder 处方号
     * @
     */
    public Object getSFExpressInfo(String admNo, String realOrder, String wxId) throws Exception {

        //根据门诊唯一号取就诊记录
//        List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByAdmNo(admNo);
        List<WlyyPrescriptionDO> wlyyPrescriptionDOList = prescriptionDao.findByRealOrderList(realOrder);
        Object result = "";

        System.out.println("获取顺丰物流面单信息:wlyyPrescriptionDOS != null=" + wlyyPrescriptionDOList != null);
        if (wlyyPrescriptionDOList != null&&wlyyPrescriptionDOList.size()!=0) {
            WlyyPrescriptionDO wlyyPrescriptionDOS = wlyyPrescriptionDOList.get(0);
            List<WlyyPrescriptionExpressageDO> expressageDOList = sfexpressService.findByField("outpatientId", wlyyPrescriptionDOS.getOutpatientId());
            WlyyPrescriptionExpressageDO sfexpress_obj = null;
            System.out.println("获取顺丰物流面单信息:CollectionUtils.isEmpty(expressageDOList)=" + CollectionUtils.isEmpty(expressageDOList));
            if (CollectionUtils.isEmpty(expressageDOList)) {
                throw new Exception("顺丰快递下单失败，未找到该处方的派送地址！");
            } else {
                System.out.println("获取顺丰物流面单信息:1");
                sfexpress_obj = expressageDOList.get(0);
                System.out.println("获取顺丰物流面单信息:2");
                //如果该处方的快递单号已生成，则说明已经下单成功，不需要重复下单，直接返回面单信息
                System.out.println("获取顺丰物流面单信息:3");
                if (org.apache.commons.lang.StringUtils.isNotBlank(sfexpress_obj.getMailno())) {
                    //处方已下单成功
                    System.out.println("获取顺丰物流面单信息:4");
                } else {
                    //如果该处方的快递单号未生成，则继续下单
                    //根据业务订单号判断是否已经下单成功
                    //--2020.05.20--顺丰V2.0接口已不提供查询接口，直接单下单--START
//                    boolean go_on = sfexpressService.sfOrderSearchService(sfexpress_obj);
//
//                    //如果该业务订单号未下单成功过，则重新下单
//                    if(go_on){
//                        //请求顺丰接口下单，成功下单后，返回快递单号
//                        sfexpress_obj = sfexpressService.postSFOrderService(sfexpress_obj);
//                        //保存快递单号和增加处方物流记录为配送
//                        sfexpressService.updatePrescriptionExpressage(sfexpress_obj);
//                    }
                    //--2020.05.20--顺丰V2.0接口已不提供查询接口，直接单下单--END

                    //请求顺丰接口下单，成功下单后，返回快递单号
                    sfexpress_obj = sfexpressService.postSFOrderService(sfexpress_obj);
                    System.out.println("获取顺丰物流面单信息:5");
                    //保存快递单号和增加处方物流记录为配送
                    sfexpressService.updatePrescriptionExpressage(sfexpress_obj);
                    System.out.println("获取顺丰物流面单信息:6");

                }
                for (WlyyPrescriptionDO prescriptionDO:wlyyPrescriptionDOList){
                    prescriptionDO.setStatus(32);
                    prescriptionDao.save(prescriptionDO);
                }
                if (sfexpress_obj != null && StringUtils.isNoneBlank(sfexpress_obj.getMailno())) {
                    com.alibaba.fastjson.JSONObject object = sfexpressService.postSFOrderQueryService(sfexpress_obj);
                    System.out.println("获取顺丰物流面单信息7-1"+object.toJSONString());
                    System.out.println("获取顺丰物流面单信息:7");
                    com.alibaba.fastjson.JSONObject sfJsonObject = new com.alibaba.fastjson.JSONObject();

                    sfJsonObject.put("mailno", sfexpress_obj.getMailno());
                    sfJsonObject.put("mailtype", "标准快递");
                    sfJsonObject.put("destcode", object.getString("destRouteLabel"));
                    if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_address", "湖滨南路201-209号");
                    } else if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_address", "湖滨南路201-209号");
                    }

                    sfJsonObject.put("j_provinceName", "福建省");
                    sfJsonObject.put("j_cityName", "厦门市");
                    sfJsonObject.put("d_name", sfexpress_obj.getName());
                    sfJsonObject.put("d_provinceName", sfexpress_obj.getProvinceName());
                    sfJsonObject.put("d_cityName", sfexpress_obj.getCityName());
                    sfJsonObject.put("d_townName", sfexpress_obj.getTownName());
                    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);
                    result = sfJsonObject;
                    System.out.println("获取顺丰物流面单信息:8");
                }
            }

        }
        System.out.println("获取顺丰物流面单信息:9");
        return result;
    }


    /**
     * 根据门诊唯一号，处方号，到顺丰下单，下单成功返回面单信息--心脏和眼科
     *
     * @param admNo     门诊唯一号
     * @param realOrder 处方号
     * @return
     */
    public Object getSFExpressInfoNew(String admNo, String realOrder, String wxId) throws Exception {

        //根据门诊唯一号取就诊记录
//        List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByAdmNo(admNo);

        if (StringUtils.isNoneBlank(realOrder)){
            String str[] = realOrder.split(";");
            Object result = "";
            for (int i=0;i<str.length;i++){
                WlyyPrescriptionDO wlyyPrescriptionDOS = new WlyyPrescriptionDO();
                if(StringUtils.isNoneBlank(admNo)){
                    wlyyPrescriptionDOS = prescriptionDao.findByAdmNoAndRealOrder(admNo,str[i]);
                }else {
                    List<WlyyPrescriptionDO> wlyyPrescriptionDOList = prescriptionDao.findByRealOrderList(str[i]);
                    if (wlyyPrescriptionDOList!=null&&wlyyPrescriptionDOList.size()!=0){
                        wlyyPrescriptionDOS =wlyyPrescriptionDOList.get(0);
                    }
                }
                System.out.println("获取顺丰物流面单信息:wlyyPrescriptionDOS != null=" + wlyyPrescriptionDOS != null);
                if (wlyyPrescriptionDOS != null) {
                    List<WlyyPrescriptionExpressageDO> expressageDOList = sfexpressService.findByField("outpatientId", wlyyPrescriptionDOS.getOutpatientId());
                    WlyyPrescriptionExpressageDO sfexpress_obj = null;
                    System.out.println("获取顺丰物流面单信息:CollectionUtils.isEmpty(expressageDOList)=" + CollectionUtils.isEmpty(expressageDOList));
                    if (CollectionUtils.isEmpty(expressageDOList)) {
                        throw new Exception("顺丰快递下单失败，未找到该处方的派送地址！");
                    } else {
                        System.out.println("获取顺丰物流面单信息:1");
                        sfexpress_obj = expressageDOList.get(0);
                        System.out.println("获取顺丰物流面单信息:2");
                        BasePatientDO basePatientDO = basePatientDao.findById(wlyyPrescriptionDOS.getPatientCode());
                        //如果该处方的快递单号已生成，则说明已经下单成功，不需要重复下单，直接返回面单信息
                        System.out.println("获取顺丰物流面单信息:3");
                        if (org.apache.commons.lang.StringUtils.isNotBlank(sfexpress_obj.getMailno())) {
                            //处方已下单成功
                            System.out.println("获取顺丰物流面单信息:4");
                        } else {
                            //如果该处方的快递单号未生成，则继续下单
                            //根据业务订单号判断是否已经下单成功
                            //--2020.05.20--顺丰V2.0接口已不提供查询接口，直接单下单--START
//                    boolean go_on = sfexpressService.sfOrderSearchService(sfexpress_obj);
//
//                    //如果该业务订单号未下单成功过，则重新下单
//                    if(go_on){
//                        //请求顺丰接口下单，成功下单后，返回快递单号
//                        sfexpress_obj = sfexpressService.postSFOrderService(sfexpress_obj);
//                        //保存快递单号和增加处方物流记录为配送
//                        sfexpressService.updatePrescriptionExpressage(sfexpress_obj);
//                    }
                            //--2020.05.20--顺丰V2.0接口已不提供查询接口，直接单下单--END

                            //请求顺丰接口下单，成功下单后，返回快递单号
                            sfexpress_obj = sfexpressService.postSFOrderService(sfexpress_obj);
                            System.out.println("获取顺丰物流面单信息:5");
                            //保存快递单号和增加处方物流记录为配送
                            sfexpressService.updatePrescriptionExpressage(sfexpress_obj);
                            System.out.println("获取顺丰物流面单信息:6");

                        }
                        wlyyPrescriptionDOS.setStatus(32);
                        prescriptionDao.save(wlyyPrescriptionDOS);
                        if (sfexpress_obj != null && StringUtils.isNoneBlank(sfexpress_obj.getMailno())) {
                            com.alibaba.fastjson.JSONObject object = sfexpressService.postSFOrderQueryService(sfexpress_obj);
                            System.out.println("获取顺丰物流面单信息7-1"+object.toJSONString());
                            System.out.println("获取顺丰物流面单信息:7");
                   /* com.alibaba.fastjson.JSONObject sfJsonObject = new com.alibaba.fastjson.JSONObject();*/

                    /*sfJsonObject.put("mailno", sfexpress_obj.getMailno());
                    sfJsonObject.put("mailtype", "标准快递");
                    sfJsonObject.put("destcode", object.getString("destRouteLabel"));
                    if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_address", "湖滨南路201-209号");
                    } else if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_address", "湖滨南路201-209号");
                    }

                    sfJsonObject.put("j_provinceName", "福建省");
                    sfJsonObject.put("j_cityName", "厦门市");
                    sfJsonObject.put("d_name", sfexpress_obj.getName());
                    sfJsonObject.put("d_provinceName", sfexpress_obj.getProvinceName());
                    sfJsonObject.put("d_cityName", sfexpress_obj.getCityName());
                    sfJsonObject.put("d_townName", sfexpress_obj.getTownName());
                    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);*/
                            result = object;
                            System.out.println("获取顺丰物流面单信息:8");
                        }
                    }
                }
                System.out.println("获取顺丰物流面单信息:9");

            }
            return result;
        }else {
            return "处方号未空!";
        }


    }

    /**
     * 根据类型获取候诊居民数量
     *
     * @param doctor
     * @param outpatient_type 1复诊  2协同
     * @param type            1图文 2视频
     * @return
     */
    public Long getWaitVideoCount(String doctor, String type, String outpatient_type, String wxId) {
        String sql = "SELECT " +
                "count(outpatient.id) AS \"total\" " +
                "FROM " +
                "wlyy_outpatient outpatient," +
                "base_patient patient " +
                "WHERE " +
                "outpatient.patient=patient.id " +
                "AND outpatient.status in (0,1,2) " +
                "AND outpatient.doctor='" + doctor + "' " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.outpatient_type= '" + outpatient_type + "'  ";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        System.out.println(sdf.format(now.getTime()));
        now.add(Calendar.DAY_OF_MONTH, -1);
        System.out.println(sdf.format(now.getTime()));

        if (!"xm_ihealth_wx".contains(wxId)){
            if ("1".equals(outpatient_type)||"3".equals(outpatient_type)) {//复诊
                sql = sql + " AND outpatient.type= '" + type + "' ";
                if ("2".equals(type)) {//视频复诊才需要判断时间，
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag){
                            sql += " AND outpatient.register_date is not null and outpatient.register_date >= str_to_date('" + sdf.format(now.getTime()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                        }else {
                            sql += " AND outpatient.register_date is not null and outpatient.register_date >= to_date('" + sdf.format(now.getTime()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                        }
                    } else {
                        sql = sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '" + sdf.format(now.getTime()) + " 00:00:00' ";
                    }
                }
            } else if ("2".equals(outpatient_type)) {
                //协同门诊也需要判断时间
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag){
                        sql += " AND outpatient.register_date is not null and outpatient.register_date >= str_to_date('" + sdf.format(now.getTime()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                    }else {
                        sql += " AND outpatient.register_date is not null and outpatient.register_date >= to_date('" + sdf.format(now.getTime()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                    }

                } else {
                    sql = sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '" + sdf.format(now.getTime()) + " 00:00:00' ";
                }
            }
        }
        logger.info("接口名称：doctorReviewConsultCount-->sql="+sql);
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);

        Long waitVideoCount = 0l;
        if (rstotal != null && rstotal.size() > 0) {
            waitVideoCount = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        return waitVideoCount;
    }

    /**
     * 保存在线排班
     *
     * @param onlineWorkJson
     * @return
     * @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);
        }
        timeDO.setCreateTime(new Date());
        return Envelop.getSuccess("保存成功");
    }

    /**
     * 删除在线排班
     *
     * @param id
     * @return
     * @throws Exception
     */
    public Envelop delDoctorOnlineWork(String id) throws Exception {
        wlyyDoctorOnlineTimeDao.delete(id);
        return Envelop.getSuccess("删除成功");
    }

    /**
     * 查询医生在线排班
     *
     * @param doctor
     * @param startDate
     * @param endDate
     * @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"));
    }

    /**
     * 发起图文和视频协同门诊复诊
     *
     * @param outpatientJson
     * @return
     * @throws Exception
     */
    public WlyyOutpatientDO cooperativeOutpatient(String outpatientJson, String registerJson, String chargeType) throws Exception {

        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());

        outpatientDO.setMjz("mz");
        outpatientDO.setStatus("0");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setIdcard(patientDO.getIdcard());
        outpatientDO.setOutpatientType("2");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setPayStatus(1);
        if (outpatientDO.getRegisterDate() == null) {
            outpatientDO.setRegisterDate(new Date());
        }
        String msg = "";
        String name=outpatientDO.getPatientName();
        String sex = "";
        String age="";
        String title = "";
        if (patientDO!=null){
            sex= IdCardUtil.getSexForIdcard(patientDO.getIdcard());
            age = IdCardUtil.getAgeForIdcard(patientDO.getIdcard())+"";
        }
        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        if (outpatientDO.getOutpatientType().equalsIgnoreCase("2")) {
            title = "协同复诊";
            msg = name + "（" + sex + " " + age + "岁）向您发起了协同复诊，点击查看";
        }
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
            String url=findDomainUrlInDict()+"/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
            enterpriseService.sendTWMesByDoctor("zsyy",outpatientDO.getDoctor(),title,msg,url);
        }else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
            String url="https://ih.xmheart.com/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
            enterpriseService.sendTWMesByDoctor("xm_xzzx_wx",outpatientDO.getDoctor(),title,msg,url);
        }else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
            String url=findDomainUrlInDict()+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
            enterpriseService.sendTWMesByDoctor("xm_ykyy_wx",outpatientDO.getDoctor(),title,msg,url);
        }
        System.out.println("发送协同复诊企业模板消息成功");
        WlyyPatientRegisterTimeDO registerTimeDO = null;
        try {
            //如果是视频预约咨询
            if (StringUtils.isNotBlank(registerJson)) {
                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                patientRegisterTimeDao.save(registerTimeDO);
            }
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约，请选择其他号源");
        }

        //3.创建候诊室
        createRoom(outpatient, chargeType);

        return outpatient;
    }

    /**
     * 发送新增门诊信息
     *
     * @param outpatient
     * @return
     */
    public SystemMessageDO sendOutPatientMes(WlyyOutpatientDO outpatient,boolean payFlag)  {
        System.out.println("发送新增门诊信息");
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        String msg = "";
        try {
            JSONObject data = new JSONObject();
            //1.在线复诊2.协同门诊
            if ("2".equals(outpatient.getOutpatientType())) {
                systemMessageDO.setTitle("协同门诊");
                systemMessageDO.setType("3");
                systemMessageDO.setReceiver(outpatient.getDoctor());
                systemMessageDO.setReceiverName(outpatient.getDoctorName());
                systemMessageDO.setRelationCode(outpatient.getId());
                systemMessageDO.setSender(outpatient.getPatient());
                systemMessageDO.setSenderName(outpatient.getPatientName());
                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);
                systemMessageDO.setData(data.toString());
                logger.info("添加模板消息4");
                systemMessageService.saveMessage(systemMessageDO);
                BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
                if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                    ykyyService.pushNotificationToYktPatient(patient.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
                }
            } else if ("3".equals(outpatient.getOutpatientType())) {//专家咨询
                //1.图文 2.视频 3家医
                if ("1".equals(outpatient.getType())) {
                    systemMessageDO.setTitle("图文咨询");
                    systemMessageDO.setType("18");
                    if (payFlag){
                        saveInquirySystemMessage(outpatient,null);
                    }
                    msg="图文咨询";
                } else if("3".equals(outpatient.getType())){
                    systemMessageDO.setTitle("家医咨询");
                    systemMessageDO.setType("15");
                    msg="家医咨询";
                    if (payFlag){
                        saveInquirySystemMessage(outpatient,null);
                    }
                }else {
                    systemMessageDO.setTitle("视频咨询");
                    systemMessageDO.setType("17");
                    if (payFlag){
                        saveInquirySystemMessage(outpatient,null);
                    }
                    msg = "您的视频咨询已预约成功。\n" +
                            "预计" + outpatient.getDoctorName() + "医生将于" + outpatient.getRegisterDate() + " 与您进行视频咨询。请留意系统消息或微信公众号消息。咨询开始时，医生将邀请您进行视频通话，请您关注消息提醒，及时接受医生视频邀请。";
                    sendWxTemplateMsg(wechatId, outpatient.getId(),null, "17", "videoOrderRemind", "");

                }
                systemMessageDO.setReceiver(outpatient.getDoctor());
                systemMessageDO.setReceiverName(outpatient.getDoctorName());
                systemMessageDO.setRelationCode(outpatient.getId());
                systemMessageDO.setSender(outpatient.getPatient());
                systemMessageDO.setSenderName(outpatient.getPatientName());
                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);
                systemMessageDO.setData(data.toString());
                logger.info("添加模板消息4");
                systemMessageService.saveMessage(systemMessageDO);
                BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
                if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                    ykyyService.pushNotificationToYktPatient(patient.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
                }
            } else if ("1".equals(outpatient.getOutpatientType()))  {        //在线复诊
                //1.图文 2.视频
                if ("1".equals(outpatient.getType())) {
                    systemMessageDO.setTitle("图文复诊");
                    systemMessageDO.setType("1");
                    if (payFlag){
                        saveInquirySystemMessage(outpatient,null);
                    }
                    msg="图文复诊";
                } else {
                    systemMessageDO.setTitle("视频复诊预约成功");
                    systemMessageDO.setType("2");

                    if (payFlag){
                        saveInquirySystemMessage(outpatient,null);
                    }
                    msg = "您的视频复诊已预约成功。\n" +
                            "预计" + outpatient.getDoctorName() + "医生将于" + outpatient.getRegisterDate() + " 与您进行视频咨询。请留意系统消息或微信公众号消息。咨询开始时，医生将邀请您进行视频通话，请您关注消息提醒，及时接受医生视频邀请。";

                    sendWxTemplateMsg(wechatId, outpatient.getId(),null, "16", "videoOrderRemind", "");

                }
                systemMessageDO.setReceiver(outpatient.getDoctor());
                systemMessageDO.setReceiverName(outpatient.getDoctorName());
                systemMessageDO.setRelationCode(outpatient.getId());
                systemMessageDO.setSender(outpatient.getPatient());
                systemMessageDO.setSenderName(outpatient.getPatientName());
                systemMessageDO.setRelationCode(outpatient.getId());
                logger.info("添加模板消息5");
                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());
                systemMessageService.saveMessage(systemMessageDO);
            }
            BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
            }
            return systemMessageDO;
        }catch (Exception e){
            e.printStackTrace();
            logger.info("sendOutPatientMes"+e.getMessage());
            return  null;
        }
    }

    public void saveInquirySystemMessage(WlyyOutpatientDO outpatient,ConsultTeamDo consultTeamDo) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        String msg = "";
        String type = "";
        systemMessageDO.setTitle("支付提醒");
        systemMessageDO.setType("11");
        JSONObject data = new JSONObject();
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatient.getId());
        if (outpatient!=null){
            if("1".equalsIgnoreCase(outpatient.getOutpatientType())){
                if ("1".equals(outpatient.getType())) {
                    type = "9";
                    msg = outpatient.getPatientName() + "，您好！您有一个图文复诊订单待支付，请及时支付。点击完成支付，如您已支付请忽略本条信息。";
                } else if ("2".equals(outpatient.getType())){
                    type = "16";
                    msg = outpatient.getPatientName() + "，您好！您有一个视频复诊订单待支付，请及时支付。点击完成支付，如您已支付请忽略本条信息。";
                }
            }else if ("3".equalsIgnoreCase(outpatient.getOutpatientType())){
                if ("1".equals(outpatient.getType())) {
                    type = "1";
                    msg = outpatient.getPatientName() + "，您好！您有一个图文咨询订单待支付，请及时支付。点击完成支付，如您已支付请忽略本条信息。";
                } else if ("2".equals(outpatient.getType())){
                    type = "17";
                    msg = outpatient.getPatientName() + "，您好！您有一个视频咨询订单待支付，请及时支付。点击完成支付，如您已支付请忽略本条信息。";
                }
            }
            systemMessageDO.setSender(outpatient.getDoctor());
            systemMessageDO.setSenderName(outpatient.getDoctorName());
            systemMessageDO.setRelationCode(outpatient.getId());
            systemMessageDO.setReceiver(outpatient.getPatient());
            systemMessageDO.setReceiverName(outpatient.getPatientName());

           data = new JSONObject();
            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);
                systemMessageDO.setData(data.toString());
                systemMessageService.saveMessage(systemMessageDO);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (businessOrderDO!=null&&0!=businessOrderDO.getPayPrice()){
                sendWxTemplateMsg(wechatId, outpatient.getId(),null, type, "payRemind", "");
            }
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
            }
        }


        if (consultTeamDo!=null){
            BaseDoctorDO doctorDO = baseDoctorDao.findById(consultTeamDo.getDoctor());
            BasePatientDO patientDO = basePatientDao.findById(consultTeamDo.getPatient());
            if (consultTeamDo.getType()==17){
                type = "17";
                msg = patientDO.getName() + "，您好！您有一个视频咨询订单待支付，请及时支付。点击完成支付，如您已支付请忽略本条信息。";
            }else if (consultTeamDo.getType()==1){
                type = "1";
                msg = patientDO.getName() + "，您好！您有一个图文咨询订单待支付，请及时支付。点击完成支付，如您已支付请忽略本条信息。";
            }
            systemMessageDO.setSender(consultTeamDo.getDoctor());
            systemMessageDO.setSenderName(doctorDO.getName());
            systemMessageDO.setRelationCode(consultTeamDo.getConsult());
            systemMessageDO.setReceiver(consultTeamDo.getPatient());
            systemMessageDO.setReceiverName(consultTeamDo.getName());

           data = new JSONObject();
            try {
                data.put("name", patientDO.getName());
                data.put("age", IdCardUtil.getAgeForIdcard(patientDO.getIdcard()));
                data.put("gender", IdCardUtil.getSexForIdcard_new(patientDO.getIdcard()));
                data.put("question", consultTeamDo.getSymptoms());
                data.put("msg", msg);
                data.put("type", type);
                systemMessageDO.setData(data.toString());
                systemMessageService.saveMessage(systemMessageDO);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (businessOrderDO!=null&&0!=businessOrderDO.getPayPrice()){
                sendWxTemplateMsg(wechatId, "",consultTeamDo, type, "payRemind", "");
            }
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                ykyyService.pushNotificationToYktPatient(patientDO.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
            }
        }


    }


    /**
     * 指定门诊医生医生
     *
     * @param outpatientJson
     * @return
     * @throws Exception
     */
    public WlyyOutpatientDO saveOutpatientDoctor(String outpatientJson, String registerJson, String chargeType) throws Exception {

        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);

        WlyyOutpatientDO one = outpatientDao.findOne(outpatientDO.getId());
        if (StringUtils.isNotBlank(one.getDoctor())&&(one.getStatus().equalsIgnoreCase("1")||one.getStatus().equalsIgnoreCase("2"))) {
            throw new RuntimeException("已有医生接诊");
        }
        one.setDoctor(outpatientDO.getDoctor());
        one.setDoctorName(outpatientDO.getDoctorName());
        one.setRegisterDate(outpatientDO.getRegisterDate());
        one.setDept(outpatientDO.getDept());
        one.setDeptName(outpatientDO.getDeptName());
        one.setType(outpatientDO.getType());
        one.setOutpatientType(outpatientDO.getOutpatientType());
        WlyyOutpatientDO outpatient = outpatientDao.save(one);

        WlyyPatientRegisterTimeDO registerTimeDO = null;

        try {
            //如果是视频预约咨询
            if (StringUtils.isNotBlank(registerJson)) {
                //删除预约记录
                List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByOutpatientId(outpatientDO.getId());
                if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                    patientRegisterTimeDao.delete(registerTimeDOs);
                }

                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                patientRegisterTimeDao.save(registerTimeDO);
            }else {
                one.setRegisterDate(new Date());
                outpatientDao.save(one);
            }
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约，请选择其他号源");
        }

        //更新候诊室
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outpatientDO.getId());

        if (roomDOs != null && roomDOs.size() > 0) {
            for (WlyyHospitalWaitingRoomDO room : roomDOs) {
                room.setDept(outpatientDO.getDept());
                room.setDeptName(outpatientDO.getDeptName());
                room.setDoctor(outpatientDO.getDoctor());
                room.setDoctorName(outpatientDO.getDoctorName());
                room.setConsultType(Integer.parseInt(outpatientDO.getType()));
                room.setChargeType(chargeType);
            }
            hospitalWaitingRoomDao.save(roomDOs);
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            String doctorYktid = "";
            String orderNo = "";
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
            if (baseDoctorDO!=null){
                if(StringUtils.isNoneBlank(baseDoctorDO.getYktDoctorId())){
                    doctorYktid = baseDoctorDO.getYktDoctorId();
                }else {
                    DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(baseDoctorDO.getId());
                    if (doctorMappingDO!=null){
                        String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
                        System.out.println("Continue");
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(doctorResponse);
                        if (jsonObject.getInteger("code")==200){
                            com.alibaba.fastjson.JSONArray array = jsonObject.getJSONArray("data");
                            if (array!=null&&array.size()!=0){
                                doctorYktid=array.getJSONObject(0).getString("DOCTORUSERID");
                            }
                        }
                    }
                }
            }
            BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientDO.getId());
            if (businessOrderDO!=null){
                orderNo = businessOrderDO.getOrderNo();
            }
            String res = ykyyService.updateDoctorIdByOrderId(doctorYktid,orderNo);
            WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
            if (StringUtils.isNoneBlank(res)){
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(res);
                if (object!=null){
                    wlyyHttpLogDO.setCode(object.getString("code"));
                }
            }
            wlyyHttpLogDO.setName("患者选择抢单医生id写入眼科通");
            wlyyHttpLogDO.setCode("update_doctorid_by_orderno");
            wlyyHttpLogDO.setRequest("doctorId="+doctorYktid+";"+"orderNo="+orderNo);
            wlyyHttpLogDO.setDoctor(outpatientDO.getDoctor());
            wlyyHttpLogDO.setPatient(outpatientDO.getConsumer());
            wlyyHttpLogDO.setResponse(res);
            wlyyHttpLogDO.setCreateTime(new Date());
            wlyyHttpLogDao.save(wlyyHttpLogDO);
        }

        return outpatient;
    }

    /**
     * 验证电子健康卡授权
     *
     * @param authorizeNo
     * @return
     */
    public Map<String, Object> checkOauthQRCode(String authorizeNo) {

        Map<String, Object> rsMap = new HashedMap();
        OauthYlzConfigDO oauthYlzConfigDO = oauthYlzConfigDao.findOne("ylz_config");
        try {
            TransRequest e = new TransRequest();
            e.setMethod("ehc.ehealthcard.auth.query");
            e.setApp_id(oauthYlzConfigDO.getAppId());
            e.setTerm_id(oauthYlzConfigDO.getTermId());
            e.setVersion(oauthYlzConfigDO.getVersion());
            e.setTimestamp(DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss"));
            e.setSign_type(oauthYlzConfigDO.getSignType());
            e.setEnc_type(oauthYlzConfigDO.getEncType());
            com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
            bizContent.put("out_authorize_no", authorizeNo);
            e.setBiz_content(JSON.toJSONString(bizContent));

            EhcHandler ehcHandler = new EhcHandler(oauthYlzConfigDO.getUrl(), oauthYlzConfigDO.getAppId(), oauthYlzConfigDO.getTermId(), oauthYlzConfigDO.getAppKey());
            TransResponse re = ehcHandler.execute(e);
            String rs = com.alibaba.fastjson.JSONObject.toJSONString(re);
            com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.parse(rs);
            logger.info("checkOauthQRCode:" + rs);
            String ret_code = json.getString("ret_code");
            if ("0000".equals(ret_code)) {
                logger.info("biz_content: " + 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 = json.getJSONObject("biz_content");
                String auth_status = biz.getString("auth_status");
                if ("succ".equals(auth_status)) {
                    String idcard = biz.getString("id_no");
                    BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(idcard, "1");
                    if (patientDO == null) {
                        BasePatientDO patient = new BasePatientDO();

                        String salt = UUID.randomUUID().toString().substring(0, 5);
                        String mobile = biz.getString("mobile_phone");
                        String pw = mobile.substring(mobile.length() - 6);

                        patient.setIdcard(idcard);
                        patient.setName(biz.getString("user_name"));
                        patient.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                        patient.setSalt(salt);
                        patient.setMobile(mobile);
                        String sexString =IdCardUtil.getSexForIdcard_new(idcard);
                        if (StringUtils.isNoneBlank(sexString)){
                            patient.setSex(Integer.parseInt(sexString));
                        }else {
                            patient.setSex(3);
                        }
                        patient.setDel("1");
                        patient.setEnabled(1);
                        patient.setLocked(0);
                        patient.setCreateTime(new Date());
                        patient.setUpdateTime(new Date());
                        patient.setBirthday(DateUtil.strToDate(biz.getString("birthday"), "yyyyMMdd"));
                        basePatientDao.save(patient);
                        rsMap.put("sCode", auth_status);
                        rsMap.put("sMes", "success");
                        rsMap.put("patient", getPatientInfoMap(patient));
                        return rsMap;
                    } else {
                        rsMap.put("sCode", auth_status);
                        rsMap.put("sMes", "success");
                        rsMap.put("patient", getPatientInfoMap(patientDO));
                        return rsMap;
                    }
                } else if ("ing".equals(auth_status)) {
                    rsMap.put("sCode", auth_status);
                    rsMap.put("sMes", "正在授权");
                    return rsMap;
                } else if ("fail".equals(auth_status)) {
                    rsMap.put("sCode", auth_status);
                    rsMap.put("sMes", "授权失败");
                    return rsMap;
                } else if ("cancel".equals(auth_status)) {
                    rsMap.put("sCode", auth_status);
                    rsMap.put("sMes", "取消授权");
                    return rsMap;
                }
            }
            rsMap.put("sCode", "err");
            rsMap.put("sMes", "请求失败");
            return rsMap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        rsMap.put("sCode", "err");
        rsMap.put("sMes", "请求失败");
        return rsMap;
    }

    /**
     * 查询协同门诊记录
     *
     * @param generalDoctor
     * @param startDate
     * @param endDate
     * @param status
     * @return
     */
    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 " +
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.general_doctor = '" + generalDoctor + "'";
        if (StringUtils.isNotBlank(startDate)) {

            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sqlTotal += " and o.register_date >= str_to_date('" + startDate + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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)) {
                if (flag){
                    sqlTotal += " and o.register_date <= str_to_date('" + endDate + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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 + "'";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlTotal);

        Long total = 0l;
        if (rstotal != null && rstotal.size() > 0) {
            total = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        String sql = "SELECT " +
                " o.id AS \"id\", " +
                " o.adm_no AS \"admNo\", " +
                " o.origin_adm_no AS \"originAdmNo\", " +
                " o.register_no AS \"registerNo\", " +
                " o.origin_register_no AS \"originRegisterNo\", " +
                " o.origin_con_no AS \"originConNo\", " +
                " o.con_no AS \"conNo\", " +
                " o.outpatient_type AS \"outpatientType\", " +
                " o.type AS \"type\", " +
                " o.hospital AS \"hospital\", " +
                " o.hospital_name AS \"hospitalName\", " +
                " o.win_no AS \"winNo\", " +
                " o.dept AS \"dept\", " +
                " o.dept_name AS \"deptName\", " +
                " o.patient AS \"patient\", " +
                " o.patient_name AS \"patientName\", " +
                " o.doctor AS \"doctor\", " +
                " o.doctor_name AS \"doctorName\", " +
                " o.general_doctor AS \"generalDoctor\", " +
                " o.general_doctor_name AS \"generalDoctorName\", " +
                " o.idcard AS \"idcard\", " +
                " o.card_no AS \"cardNo\", " +
                " o.mjz AS \"mjz\", " +
                " o.icd10 AS \"icd10\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " o.advice AS \"advice\", " +
                " o.adm_date AS \"admDate\", " +
                " o.description AS \"description\", " +
                " o.disease_img AS \"diseaseImg\", " +
                " o.create_time AS \"createTime\", " +
                " o.con_date AS \"conDate\", " +
                " o.patient_cancel_type AS \"patientCancelType\", " +
                " o.patient_cancel_value AS \"patientCancelValue\", " +
                " o.patient_cancel_remark AS \"patientCancelRemark\", " +
                " o.register_date AS \"registerDate\", " +
                " o.status AS \"STATUS\", " +
                " o.evaluate_status AS \"evaluateStatus\" " +
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.general_doctor = '" + generalDoctor + "'";
        if (StringUtils.isNotBlank(startDate)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql += " and o.register_date >= str_to_date('" + startDate + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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)) {
                if (flag){
                    sql += " and o.register_date <= str_to_date('" + endDate + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    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(sort)) {
            sql += " ORDER BY o.register_date " + sort;
        } else {
            sql += " ORDER BY o.register_date ASC ";
        }

        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, size);
        //List<WlyyOutpatientDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyOutpatientDO.class));
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, total);
    }

    /**
     * 全科医生首页协同门诊统计列表.
     *
     * @param generalDoctor
     * @return
     */
    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");

        //今天协同门诊列表
        List<WlyyOutpatientDO> todayList = outpatientDao.findByGeneralDoctor(generalDoctor, startTime, endTime, "0");

        rs.put("todayList", todayList);

        List<WlyyOutpatientDO> todayBeginList = outpatientDao.findByGeneralDoctor(generalDoctor, startTime, endTime, "1");

        rs.put("todayBeginList", todayBeginList);

        Calendar tomorrowTime = Calendar.getInstance();
        tomorrowTime.setTime(startTime);
        tomorrowTime.add(Calendar.DATE, 1);

        Calendar tomorrowEndtime = Calendar.getInstance();
        tomorrowEndtime.setTime(endTime);
        tomorrowEndtime.add(Calendar.DATE, 1);
        //明天协同门诊列表
        List<WlyyOutpatientDO> tomorrowList = outpatientDao.findByGeneralDoctor(generalDoctor, tomorrowTime.getTime(), tomorrowEndtime.getTime(), "0");
        rs.put("tomorrowList", tomorrowList);

        //统计科预约医生
        String sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_role r ON d.id = r.doctor_code " +
                " WHERE " +
                " r.role_code ='specialist'" +
                " AND d.charge_type is not null " +
                " AND d.outpatient_type like '%xt%' ";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);

        Long doctorTotal = 0l;
        if (rstotal != null && rstotal.size() > 0) {
            doctorTotal = (Long) rstotal.get(0).get("total");
        }

        rs.put("doctorTotal", doctorTotal);

        //统计在线医生
        String onlineSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_role r ON d.id = r.doctor_code " +
                " WHERE " +
                " r.role_code ='specialist' " +
                " AND d.consult_status ='1' " +
                " AND d.charge_type is not null " +
                " AND d.outpatient_type like '%xt%' ";
        List<Map<String, Object>> oltotal = jdbcTemplate.queryForList(onlineSql);

        Long onlineTotal = 0l;
        if (oltotal != null && oltotal.size() > 0) {
            onlineTotal = Long.parseLong(oltotal.get(0).get("total").toString());
        }

        rs.put("onlineTotal", onlineTotal);

        return rs;
    }


    /**
     * 查询医生所有可抢单的数量
     *
     * @param doctor
     * @param dept
     * @return
     */
    public com.alibaba.fastjson.JSONObject findWaitingRoomOutpatientNumberByDoctor(String doctor, String dept) {

        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();


        //总数
        String sqlAll = "SELECT " +
                " COUNT(room.outpatient_id) AS \"total\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND outpatient.pay_status=1 AND outpatient.dept='" + dept + "' ";

        List<Map<String, Object>> alltotal = jdbcTemplate.queryForList(sqlAll);

        Long totalsqlAll = 0l;
        if (alltotal != null && alltotal.size() > 0) {
            totalsqlAll = Long.parseLong(alltotal.get(0).get("total").toString());
        }

        object.put("all", totalsqlAll);

        //图文复诊
        String imgAll = "SELECT " +
                " COUNT(room.outpatient_id) AS \"total\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND outpatient.pay_status=1 AND room.reservation_type=1 AND room.consult_type=1 AND outpatient.dept='" + dept + "' ";

        List<Map<String, Object>> imgtotal = jdbcTemplate.queryForList(imgAll);

        Long twCount = 0l;
        if (imgtotal != null && imgtotal.size() > 0) {
            twCount = Long.parseLong(imgtotal.get(0).get("total").toString());
        }

        object.put("twCount", twCount);

        //视频复诊
        String spsql = "SELECT " +
                " COUNT(room.outpatient_id) AS \"total\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND outpatient.pay_status=1 AND room.reservation_type=1 AND room.consult_type=2 AND outpatient.dept='" + dept + "' ";

        List<Map<String, Object>> sptotal = jdbcTemplate.queryForList(spsql);

        Long spcount = 0l;
        if (sptotal != null && sptotal.size() > 0) {
            spcount = Long.parseLong(sptotal.get(0).get("total").toString());
        }

        object.put("spCount", spcount);


        //协同门诊
        String xtsql = "SELECT " +
                " COUNT(room.outpatient_id) AS \"total\" " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND outpatient.pay_status=1 AND room.reservation_type=2 AND outpatient.dept='" + dept + "' ";

        List<Map<String, Object>> xttotal = jdbcTemplate.queryForList(xtsql);

        Long xtcount = 0l;
        if (xttotal != null && xttotal.size() > 0) {
            xtcount = Long.parseLong(xttotal.get(0).get("total").toString());
        }

        object.put("xtCount", xtcount);


        return object;
    }

    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", "医生已经接诊，无法取消");
                    return rs;
                } else {
                    roomDO.setVisitStatus(-1);
                    hospitalWaitingRoomDao.save(roomDO);
                }
            }
        }

        //更改门诊状态
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outPatientId);
        wlyyOutpatientDO.setStatus("-1");
        wlyyOutpatientDO.setDoctorCancelRemark(cancelRemark);
        wlyyOutpatientDO.setDoctorCancelType(cancelType);
        wlyyOutpatientDO.setDoctorCancelValue(cancelValue);
        outpatientDao.save(wlyyOutpatientDO);

        //删除门诊号源
        List<WlyyPatientRegisterTimeDO> list = patientRegisterTimeDao.findByOutpatientId(wlyyOutpatientDO.getId());
        if (list != null && list.size() > 0) {
            patientRegisterTimeDao.delete(list);
        }

        rs.put("code", 1);
        rs.put("mes", "取消成功");
        return rs;
    }

    /**
     * 获取居民当日就诊列表
     *
     * @param patient
     * @return
     */
    public List<Map<String, Object>> getTodayOutpatinetList(String patient, String wxId) {

        String condition = "";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                condition = "date_format(p.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            }else {
                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\",";
        }

        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)) {
            if (flag){
                sql += " AND p.register_date >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                sql += " AND p.register_date <= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
                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);
        return list;
    }

    /**
     * 获取doctormappingcode
     *
     * @param doctor
     * @param orgCode
     * @return
     */
    public DoctorMappingDO getDoctorMapping(String doctor, String orgCode) {
        return doctorMappingService.findMappingCode(doctor, orgCode);
    }

    /**
     * 获取医生简介
     *
     * @param doctorCode
     * @return
     * @throws Exception
     */
    public net.sf.json.JSON getDoctorIntroduction(String doctorCode) throws Exception {
        DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(doctorCode, "350211A1002");
        if (doctorMappingDO == null) {
            throw new RuntimeException("未找到医生映射信息");
        }
        return entranceService.BS16010(doctorMappingDO.getMappingCode(), demoFlag);
    }

    /**
     * @param name
     * @param hospital
     * @return
     */
    public List<WlyyHospitalSysDictDO> findByDict(String name, String hospital) {
        return sysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital, name);
    }

    /**
     * 建立档案
     *
     * @param json
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject setRecord(String json, String type) throws Exception {
        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()) + "");
            }
            if (StringUtils.isBlank(archiveVO.getCsrq00())) {
                archiveVO.setCsrq00(DateUtil.dateToStr(IdCardUtil.getBirthdayForIdcard(archiveVO.getSfzhao()), "yyyyMMdd"));
            }
            //1为需要同步建档
            if ("1".equals(type)) {
                rs = entranceService.BS16018(archiveVO, demoFlag);
            }
            //保存互联网医院居民账户
            BasePatientDO patientDO = savePatient(archiveVO);
            rs.put("patient", patientDO.getId());
        }
        return rs;
    }

    /**
     * 存储居民
     *
     * @param archiveVO
     * @return
     */
    public BasePatientDO savePatient(ArchiveVO archiveVO) throws Exception {
        BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(archiveVO.getSfzhao(), "1");
        if (patientDO == null) {
            BasePatientDO patient = new BasePatientDO();

            String salt = UUID.randomUUID().toString().substring(0, 5);
            String mobile = archiveVO.getYytel0();
            String pw = mobile.substring(mobile.length() - 6);

            patient.setIdcard(archiveVO.getSfzhao());
            String sexString =IdCardUtil.getSexForIdcard_new(archiveVO.getSfzhao());
            if (StringUtils.isNoneBlank(sexString)){
                patient.setSex(Integer.parseInt(sexString));
            }else {
                patient.setSex(3);
            }
            patient.setName(archiveVO.getXming0());
            patient.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
            patient.setSalt(salt);
            patient.setMobile(mobile);
            patient.setDel("1");
            patient.setEnabled(1);
            patient.setLocked(0);
            patient.setCreateTime(new Date());
            patient.setUpdateTime(new Date());
            patient.setBirthday(IdCardUtil.getBirthdayForIdcard(archiveVO.getSfzhao()));

            return basePatientDao.save(patient);
        }
        return patientDO;
    }

    /**
     * 获取HIIS居民档案信息
     *
     * @param idcard
     * @param patient
     * @param admitNum
     * @return
     * @throws Exception
     */
    public JSONArray findPatientRecord(String idcard, String patient, String admitNum, String ybcard) throws Exception {
        String patientId = null;
        if (StringUtils.isNotBlank(patient)) {
            /*patientId = patientMappingService.findHisPatNoByPatient(patient);*/
            BasePatientDO patientDO = basePatientDao.findById(patient);
            if (patientDO==null){
                return null;
            }
            PatientMappingDO patientMappingDO = patientMappingDao.findByIdcardAndSource(patientDO.getIdcard(),"1");
            if (patientMappingDO!=null){
                patientId = patientMappingDO.getMappingCode();
            }
        }
        return entranceService.BS10008(idcard, null,null,patientId, admitNum, ybcard, demoFlag);
    }

    /**
     * 查找未配送处方订单
     */
    public List<WlyyPrescriptionVO> findUndeliveredList() {
        String sql = "SELECT " +
                " p.id AS \"id\", " +
                " p.real_order AS \"realOrder\"," +
                " p.origin_real_order AS \"originRealOrder\"," +
                " p.adm_no AS \"admNo\"," +
                " p.origin_adm_no AS \"originAdmNo\"," +
                " p.serial_no AS \"serialNo\"," +
                " p.type AS \"type\", " +
                " p.patient_code AS \"patientCode\", " +
                " p.patient_name AS \"patientName\", " +
                " p.ssc AS \"ssc\", " +
                " p.doctor AS \"doctor\", " +
                " p.doctor_name AS \"doctorName\", " +
                " p.status AS \"status\", " +
                " p.mk_fail_reason AS \"mkFailReason\", " +
                " p.mk_time AS \"mk_time\", " +
                " p.prescribe_reason AS \"prescribeReason\", " +
                " p.prescribe_time AS \"prescribeTime\", " +
                " p.pay_time AS \"payTime\", " +
                " p.dosage_time AS \"dosageTime\", " +
                " p.finish_time AS \"finishTime\", " +
                " p.create_time AS \"createTime\", " +
                " p.dept AS \"dept\", " +
                " p.dept_name AS \"deptName\", " +
                " p.hospital AS \"hospital\", " +
                " p.hospital_name AS \"hospitalName\", " +
                " p.consult AS \"consult\", " +
                " p.dispensary_type AS \"dispensaryType\", " +
                " p.reason AS \"reason\", " +
                " p.remark AS \"remark\", " +
                " p.cancel_reason AS \"cancelReason\", " +
                " p.ca_cert_data AS \"caCertData\", " +
                " p.ca_message AS \"caMessage\", " +
                " p.digital_sign_no AS \"digitalSignNo\", " +
                " p.original_data_abstract AS \"originalDataAbstract\", " +
                " p.str_original_data AS \"strOriginalData\", " +
                " p.his_dept_code AS \"hisDeptCode\", " +
                " p.his_doctor_code AS \"hisDoctorCode\", " +
                " p.his_gister_type_code AS \"hisGisterTypeCode\", " +
                " p.his_rate_type_code AS \"hisRateTypeCode\", " +
                " p.his_hospital AS \"hisHospital\", " +
                " p.his_register_fee AS \"hisRegisterFee\", " +
                " p.pay_status AS \"payStatus\" " +
                " FROM " +
                " wlyy_prescription p " +
                " WHERE status = 60 or status = 50 ";
        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyPrescriptionVO.class));
        if (list != null) {
            return list;
        }
        return new ArrayList<>();
    }

    /**
     * 获取医生信息
     *
     * @param hospital
     * @param name
     * @return
     */
    public List<Map<String, Object>> findDoctorByName(String hospital, String name, String chargeType,String dept) {
        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.name AS \"name\"" +
                " FROM " +
                " base_doctor d ";
        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 + "'";
        }
        if(StringUtils.isNotBlank(dept)){
            sql+= " AND h.dept_code = '"+dept+"'";
        }

        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equals(chargeType)) {
                //查询全部号源
            } else {
                sql += " AND d.charge_type ='" + chargeType + "'";
            }
        } else {
            sql += " AND d.charge_type is not null ";
        }

        sql += " AND r.role_code ='specialist'";

        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<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(d.get("id").toString());
                d.put("depts", depts);
            }
        }
        return list;
    }

    public void followOrgByPatient(String patientid, String doctorid, String type) {
        List<BaseDoctorPatientFollowDO> list = baseOrgPatientDao.findByDoctorAndPatient(doctorid, patientid);
        if ("1".equals(type)) {//关注
            if (list.isEmpty()) {
                BaseDoctorPatientFollowDO baseOrgPatientFollowDO = new BaseDoctorPatientFollowDO();
                baseOrgPatientFollowDO.setDoctor(doctorid);
                baseOrgPatientFollowDO.setPatient(patientid);
                baseOrgPatientDao.save(baseOrgPatientFollowDO);
            }
        }
        if ("0".equals(type)) {//取消关注
            if (!list.isEmpty()) {
                for (BaseDoctorPatientFollowDO baseOrgPatientFollowDO : list) {
                    baseOrgPatientDao.delete(baseOrgPatientFollowDO.getId());
                }
            }
        }
    }

    public List<Map<String, Object>> findDeptByKeyWord(String keyWord, Integer page, Integer pagesize) {

        String sql = "SELECT " +
                "dept.code AS \"deptCode\"," +
                "dept.name AS \"deptName\"," +
                "org.CODE AS \"orgCode\", " +
                "org.NAME AS \"orgName\" " +
                "FROM " +
                "dict_hospital_dept dept," +
                "base_org org " +
                "WHERE org.CODE=dept.org_code " +
                "AND org.del=1 ";

        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);
        return list;
    }

    public List<Map<String, Object>> findDeptWithDoctorWorkTime(String hospital, String keyWord, Integer page, Integer pagesize) {

        String now = DateUtil.dateToStr(new Date(), "yyyy-MM-dd");
//        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");

        String sql = "SELECT  " +
                " DISTINCT " +
                " h.dept_code AS \"deptCode\", " +
                " h.dept_name AS \"deptName\"," +
                " h.org_code AS \"orgCode\"," +
                " h.org_name AS \"orgName\"" +
                " FROM " +
                " base_doctor_hospital h " +
                " JOIN base_doctor d ON h.doctor_code = d.id" +
                " WHERE " +
                " ( EXISTS ( " +
                " SELECT " +
                "  w.doctor " +
                " FROM " +
                "  wlyy_doctor_work_time w " +
                " WHERE " +
                "  w.doctor = h.doctor_code " +
                " AND start_time <=:startTime " +
                " AND end_time >=:endDate " +
                " ) OR d.consult_status ='1') " +
                " AND h.dept_code IS NOT NULL " +
                " 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);
        }
        if (StringUtils.isNotBlank(keyWord)) {
            sql += " AND h.dept_name like:keyWord";
            params.put("keyWord", "%" + keyWord + "%");
        }
        logger.info(sql);
        return hibenateUtils.createSQLQuery(sql, params, page, pagesize);
    }


    public String testYt()throws Exception{
        Map<String, String> map = new HashedMap();
        map.put("object","cgMLzMGWyPqVrHAD8JrUcLi+zX7o109MEKl+7Hzg8djZPjv9mkQM2fahQdSROvSE423tbABvN5kb0DmT6HyST0VtguxzR2qdan1zvyegsD78QByzTCC97EEB93GYe8ZfsI2b/lsXRv8/ro6nImjkng==");
        String repsonse = HttpClientUtils.doGet("https://www.xmdsyy.cn/dsyy/hospital/open/noLogin/ytzfNotify");
        logger.info(repsonse);
        return repsonse;
    }


    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" +
                "\tp.doctor as \"doctor\",\n" +
                "\tp.id as \"id\",\n" +
                "\tp.doctor_name as \"doctorName\",\n" +
                "\tp.dept as \"dept\",\n" +
                "\tp.dept_name as \"deptName\",\n" +
                "\tp.hospital as \"hospital\",\n" +
                "\tp.hospital_name as \"hospitalName\",\n" +
                "\tp.patient_code as \"patientCode\",\n" +
                "\tp.patient_name as \"patientName\",\n" +
                "\tp.idcard as \"idcard\",\n" +
                "\tp.ssc as \"ssc\",\n";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag){
                sql = sql + "date_format(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            }else {
                sql = sql + "to_char(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            }

        } else {
            sql = sql + "date_format(p.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
        }
        sql += "\tp.status as \"status\",\n" +
                "\tp.check_status as \"checkStatus\",\n" +
                "\tp.check_reason as \"checkReason\",\n" +
                "\tp.pay_type as \"payType\"\n" +
                "FROM\n" +
                "\twlyy_prescription P\n" +
                "WHERE\n" +
                "\t1 = 1 and  p.check_status not in (3,4) ";
        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(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(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 + "%')";
        }
        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 and  p.check_status not in (3,4)  ";
        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(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(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 + "%')";
        }
        Long count = 0L;
        List<Map<String, Object>> total = hibenateUtils.createSQLQuery(sqlTotal, params1);
        if (total != null) {
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        Map<String, Object> map = new HashedMap();
       /* for (Map<String,Object> map1:mapList){
            String outpatientId = null;
            List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(map1.get("doctor").toString());
            if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);

            }
        }*/
        map.put("count", count);
        map.put("list", mapList);
        maps.add(map);
        return maps;
    }

    /**
     * 修改处方状态
     *
     * @param prescriptionId
     * @param status
     */
    public void updateStatus(String prescriptionId, Integer status) {
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        prescriptionDao.updateStatus( status, new Date(),prescriptionId);
        prescriptionLogService.addPrescriptionLog(prescriptionId, status, 1, wlyyPrescriptionDO.getPatientCode(), wlyyPrescriptionDO.getPatientName(), null, new Date());
    }


    /**
     * 更改订单号
     *
     * @param id
     * @param mailNo
     */
    public void updateMailNoById(String id, String mailNo) {
        prescriptionExpressageDao.updateMailNoById(id, mailNo);
    }


    /**
     * 审方
     *
     * @param operate
     * @param operateName
     * @param reason
     * @param status
     * @param prescriptionId
     * @return
     */
    public WlyyPrescriptionCheckDO saveCheck(String operate, String operateName, String reason, Integer status, String prescriptionId, String wxId) {
        WlyyPrescriptionCheckDO prescriptionCheckDO = new WlyyPrescriptionCheckDO();
        prescriptionCheckDO.setCreateTime(new Date());
        prescriptionCheckDO.setOperate(operate);
        prescriptionCheckDO.setOperateName(operateName);
        prescriptionCheckDO.setUpdateTime(new Date());
        prescriptionCheckDO.setCreateUser(operate);
        prescriptionCheckDO.setCreateUserName(operateName);
        prescriptionCheckDO.setReason(reason);
        prescriptionCheckDO.setStatus(status);
        prescriptionCheckDO.setPrescriptionId(prescriptionId);
        prescriptionCheckDO = prescriptionCheckDao.save(prescriptionCheckDO);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (status == 2) {
            /*prescriptionDao.updateCheckStatus(prescriptionId,2,reason,20);*/
            logger.info("开始=====" + wlyyPrescriptionDO.getCheckStatus());
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
            DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
            List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyPrescriptionDiagnosisDO> prescriptionDiagnosisDOS = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionId,1);

            List<WlyyPrescriptionExpressageDO> expressageDOS = prescriptionExpressageDao.findByOutpatientId(outpatientDO.getId());
            if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                try {
                    //his处方拼接开方条件
                    com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
                    for (WlyyPrescriptionInfoDO info : infoDOS) {
                        //设置his药品查询条件
                        setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, wlyyPrescriptionDO, info, outpatientDO.getIcd10());
                    }
                    for (WlyyInspectionDO ins : inspectionDOS) {
                        //设置his药品查询条件
                        setInspectionParam(jsonData, doctorMappingDO, outpatientDO, wlyyPrescriptionDO, ins, outpatientDO.getIcd10());
                    }
                    if (expressageDOS!=null&&expressageDOS.size()!=0){
                        WlyyPrescriptionExpressageDO prescriptionExpressageDO = expressageDOS.get(0);
                        if (prescriptionExpressageDO!=null&&prescriptionExpressageDO.getOneselfPickupFlg()==0){
                            for (int i=0;i<jsonData.size();i++){
                                com.alibaba.fastjson.JSONObject object = jsonData.getJSONObject(i);
                                object.put("selfDelivered",0);
                            }
                        }else if (prescriptionExpressageDO!=null&&prescriptionExpressageDO.getOneselfPickupFlg()==1){
                            for (int i=0;i<jsonData.size();i++){
                                com.alibaba.fastjson.JSONObject object = jsonData.getJSONObject(i);
                                object.put("selfDelivered",1);
                            }
                        }
                    }
                    Map<String, Object> map = sendHisDiagnosis(jsonData, outpatientDO, wlyyPrescriptionDO);
                    //处方签名
                    logger.info("处方签名");
                    SOF_SignDataWithExtraInfo(wlyyPrescriptionDO);
                    //同步电子病历
                    WlyyPrescriptionEmrDO prescriptionEmrDO = prescriptionEmrDao.findEmrByPrescriptionId(prescriptionId);
                    if (prescriptionEmrDO != null) {
                        String doctorId = doctorMappingDO.getMappingCode();
                        String doctorName = doctorMappingDO.getDoctorName();
                        logger.info("电子病历签名");
                        SOF_SignDataWithExtraInfoEmr(prescriptionEmrDO);
                        writeOutPatient(outpatientDO.getRegisterNo(), prescriptionEmrDO.getComplaint(), prescriptionEmrDO.getMedicalHistory(), prescriptionEmrDO.getPastHistory(), prescriptionEmrDO.getPhysicalExamination(), prescriptionEmrDO.getAssistExamination(), doctorId, doctorName);
                    }
                    if (map.get("code").toString().equalsIgnoreCase("1")) {
                        //  * @param applyDepaName @param applyDoctorName
                        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
                        String patientCode = outpatientDO.getConsumer();
                        String realerOrder = prescriptionDO.getRealOrder();

                        String recipeTime = DateUtil.dateToStr(prescriptionDO.getCreateTime(), "yyyyMMddHHmmss");
                        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(prescriptionDO.getDoctor());
                        String applyDepaName = null;
                        if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
                            applyDepaName = doctorHospitalDOS.get(0).getDeptName();
                        }
                        String voucherNo = map.get("voucherNo") + "";
                        String applyDoctorName = prescriptionDO.getDoctorName();
                        BasePatientDO patientDO = basePatientDao.findById(patientCode);
                        String userName = null;
                        String idcard = null;
                        if (patientDO != null) {
                            userName = patientDO.getName();
                            idcard = patientDO.getIdcard();
                        }
                        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patientCode);
                        String userNo = null;
                        if (patientMappingDO != null) {
                            userNo = patientMappingDO.getMappingCode();
                        }
                        String cardNo = null;
                        if (StringUtils.isNoneBlank(outpatientDO.getCardNo())) {
                            cardNo = outpatientDO.getCardNo();
                        }
                        logger.info("cardNo:" + cardNo);
                        JSONObject object =entranceService.BS15054(patientMappingDO.getMappingCode(),prescriptionDO.getRealOrder(),demoFlag);
                        net.sf.json.JSONObject res = object.getJSONObject("resquest");
                        logger.info("获取待结算数据 res: " + res.toString());
                        String rsCode = res.getString("@RESULT");
                        String free= 0+"";
                        if ("0".equals(rsCode)) {
                            free = res.getString("@total_charge");
                        }
                        ylzPayService.msgPush("01", cardNo, "01", patientDO.getMobile(), "00", userNo, userName, idcard, voucherNo, applyDepaName, applyDoctorName, recipeTime, free, "1","WX_PUB");
                        if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                            String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/prescriptionDetail?outpatientId="+outpatientDO.getId()+"&id="+prescriptionId;
                            sendZsMsgFlow("OL_JSTX",outpatientDO.getId(),prescriptionId,msgUrl,"结算提醒");
                        }
                    }else {
                        throw new Exception(map.get("mes").toString());
                    }
                    //sendHisDiagnosis(jsonData, outpatientDO, wlyyPrescriptionDO);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }else if (wxId.equalsIgnoreCase("xm_xzzx_wx")){
                try {
                    if (prescriptionDiagnosisDOS!=null&&prescriptionDiagnosisDOS.size()!=0){
                        String diagnosisName = prescriptionDiagnosisDOS.get(0).getName();
                        String diagnosisCode = prescriptionDiagnosisDOS.get(0).getCode();
                        //同步诊断
                        com.alibaba.fastjson.JSONObject jsonObject2 = xzzxEntranceService.saveDiagnosisToEntrance(outpatientDO.getRegisterNo(),diagnosisName,diagnosisCode);
                        logger.info("上传诊断返回参数"+jsonObject2);
                        //{"msg":"交易成功","code":"0","data":{"PresDetail":{"PresNo":"16151365"}},"success":"True"}
                        if (jsonObject2!=null){
                            if (jsonObject2.getString("code").equalsIgnoreCase("0")){
                                com.alibaba.fastjson.JSONObject jsonObject = jsonObject2.getJSONObject("data");
                                logger.info("上传诊断成功"+jsonObject2);
                            }
                        }
                    }
                    //同步处方
                    String applyDoctor = doctorMappingDO.getDoctorName()+"/"+doctorMappingDO.getMappingCode();
                    com.alibaba.fastjson.JSONObject object = xzzxEntranceService.savePrescriptionToEntrance("0",outpatientDO.getCardNo(),outpatientDO.getRegisterNo(),outpatientDO.getDept(),applyDoctor,"50100",infoDOS);
                    logger.info("成功上传处方"+object);
                    //{"msg":"交易成功","code":"0","data":{"PresDetail":{"PresNo":"16151365"}},"success":"True"}
                    if (object!=null){
                        if (object.getString("code").equalsIgnoreCase("0")){
                            com.alibaba.fastjson.JSONObject jsonObject = object.getJSONObject("data");
                            com.alibaba.fastjson.JSONObject jsonObject1 = jsonObject.getJSONObject("PresDetail");
                            String realOrder = jsonObject1.getString("PresNo");
                            wlyyPrescriptionDO.setAdmNo(outpatientDO.getAdmNo());
                            wlyyPrescriptionDO.setSerialNo(outpatientDO.getAdmNo());
                            wlyyPrescriptionDO.setRealOrder(realOrder);
                            //调医保接口
                            try {
                                if(healthCareService.isHospitalFlag()){
                                    String doctorPrescriptionUpload = entranceHealthCareUrl + "doctorPrescriptionUpload?prescriptionId="+wlyyPrescriptionDO.getId();
                                    String advanceWarning = entranceHealthCareUrl + "advanceWarning?outpatientId="+wlyyPrescriptionDO.getId();
                                    String infoResponse1 = httpClientUtil.get(doctorPrescriptionUpload,"GBK");
                                    logger.info("doctorPrescriptionUpload:"+infoResponse1);
                                    String infoResponse2 = httpClientUtil.get(advanceWarning,"GBK");
                                    logger.info("advanceWarning:"+infoResponse2);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                    logger.info("进入处方签名");
                    //处方签名
                    String baseSign=xzyyPrescriptionService.SOF_SignDataWithExtraInfo(wlyyPrescriptionDO);
                    //同步电子病历
                    WlyyPrescriptionEmrDO prescriptionEmrDO = prescriptionEmrDao.findEmrByPrescriptionId(prescriptionId);
                    try {
                        if (prescriptionEmrDO != null) {
                            logger.info("电子病历同步");
                            xzzxEntranceService.saveEmrToEntrance(prescriptionId,baseSign);
                            logger.info("电子病历同步");
                            logger.info("电子病历签名");
                            xzyyPrescriptionService.SOF_SignDataWithExtraInfoEmr(wlyyPrescriptionDO);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try {
                        if (object!=null){
                            if (object.getString("code").equalsIgnoreCase("0")){
                                //  * @param applyDepaName @param applyDoctorName
                                WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
                                String patientCode = outpatientDO.getConsumer();
                                String realerOrder = prescriptionDO.getRealOrder();

                                String recipeTime = DateUtil.dateToStr(prescriptionDO.getCreateTime(), "yyyyMMddHHmmss");
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(prescriptionDO.getDoctor());
                                String applyDepaName = null;
                                if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
                                    applyDepaName = doctorHospitalDOS.get(0).getDeptName();
                                }
                                String voucherNo = outpatientDO.getRegisterNo();
                                String applyDoctorName = prescriptionDO.getDoctorName();
                                BasePatientDO patientDO = basePatientDao.findById(patientCode);
                                String userName = null;
                                String idcard = null;
                                if (patientDO != null) {
                                    userName = patientDO.getName();
                                    idcard = patientDO.getIdcard();
                                }
                                PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patientCode);
                                String userNo = null;
                                if (patientMappingDO != null) {
                                    userNo = patientMappingDO.getMappingCode();
                                }
                                String cardNo = null;
                                if (StringUtils.isNoneBlank(outpatientDO.getCardNo())) {
                                    cardNo = outpatientDO.getCardNo();
                                }
                                logger.info("cardNo:" + cardNo);
                               /* JSONObject jsonObject =entranceService.BS15054(patientMappingDO.getMappingCode(),prescriptionDO.getRealOrder(),demoFlag);
                                net.sf.json.JSONObject res = jsonObject.getJSONObject("resquest");
                                logger.info("获取待结算数据 res: " + res.toString());
                                String rsCode = res.getString("@RESULT");
                                String free= 0+"";
                                if ("0".equals(rsCode)) {
                                    free = res.getString("@total_charge");
                                }*/
                                ylzPayService.msgPush("01", cardNo, "01", patientDO.getMobile(), "00", userNo, userName, idcard, voucherNo, applyDepaName, applyDoctorName, recipeTime, "", "","WX_PUB");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            prescriptionLogService.addPrescriptionLog(prescriptionId, 20, 2, operate, operateName, reason, new Date());
            wlyyPrescriptionDO.setCheckStatus(2);
            wlyyPrescriptionDO.setCheckReason(reason);
            wlyyPrescriptionDO.setStatus(20);
            wlyyPrescriptionDO.setPrescribeTime(new Date());
            wlyyPrescriptionDO.setId(prescriptionId);

            //发送系统消息 处方支付提醒
            SystemMessageDO messageDO = new SystemMessageDO();
            messageDO.setType("6");
            messageDO.setTitle("处方支付提醒");
            messageDO.setSender(outpatientDO.getDoctor());
            messageDO.setSenderName(outpatientDO.getDoctorName());
            messageDO.setRelationCode(outpatientDO.getId() + "," + wlyyPrescriptionDO.getId());
            messageDO.setReceiver(outpatientDO.getPatient());
            messageDO.setReceiverName(outpatientDO.getPatientName());
            JSONObject data = new JSONObject();
            try {
                data.put("name", outpatientDO.getPatientName());
                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);
                messageDO.setData(data.toString());
                systemMessageService.saveMessage(messageDO);

            } catch (Exception e) {
                e.printStackTrace();
            }
            BasePatientDO patient = basePatientDao.findById(outpatientDO.getPatient());
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), messageDO.getTitle(), data.get("msg").toString());
            }
            sendWxTemplateMsg(wxId, outpatientDO.getId(), null,"", "prescriptionPayRemind", wlyyPrescriptionDO.getId());
        } else {
            wlyyPrescriptionDO.setId(prescriptionId);
            wlyyPrescriptionDO.setCheckStatus(status);
            wlyyPrescriptionDO.setCheckReason(reason);
            /*if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                wlyyPrescriptionDO.setStatus(10);
            }else{
                wlyyPrescriptionDO.setStatus(11);
            }*/
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                wlyyPrescriptionDO.setStatus(10);
                if(!demoFlag) {
                    //同步his
                    try {
                        WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
                        ykyyEntranceService.findByRealOrder(prescriptionId, demoFlag);
                        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientDO.getId());
                        logger.info("cfsb", wlyyPrescriptionDO.getRealOrder());
                        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKTCONTROL");
                        if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

                        } else {
                            ykyyService.updateDrugorderInfo(businessOrderDO.getOrderNo(), wlyyPrescriptionDO.getOrderId(), wlyyPrescriptionDO.getRealOrder());
                        }
                        List<WlyyPrescriptionInfoDO> list = prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
                        if (list!=null&&list.size()>0){
                            ykyySMSService.sendSmsByTempcode("prescription_remind", outpatientDO, wlyyPrescriptionDO, "");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                List<WlyyPrescriptionInfoDO> list = prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
                List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
                if (list!=null&&list.size()>0){
                }else {
                    if(inspectionDOS!=null&&inspectionDOS.size()>0){
                        wlyyPrescriptionDO.setStatus(9);
                        wlyyPrescriptionDO.setCheckReason("只开检查检验，不开药品无需审方");
                        wlyyPrescriptionDO.setCheckStatus(2);
                    }
                }
            }else{
                wlyyPrescriptionDO.setStatus(11);
            }

        }
        prescriptionDao.save(wlyyPrescriptionDO);
        if (status == 2 || status == 1) {
            sendCheckMessage(status, wlyyPrescriptionDO, operate, operateName);
        }


        return prescriptionCheckDO;
    }


    public WlyyPrescriptionCheckDO savePrescriptionCheck(String operate, String reason, Integer status, String prescriptionId) {
        String dept = null;
        String deptName = null;
        String job = null;
        String jobName = null;
        BaseDoctorDO doctorDO = baseDoctorDao.findById(operate);
        String operateName = null;
        if (doctorDO != null) {
            operateName = doctorDO.getName();
            job = doctorDO.getJobTitleCode();
            jobName = doctorDO.getJobTitleName();
        }
        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(operate);
        if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
            BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
            dept = doctorHospitalDO.getDeptCode();
            deptName = doctorHospitalDO.getDeptName();
        }
        WlyyPrescriptionCheckDO prescriptionCheckDO = new WlyyPrescriptionCheckDO();
        prescriptionCheckDO.setCreateTime(new Date());
        prescriptionCheckDO.setOperate(operate);
        prescriptionCheckDO.setOperateName(operateName);
        prescriptionCheckDO.setUpdateTime(new Date());
        prescriptionCheckDO.setCreateUser(operate);
        prescriptionCheckDO.setCreateUserName(operateName);
        prescriptionCheckDO.setReason(reason);
        prescriptionCheckDO.setStatus(status);
        prescriptionCheckDO.setDept(dept);
        prescriptionCheckDO.setDeptName(deptName);
        prescriptionCheckDO.setJob(job);
        prescriptionCheckDO.setJobName(jobName);
        prescriptionCheckDO.setPrescriptionId(prescriptionId);
        prescriptionCheckDO = prescriptionCheckDao.save(prescriptionCheckDO);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (status == 3) {
            wlyyPrescriptionDO.setStatus(10);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setDealStatus(1);
            wlyyPrescriptionDO.setDealReason(reason);
        } else if (status == 4) {
            wlyyPrescriptionDO.setStatus(10);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setDealStatus(2);
            wlyyPrescriptionDO.setDealReason(reason);
        } else if (status == 5) {
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckReason("未审核");
        }else if (status == 6) {
            wlyyPrescriptionDO.setCheckStatus(3);
            wlyyPrescriptionDO.setCheckReason("草稿");
        }
        prescriptionDao.save(wlyyPrescriptionDO);
        return prescriptionCheckDO;
    }


    /**
     * 查询审批记录
     *
     * @param prescriptionId
     * @return
     */
    public List<WlyyPrescriptionCheckDO> findPrescriptionCheck(String prescriptionId) {
        return prescriptionCheckDao.findByPrescriptionIdAndStatus(prescriptionId);
    }


    /**
     * 发送处方审核消息
     *
     * @param status
     * @param prescriptionDO
     * @param operate
     * @param operateName
     * @return
     */
    public SystemMessageDO sendCheckMessage(Integer status, WlyyPrescriptionDO prescriptionDO, String operate, String operateName) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        try {

            systemMessageDO.setReceiver(prescriptionDO.getDoctor());
            systemMessageDO.setReceiverName(prescriptionDO.getDoctorName());
            systemMessageDO.setRelationCode(prescriptionDO.getId());
            systemMessageDO.setSender(operate);
            systemMessageDO.setSenderName(operateName);
            JSONObject data = new JSONObject();
            Integer age = 0;
            String gender = "";
            BasePatientDO patientDO = basePatientDao.findById(prescriptionDO.getPatientCode());
            if (null!=patientDO&&StringUtils.isNotBlank(patientDO.getIdcard())) {
                age = IdCardUtil.getAgeForIdcard(patientDO.getIdcard());
                gender = IdCardUtil.getSexForIdcard(patientDO.getIdcard());
            }
            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.setTitle("审方通过");
                data.put("message", "审方通过");
                data.put("message", "您为" + prescriptionDO.getPatientName() + "（" + age + "岁 " + gender + "）开具的处方已审核通过。");
                /**
                 *  * @param userName      推送人姓名
                 * @param idCard        推送人身份证
                 * @param phone         推送人手机号
                 * @param title         推送标题
                 * @param url           跳转链接
                 * @param content       内容简介
                 * @param contentString 内容明细串
                 */
               /* String idCard = "";
                String phone = "";
                String title="";
                String url = "https://hlwyy.xmzsh.com/ims-wx/#/returnVisit/record?outpatientId="+prescriptionDO.getOutpatientId();
                String content = "";
                String contentString = "";
                if (patientDO!=null){
                    idCard = patientDO.getIdcard();
                    phone = patientDO.getMobile();
                    title = patientDO.getName()+",您好！医生已为您开具处方，请及时支付";
                }
                entranceService.ehospitalNotice(prescriptionDO.getPatientName())*/
            } else if (status == 1) {
                systemMessageDO.setType("8");
                systemMessageDO.setTitle("审方退回");
                data.put("message", "审方退回");
                data.put("message", "您为" + prescriptionDO.getPatientName() + "（" + age + "岁 " + gender + "）开具的处方被审方退回，请尽快处理");
            }
            systemMessageDO.setData(data.toString());
            systemMessageService.saveMessage(systemMessageDO);
        } catch (Exception e) {
            logger.error("sendPatientGetDrugMes :" + e.toString());
        }
        return systemMessageDO;
    }


    /**
     * 查询单条处方记录
     *
     * @param prescriptionId
     * @return
     * @throws Exception
     */
    public WlyyPrescriptionVO selectByPrescriptionId(String prescriptionId) throws Exception {
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (wlyyPrescriptionDO != null) {
            List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(wlyyPrescriptionDO.getDoctor());
            String deptName = null;
            String hospitalName =null;
            String sex = null;
            String age = null;
            String cardNo = null;
            if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                deptName = doctorHospitalDO.getDeptName();
                hospitalName = doctorHospitalDO.getOrgName();
            }
            BasePatientDO patientDO = basePatientDao.findById(wlyyPrescriptionDO.getPatientCode());
            if (patientDO!=null){
                sex = patientDO.getSex()+"";
                age = DateUtil.getAgeForIdcard(patientDO.getIdcard())+"";
            }
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
            if (outpatientDO!=null){
                cardNo = outpatientDO.getCardNo();
            }
            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);
            List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
            for (WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO : wlyyPrescriptionInfoDOS) {
                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);
                wlyyPrescriptionInfoVOS.add(prescriptionInfoVO);
            }
            prescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
            List<WlyyPrescriptionDiagnosisDO> wlyyPrescriptionDiagnosisDOS = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyPrescriptionDiagnosisVO> wlyyPrescriptionDiagnosisVOS = new ArrayList<>();
            for (WlyyPrescriptionDiagnosisDO prescriptionDiagnosisDO : wlyyPrescriptionDiagnosisDOS) {
                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);
                wlyyPrescriptionDiagnosisVOS.add(prescriptionDiagnosisVO);
            }
            prescriptionVO.setDiagnosisVOs(wlyyPrescriptionDiagnosisVOS);

            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyInspectionVO> inspectionVOList = new ArrayList<>();
            for (WlyyInspectionDO inspectionDO : inspectionDOS) {
                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);
                inspectionVOList.add(inspectionVO);
            }
            prescriptionVO.setInspectionVOs(inspectionVOList);
            prescriptionVO.setAge(age);
            prescriptionVO.setSex(sex);
            prescriptionVO.setDeptName(deptName);
            prescriptionVO.setHospitalName(hospitalName);
            prescriptionVO.setCardNo(cardNo);
            return prescriptionVO;
        }
        return null;
    }


    public void deleteById(Integer flag, String id) {
        if (flag == 1) {
            //药品
            prescriptionInfoDao.deleteById(id);
        } else if (flag == 2) {
            //诊断
            prescriptionDiagnosisDao.deleteById(id);
        } else if (flag == 3) {
            //检查检验
            wlyyInspectionDao.deleteById(id);
        }
    }


    public void zsSynHis(String prescriptionId) {
        try {
            WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
            List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
            DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());

            //his处方拼接开方条件
            com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
            for (WlyyPrescriptionInfoDO info : infoDOS) {
                //设置his药品查询条件
                setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, info, outpatientDO.getIcd10());
            }

            for (WlyyInspectionDO ins : inspectionDOS) {
                //设置his药品查询条件
                setInspectionParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, ins, outpatientDO.getIcd10());
            }
            sendHisDiagnosis(jsonData, outpatientDO, prescriptionDO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建电子病历
     *
     * @param wlyyPrescriptionEmrDO
     * @return
     */
    public WlyyPrescriptionEmrDO saveEmr(WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO) {
        wlyyPrescriptionEmrDO.setCreateTime(new Date());
        wlyyPrescriptionEmrDO.setUpdateTime(new Date());
        wlyyPrescriptionEmrDO.setDel(1);
        return prescriptionEmrDao.save(wlyyPrescriptionEmrDO);
    }


    /**
     * 查询电子病历
     *
     * @param prescriptionId
     * @return
     */
    public List<WlyyPrescriptionEmrDO> findByPrescriptionId(String prescriptionId) {
        return prescriptionEmrDao.findByPrescriptionId(prescriptionId);
    }


    /**
     * 保存排班规则
     *
     * @param advicesJson
     * @return
     */
    public Boolean sendOutPatientSuggest(String advicesJson) {
        List<WlyyConsultAdvice> advices = (List<WlyyConsultAdvice>) com.alibaba.fastjson.JSONArray.parseArray(advicesJson, WlyyConsultAdvice.class);
        if (advices!=null&&advices.size()>0){
            WlyyConsultAdvice advice = advices.get(0);
            String consult =  advice.getConsult();
            String sql = "select t.relation_code as \"relationCode\" from wlyy_consult t where t.id = '"+consult+"'";
            List<Map<String,Object>> map = hibenateUtils.createSQLQuery(sql);
            if(map!=null&&map.size()>0){
                String outpatientId= map.get(0).get("relationCode").toString();
               WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
               if (wlyyOutpatientDO!=null){
                   StringBuffer content = new StringBuffer();
                   StringBuffer icd10Code = new StringBuffer();
                   for (WlyyConsultAdvice consultAdvice:advices){
                       content.append(consultAdvice.getAdviceValue()+",");
                       icd10Code.append(consultAdvice.getAdviceKey()+",");
                   }
                   if (content!=null&&content.length()>0){
                       System.out.println("content+====="+content);
                       content.deleteCharAt(content.length()-1);
                       icd10Code.deleteCharAt(icd10Code.length()-1);
                   }
                   wlyyOutpatientDO.setStatus("2");
                   wlyyOutpatientDO.setIcd10Name(content.toString());
                   wlyyOutpatientDO.setIcd10(icd10Code.toString());
                   outpatientDao.save(wlyyOutpatientDO);
               }
            }
        }

        wlyyConsultAdviceDao.save(advices);
        return true;
    }

    /**
     * 获取咨询建议
     *
     * @param consultcode
     * @return
     */
    public List<WlyyConsultAdvice> getConsultSuggest(String consultcode) {
        return wlyyConsultAdviceDao.getByConsult(consultcode);
    }


    /**
     * 电子病历html
     *
     * @param registerSn
     * @return
     * @throws Exception
     */
    public String readOutPatient(String registerSn) throws Exception {
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<HtRequest>\n";
        xmlStr += "<REGISTER_SN>" + registerSn + "</REGISTER_SN>";
        String reqTime = DateUtil.dateToStr(new Date(), "yyyyMMddHHmmssSSS");
        xmlStr += "<REQ_TIME>" + reqTime + "</REQ_TIME>";
        xmlStr += "</HtRequest>";
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        params.put("type", "readOutPatient");
        params.put("xmlStr", xmlStr);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "manageOutRegister",
                params);

        logger.info("调用电子病历查询接口请求成功，返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json" + json);

        return json.toString();
    }


    /**
     * 电子病历xml
     *
     * @param registerSn
     * @return
     * @throws Exception
     */
    public WlyyPrescriptionEmrDO readOutPatientXml(String registerSn) throws Exception {
        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = new WlyyPrescriptionEmrDO();
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\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>";
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        params.put("type", "readOutPatientDetail");
        params.put("xmlStr", xmlStr);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "manageOutRegister",
                params);

        logger.info("调用电子病历查询接口请求成功，返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json" + json);
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(json.toString());
        wlyyPrescriptionEmrDO.setComplaint(object.getString("CHIEF_COMPLAINT"));
        wlyyPrescriptionEmrDO.setMedicalHistory(object.getString("HPI"));
        wlyyPrescriptionEmrDO.setPastHistory(object.getString("ELAPSEMHIS"));
        wlyyPrescriptionEmrDO.setPhysicalExamination(object.getString("BODYCHECK"));
        wlyyPrescriptionEmrDO.setAssistExamination(object.getString("ASSISTANTCHECK"));
        return wlyyPrescriptionEmrDO;
    }


    /**
     * 门诊病历列表信息
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public net.sf.json.JSON outpatient(String patient,String doctorId) throws Exception {
        try {
            baseOperateLogService.saveOperateLog(doctorId,patient,"EMR","住院病历","","");
        }catch (Exception e){
            e.printStackTrace();
        }
        PatientMappingDO mappingDO = patientMappingDao.findByPatient(patient);
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_OUTPATIENT_URL");
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        String patNo = null;
        if (mappingDO!=null){
            patNo = mappingDO.getMappingCode();
        }
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        params.put("type", "Outpatient");
        params.put("xmlStr", patNo);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "manageEmrDataRestore",
                params);

        logger.info("门诊病历列表信息，返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json" + json);

        return json;
    }


    /**
     * 医疗文书列表信息
     * @param patient
     * @return
     * @throws Exception
     */
    public net.sf.json.JSON outpmedicaldoc(String patient) throws Exception {
        PatientMappingDO mappingDO = patientMappingDao.findByPatient(patient);
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_OUTPATIENT_URL");
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        String patNo = null;
        if (mappingDO!=null){
            patNo = mappingDO.getMappingCode();
        }
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        params.put("type", "Outpmedicaldoc");
        params.put("xmlStr", patNo);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "manageEmrDataRestore",
                params);

        logger.info("门诊病历列表信息，返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json" + json);
        return json;
    }


    public net.sf.json.JSON getPatInfoDataXml(String opid,String recSn) throws Exception {

        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_OUTPATIENT_URL");
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        String data = null;
        if (StringUtils.isNoneBlank(opid)){
            data = "Outpatient_"+opid;
        }else if (StringUtils.isNoneBlank(recSn)){
            data = "Outpmedicaldoc_"+recSn;
        }
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        params.put("data", data);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "getPatInfoDataXml",
                params);

        logger.info("门诊病历列表信息，返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json" + json);
        return json;
    }

    public String writeOutPatient(String registerSn, String chiefComplaint, String hpi, String elapsemhis, String bodycheck, String assistanTcheck, String doctorId, String doctorName) throws Exception {
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\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>";
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        params.put("type", "writeOutPatient");
        params.put("xmlStr", xmlStr);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "manageOutRegister",
                params);

        logger.info("调用电子病历写入接口请求成功，返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json" + json);

        return json.toString();
    }





    /**
     * 关注医生
     * @param doctorId
     * @return
     */
//    public Envelop attentionDoctor(String doctorId){
//        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctorId);
//        if (doctorDO==null){
//            return Envelop.getError("医生不存在");
//        }
//        BaseDoctorPatientDO doctorPatientDO = new BaseDoctorPatientDO();
//        doctorPatientDO.setDoctorCode(doctorId);
//        doctorPatientDO.setDoctorName(doctorDO.getName());
//        String uid = userAgent.getUID();
//        BasePatientDO patientDO = basePatientDao.findById(uid);
//        if (patientDO==null){
//            return ObjEnvelop.getError("患者不存在");
//        }
//        doctorPatientDO.setPatientCode(uid);
//        doctorPatientDO.setPatientName(patientDO.getName());
//        doctorPatientDO.setStatus(1);
//        baseDoctorPatientDao.save(doctorPatientDO);
//        return ObjEnvelop.getSuccess("关注成功");
//    }


    /**
     *查询患者关注的医生
     * @param keyWord
     * @param outPatient
     * @param jobTitleCode
     * @param shift
     * @param page
     * @param pagesize
     * @return
     */
//    public PageEnvelop findAllAttentionDoctor(String keyWord, Integer outPatient, String jobTitleCode, Integer shift, Integer page, Integer pagesize) {
//        StringBuffer sql = new StringBuffer("SELECT DISTINCT\n" +
//                "\tc.*, e.org_name,\n" +
//                "\te.dept_name,\n" +
//                "\tIFNULL(k.disease_name,NULL)\n" +
//                "\tdisease_name\n" +
//                "FROM\n" +
//                "\tbase_doctor c\n" +
//                "RIGHT JOIN (\n" +
//                "\tSELECT\n" +
//                "\t\tdoctor_code\n" +
//                "\tFROM\n" +
//                "\t\tbase_doctor_paitent\n" +
//                "\tWHERE\n" + " patient_code = '"+userAgent.getUID()+"'\n" +
//                " ) d ON c.id = d.doctor_code\n" +
//                "LEFT JOIN (\n" +
//                "\tSELECT\n" +
//                "\t\t*\n" +
//                "\tFROM\n" +
//                "\t\twlyy_doctor_special_disease\n" +
//                ") k ON k.doctor_code = c.id\n" +
//                "LEFT JOIN (\n" +
//                "\tSELECT\n" +
//                "\t\t*\n" +
//                "\tFROM\n" +
//                "\t\tbase_doctor_hospital\n" +
//                ") e ON e.doctor_code = c.id");
//        StringBuffer countSql = new StringBuffer("SELECT DISTINCT\n" +
//                "\tc.*, e.org_name,\n" +
//                "\te.dept_name,\n" +
//                "\tk.disease_name\n" +
//                "FROM\n" +
//                "\tbase_doctor c\n" +
//                "RIGHT JOIN (\n" +
//                "\tSELECT\n" +
//                "\t\tdoctor_code\n" +
//                "\tFROM\n" +
//                "\t\tbase_doctor_paitent\n" +
//                "\tWHERE\n" + " patient_code = '"+userAgent.getUID()+"'\n" +
//                " ) d ON c.id = d.doctor_code\n" +
//                "LEFT JOIN (\n" +
//                "\tSELECT\n" +
//                "\t\t*\n" +
//                "\tFROM\n" +
//                "\t\twlyy_doctor_special_disease\n" +
//                ") k ON k.doctor_code = c.id\n" +
//                "LEFT JOIN (\n" +
//                "\tSELECT\n" +
//                "\t\t*\n" +
//                "\tFROM\n" +
//                "\t\tbase_doctor_hospital\n" +
//                ") e ON e.doctor_code = c.id");
//
//        if (shift==1){
//            sql.append(" JOIN (\n" +
//                    "\tSELECT\n" +
//                    "\t\t*\n" +
//                    "\tFROM\n" +
//                    "\t\tbase_doctor_hospital\n" +
//                    "\tWHERE\n" +
//                    "\t\tdept_name = '发热门诊'\n" +
//                    ") h ON h.doctor_code = c.id ");
//            countSql.append(" JOIN (\n" +
//                    "\tSELECT\n" +
//                    "\t\t*\n" +
//                    "\tFROM\n" +
//                    "\t\tbase_doctor_hospital\n" +
//                    "\tWHERE\n" +
//                    "\t\tdept_name = '发热门诊'\n" +
//                    ") h ON h.doctor_code = c.id ");
//        }
//        if (StringUtils.isNotEmpty(jobTitleCode)){
//            sql.append(" AND c.job_title_code =").append(jobTitleCode);
//            countSql.append(" AND c.job_title_code =").append(jobTitleCode);
//        }
//        if (outPatient==1){
//            sql.append(" JOIN (\n" +
//                    "\tSELECT DISTINCT\n" +
//                    "\t\t*\n" +
//                    "\tFROM\n" +
//                    "\t\twlyy_doctor_work_time\n" +
//                    "\tGROUP BY\n" +
//                    "\t\tdoctor\n" +
//                    ") f ON f.doctor = c.id");
//            countSql.append(" JOIN (\n" +
//                    "\tSELECT DISTINCT\n" +
//                    "\t\t*\n" +
//                    "\tFROM\n" +
//                    "\t\twlyy_doctor_work_time\n" +
//                    "\tGROUP BY\n" +
//                    "\t\tdoctor\n" +
//                    ") f ON f.doctor = c.id");
//        }
//        if(StringUtils.isNotEmpty(keyWord)){
//            sql.append(" WHERE\n" +
//                    "\t(\n" +
//                    " c.`name` LIKE  '%"+keyWord+"%'" +
//                    " OR e.dept_name LIKE '%"+keyWord+"%' " +
//                    " OR e.org_name LIKE  '%"+keyWord+"%'" +
//                    " OR c.expertise LIKE  '%"+keyWord+"%'" +
//                    " OR c.introduce LIKE  '%"+keyWord+"%'" +
//                    " OR k.disease_name LIKE  '%"+keyWord+"%'" +
//                    ") ");
//            countSql.append(" WHERE\n" +
//                    "\t(\n" +
//                    " c.`name` LIKE  '%"+keyWord+"%'" +
//                    " OR e.dept_name LIKE '%"+keyWord+"%' " +
//                    " OR e.org_name LIKE  '%"+keyWord+"%'" +
//                    " OR c.expertise LIKE  '%"+keyWord+"%'" +
//                    " OR c.introduce LIKE  '%"+keyWord+"%'" +
//                    " OR k.disease_name LIKE  '%"+keyWord+"%'" +
//                    ") ");
//        }
//        countSql.append(" GROUP BY c.id");
//        List<Map<String, Object>> countList = jdbcTemplate.queryForList(countSql.toString());
//        long count=countList.size();
//
//        sql.append(" ORDER BY C.update_time LIMIT ").append((page-1)*pagesize).append(",").append(pagesize);
//
//        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql.toString());
//        List<BaseDoctorVO> list = new ArrayList<>();
//
//        mapList.forEach(one->{
//            String json = com.alibaba.fastjson.JSONObject.toJSONString(one);
//            BaseDoctorDO doctorDO = com.alibaba.fastjson.JSONObject.parseObject(json, BaseDoctorDO.class);
//            BaseDoctorVO doctorVO = convertToModel(doctorDO, BaseDoctorVO.class);
//            if (one.get("org_name")!=null&&StringUtils.isNotEmpty(one.get("org_name").toString())){
//                doctorVO.setHospital(one.get("org_name").toString());
//            }
//            if(one.get("dept_name")!=null&&StringUtils.isNotEmpty(one.get("dept_name").toString())){
//                ArrayList<String> deptList = new ArrayList<>();
//                deptList.add(one.get("dept_name").toString());
//                doctorVO.setDepartment(deptList);
//            }
//            if (one.get("disease_name")!=null&&StringUtils.isNotEmpty(one.get("disease_name").toString())){
//                ArrayList<String> disList = new ArrayList<>();
//                disList.add(one.get("disease_name").toString());
//                doctorVO.setDisease(disList);
//            }
//
//            if (list!=null&&list.size()>0){
//                list.forEach(tow->{
//                    if (doctorVO.getId().equalsIgnoreCase(tow.getId())){
//                        if (tow.getDepartment()!=null&&StringUtils.isNotEmpty(tow.getDepartment().get(0))){
//                            doctorVO.getDepartment().add(tow.getDepartment().get(0));
//                        }
//                        if (tow.getDisease()!=null&&StringUtils.isNotEmpty(tow.getDisease().get(0))){
//                            doctorVO.getDisease().add(tow.getDisease().get(0));
//                        }
//                        list.remove(tow);
//                    }
//                });
//            }
//
//            list.add(doctorVO);
//        });
//
//
//
//        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find,list,page,pagesize,count);
//    }

    /**
     * 查询患者所有处方信息
     *
     * @param page
     * @param size
     * @return
     */
    public PageEnvelop findPatientAllPrescription(String keyName, String status, Integer page, Integer size,String patient,String isSelectDrug,boolean consumerflag) {
        BasePatientDO patientDO = basePatientDao.findById(patient);
        if (patientDO==null){
            return PageEnvelop.getError("找不到该患者",-1);
        }
        StringBuffer sql = new StringBuffer(" SELECT DISTINCT b.*, c.oneself_pickup_flg,f.job_title_code,f.job_title_name  FROM (SELECT a.* FROM wlyy_prescription a left join wlyy_outpatient o ON o.id=a.outpatient_id  WHERE o.consumer = '");
        StringBuffer countSql = new StringBuffer("select COUNT(DISTINCT b.id) count FROM (SELECT a.* FROM wlyy_prescription a left join wlyy_outpatient o ON o.id=a.outpatient_id  WHERE o.consumer = '");
        /*if (consumerflag){
            sql.append(" WHERE o.consumer = '");
            countSql.append(" WHERE o.consumer = '");
        }else{
            sql.append(" WHERE o.patient = '");
            countSql.append(" WHERE o.patient = '");
        }*/
        sql.append(patient).append("') b  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(patient).append("') b  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.isNoneBlank(isSelectDrug)){
            if("0".equalsIgnoreCase(isSelectDrug)){
                sql.append(" left join wlyy_inspection m on b.outpatient_id =m.outpatient_id");
                countSql.append(" left join wlyy_inspection m on b.outpatient_id =m.outpatient_id");
            }
            if ("1".equalsIgnoreCase(isSelectDrug)){
                sql.append(" left join wlyy_prescription_info m on b.id =m.prescription_id");
                countSql.append(" left join wlyy_prescription_info m on b.id =m.prescription_id");
            }
        }
        if (StringUtils.isNotEmpty(status)) {
            status = status.substring(1, status.length() - 1);
            if (StringUtils.isNoneBlank(isSelectDrug)){
                if("0".equalsIgnoreCase(isSelectDrug)){
                    sql.append(" where b.status IN( 9,").append(status).append(")");
                    countSql.append(" where b.status IN( 9,").append(status).append(")");
                }else {
                    sql.append(" where b.status IN(").append(status).append(")");
                    countSql.append(" where b.status IN(").append(status).append(")");
                }
            }else{
                sql.append(" where b.status IN(").append(status).append(")");
                countSql.append(" where b.status IN(").append(status).append(")");
            }
        } else {
            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) ");
        }
        if (StringUtils.isNoneBlank(isSelectDrug)){
            if("0".equalsIgnoreCase(isSelectDrug)){
                sql.append(" and m.del =1 ");
                countSql.append(" and m.del =1 ");
            }
            if ("1".equalsIgnoreCase(isSelectDrug)){
                sql.append(" and m.del =1");
                countSql.append(" and m.del =1");
            }
        }

        if (StringUtils.isNotEmpty(keyName)) {
            sql.append(" and (" +
                    " b.doctor_name LIKE '%" + keyName + "%' " +
                    " OR b.dept_name LIKE'%" + keyName + "%' " +
                    " OR b.hospital_name LIKE '%" + keyName + "%' " +
                    " OR m.drug_name LIKE '%" + keyName + "%' " +
                    " OR b.real_order LIKE '%" + keyName + "%' " +
                    ")");
            countSql.append(" and (" +
                    " b.doctor_name LIKE '%" + keyName + "%' " +
                    " OR b.dept_name LIKE'%" + keyName + "%' " +
                    " OR b.hospital_name LIKE '%" + keyName + "%' " +
                    " OR m.drug_name LIKE '%" + keyName + "%' " +
                    " OR b.real_order LIKE '%" + keyName + "%' " +
                    ")");
        }

        sql.append(" order by b.prescribe_time DESC ");

        List<WlyyPrescriptionVO> list = null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            String oracleSql = "SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tA .*\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";

            oracleSql += sql.toString();

            oracleSql += "\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <=" + page * size +
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= " + (page - 1) * size;
            if (flag){
                sql.append("  limit ").append((page - 1) * size).append(",").append(size);
                logger.info("MySql=" + sql.toString());
                list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            }else {
                logger.info("oracleSql=" + oracleSql);
                list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            }
        } else {
//            sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
            sql.append("  limit ").append((page - 1) * size).append(",").append(size);
            logger.info("MySql=" + sql.toString());
            list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        }
        for (WlyyPrescriptionVO singlePre:list){
            List<WlyyPrescriptionInfoDO> infoDOs = prescriptionInfoDao.findByPrescriptionId(singlePre.getId(),1);
            logger.info("singlePreId===="+singlePre.getId());
            logger.info("infoDOs"+infoDOs);
            List<WlyyPrescriptionInfoVO> infoVOS = new ArrayList<>();
            convertToModels(infoDOs, infoVOS, WlyyPrescriptionInfoVO.class);
            logger.info("infoVOS"+infoVOS);
            singlePre.setInfoVOs(infoVOS);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(singlePre.getId(),1);
            List<WlyyInspectionVO> inspectionVOS = new ArrayList<>();
            convertToModels(inspectionDOS, inspectionVOS, WlyyInspectionVO.class);
            //BeanUtils.copyProperties(inspectionDOS,inspectionVOS);
            singlePre.setInspectionVOs(inspectionVOS);
        }
//        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        logger.info("countSql=" + countSql.toString());
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(countSql.toString());
        long count = Long.parseLong(mapList.get(0).get("count").toString());
        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find, list, page, size, count);
    }


    /**
     * 查询取药地址
     *
     * @param outpatientId
     * @param longitude
     * @param dimension
     * @return
     */
    public MixEnvelop findDrugAddress(String outpatientId, String longitude, String dimension) {
        String sql = "SELECT\n" +
                "\ta.*\n" +
                "FROM\n" +
                "\tbase_org a\n" +
                "LEFT JOIN (\n" +
                "\tSELECT\n" +
                "\t\tc.*\n" +
                "\tFROM\n" +
                "\t\twlyy_prescription_expressage c\n" +
                "\tWHERE\n" +
                " c.outpatient_id = '" + outpatientId + "'" +
                " ) d ON a.`code` = d.hospital_code";
        BaseOrgDO baseOrgDO = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BaseOrgDO.class)).get(0);
        Map<String, String> rs = new HashMap<>();
        rs.put("hospital", baseOrgDO.getName());
        rs.put("address", baseOrgDO.getAddress());
        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);
    }


    public MixEnvelop selectByUrl(String oupatientId, String prescriptionId, String wxId) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        if (wxWechatDO == null) {
            throw new Exception("微信配置不存在！");
        }
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (prescriptionDO == null) {
            throw new Exception("处方不存在！");
        }
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(oupatientId);
        List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wxId, outpatientDO.getConsumer());
        if (patientWechatDos == null || patientWechatDos.size() == 0) {
            throw new Exception("openid不存在！");
        }
        BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);

        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(oupatientId);
        String idcard = null;
        if (wlyyOutpatientDO != null) {
            idcard = wlyyOutpatientDO.getCardNo();
        }
        if (!StringUtils.isNoneBlank(idcard)) {
            throw new Exception("就诊卡不存在！");
        }
        String url = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(), patientWechatDo.getOpenid(), idcard, "WX");
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(url);
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, object);
    }


    public MixEnvelop selectByUrlHsjc(Integer id,String wxId,String channel) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        if (wxWechatDO == null) {
            throw new Exception("微信配置不存在！");
        }

        BaseNatAppointmentDO natAppointmentDO = baseNatAppointmentDao.findOne(id);
        BasePatientDO patientDO = basePatientDao.findById(natAppointmentDO.getPatientId());
        List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wxId, natAppointmentDO.getPatientId());
        if (patientWechatDos == null || patientWechatDos.size() == 0) {
            throw new Exception("openid不存在！");
        }
        BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);

        String idcard = null;
        if (natAppointmentDO != null) {
            idcard = natAppointmentDO.getMedicare();
        }
        if (!StringUtils.isNoneBlank(idcard)) {
            throw new Exception("就诊卡不存在！");
        }
        String url = null;
        if (StringUtils.isNoneBlank(channel)&&channel.equalsIgnoreCase("ALI")){
            url = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(), patientDO.getAlipayId(), idcard, "ALI");
        }else {
            url = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(), patientWechatDo.getOpenid(), idcard, "WX");
        }
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(url);
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, object);
    }

    /**
     * 获取居民openId
     *
     * @param patientCode
     * @return
     */
    public MixEnvelop findPatientOpenId(String patientCode) {
        List<BasePatientWechatDo> basePatientWechatDo = patientWechatDao.findByWechatIdAndPatientId(wechatId, patientCode);
        if (basePatientWechatDo.isEmpty()) {
            return MixEnvelop.getSuccess("居民openID不存在", null);
        }
        String openid = basePatientWechatDo.get(0).getOpenid();
        if (StringUtils.isEmpty(openid)) {
            return MixEnvelop.getSuccess("居民openID不存在", null);
        }
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, openid);
    }

    /**
     * 查询科室简介
     *
     * @param orgCode
     * @param deptCode
     * @return
     */
    public MixEnvelop findDeptDesc(String orgCode, String deptCode) {
        DictDeptDescDO deptDescDO = dictDeptDescDao.findByDeptCodeAndOrgCode(deptCode, orgCode);
        if (deptDescDO != null) {
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, deptDescDO);
        } else {
            return MixEnvelop.getError("无该科室简介");
        }
    }

    /**
     * 查询机构科室
     *
     * @param orgCode
     * @return
     */
    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);
        }
        List<DictDeptDescDO> res = new ArrayList<>();
        deptDescDOList.forEach(one->{
            DictDeptDescDO descDO = new DictDeptDescDO();
            BeanUtils.copyProperties(one,descDO);
            descDO.setDeptDescription(null);
            res.add(descDO);
        });
        if (deptDescDOList == null || deptDescDOList.size() == 0) {
            return MixEnvelop.getError("无科室信息");
        }
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, res);
    }


    /**
     * 处方签名
     * @param prescriptionDO
     * @throws Exception
     */
    public void SOF_SignDataWithExtraInfo(WlyyPrescriptionDO prescriptionDO) throws Exception {
        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(prescriptionDO.getDoctor());
        BaseDoctorDO doctorDO = baseDoctorDao.findById(prescriptionDO.getDoctor());
        BasePatientDO patientDO = basePatientDao.findById(prescriptionDO.getPatientCode());
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
        PKIService_ServiceLocator locator = new PKIService_ServiceLocator();
        URL portAddress = new URL("http://192.0.33.91:8080/pkis/services/v1?wsdl");
        PKIService_PortType service = locator.getPKIServiceImplPort(portAddress);
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
        List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionDO.getId(), 1);
        List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionDO.getId(), 1);

        //his处方拼接开方条件
        com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
        for (WlyyPrescriptionInfoDO info : infoDOS) {
            //设置his药品查询条件
            setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, info, outpatientDO.getIcd10());
        }
        for (WlyyInspectionDO ins : inspectionDOS) {
            //设置his药品查询条件
            setInspectionParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, ins, outpatientDO.getIcd10());
        }
        // 1.1.1 服务端签名（带取证查询扩展信息）
        // inData 参数
        String inData = jsonData.toJSONString();
        inData = org.apache.commons.codec.binary.Base64.encodeBase64String(inData.getBytes("gbk"));
        // extInfo  参数
        String idCardNo = "123502004266006872;"+doctorDO.getIdcard();
        Map<String, String> extInfoMap = new HashMap<String, String>();
        extInfoMap.put("busSys", "ZhongJianXinLianHLWYY");
        extInfoMap.put("doctorNo", doctorMappingDO!=null?doctorMappingDO.getMappingCode():null);
        extInfoMap.put("doctorName", doctorMappingDO!=null?doctorMappingDO.getDoctorName():null);
        extInfoMap.put("deptName", "部门");
        extInfoMap.put("patientName", patientDO!=null?patientDO.getName():null);
        extInfoMap.put("patientSex", patientDO!=null?IdCardUtil.getSexForIdcard(patientDO.getIdcard()):null);
        extInfoMap.put("hospitalNo", wlyyOutpatientDO!=null?wlyyOutpatientDO.getOriginAdmNo():null);
        extInfoMap.put("hospitalNumber",  wlyyOutpatientDO!=null?wlyyOutpatientDO.getOriginConNo():null);
        extInfoMap.put("diagnostic", wlyyOutpatientDO!=null?wlyyOutpatientDO.getIcd10Name():null);
        String extInfo = org.apache.commons.codec.binary.Base64.encodeBase64String(JSON.toJSONString(extInfoMap).getBytes("GBK"));
        String result = service.SOF_SignDataWithExtraInfo(idCardNo, inData, extInfo);
        logger.info("请求返参"+result);
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(result);
        if ("1000".equalsIgnoreCase(object.getString("code"))){
            com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(object.getString("data"));
            for (int i=0;i<array.size();i++){
                com.alibaba.fastjson.JSONObject jsonObject = array.getJSONObject(i);
                String signData = jsonObject.getString("signData");
                String signResult = jsonObject.getString("signResult");
                String certData = jsonObject.getString("certData");
                WlyyPrescriptionSignDO prescriptionSignDO = new WlyyPrescriptionSignDO();
                prescriptionSignDO.setCertData(certData);
                prescriptionSignDO.setPrescriptionId(prescriptionDO.getId());
                prescriptionSignDO.setSignData(signData);
                prescriptionSignDO.setSignResult(signResult);
                prescriptionSignDO.setCreateTime(new Date());
                prescriptionSignDO.setUpdateTime(new Date());
                prescriptionSignDao.save(prescriptionSignDO);
            }
            prescriptionDO.setSignFlag(1);
        }
    }


    /**
     * 电子病历签名
     * @param prescriptionEmrDO
     * @throws Exception
     */
    public void SOF_SignDataWithExtraInfoEmr(WlyyPrescriptionEmrDO prescriptionEmrDO) throws Exception {
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionEmrDO.getPrescriptionId());
        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(prescriptionDO.getDoctor());
        BaseDoctorDO doctorDO = baseDoctorDao.findById(prescriptionDO.getDoctor());
        BasePatientDO patientDO = basePatientDao.findById(prescriptionDO.getPatientCode());
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
        PKIService_ServiceLocator locator = new PKIService_ServiceLocator();
        URL portAddress = new URL("http://192.0.33.91:8080/pkis/services/v1?wsdl");
        PKIService_PortType service = locator.getPKIServiceImplPort(portAddress);

        //电子病历签名
        com.alibaba.fastjson.JSONObject jsonData = new com.alibaba.fastjson.JSONObject();
        jsonData.put("CHIEF_COMPLAINT",prescriptionEmrDO.getComplaint());
        jsonData.put("HPI",prescriptionEmrDO.getMedicalHistory());
        jsonData.put("ELAPSEMHIS",prescriptionEmrDO.getPastHistory());
        jsonData.put("BODYCHECK",prescriptionEmrDO.getPhysicalExamination());
        jsonData.put("ASSISTANTCHECK",prescriptionEmrDO.getAssistExamination());
        // 1.1.1 服务端签名（带取证查询扩展信息）
        // inData 参数
        String inData = jsonData.toJSONString();
        inData = org.apache.commons.codec.binary.Base64.encodeBase64String(inData.getBytes("gbk"));
        // extInfo  参数
        String idCardNo = "123502004266006872;"+doctorDO.getIdcard();
        Map<String, String> extInfoMap = new HashMap<String, String>();
        extInfoMap.put("busSys", "ZhongJianXinLianHLWYY");
        extInfoMap.put("doctorNo", doctorMappingDO!=null?doctorMappingDO.getMappingCode():null);
        extInfoMap.put("doctorName", doctorMappingDO!=null?doctorMappingDO.getDoctorName():null);
        extInfoMap.put("deptName", "部门");
        extInfoMap.put("patientName", patientDO!=null?patientDO.getName():null);
        extInfoMap.put("patientSex", patientDO!=null?IdCardUtil.getSexForIdcard(patientDO.getIdcard()):null);
        extInfoMap.put("hospitalNo", wlyyOutpatientDO!=null?wlyyOutpatientDO.getOriginAdmNo():null);
        extInfoMap.put("hospitalNumber",  wlyyOutpatientDO!=null?wlyyOutpatientDO.getOriginConNo():null);
        extInfoMap.put("diagnostic", wlyyOutpatientDO!=null?wlyyOutpatientDO.getIcd10Name():null);
        String extInfo = org.apache.commons.codec.binary.Base64.encodeBase64String(JSON.toJSONString(extInfoMap).getBytes("GBK"));
        String result = service.SOF_SignDataWithExtraInfo(idCardNo, inData, extInfo);
        logger.info("请求返参"+result);
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(result);
        if ("1000".equalsIgnoreCase(object.getString("code"))){
            com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(object.getString("data"));
            for (int i=0;i<array.size();i++){
                com.alibaba.fastjson.JSONObject jsonObject = array.getJSONObject(i);
                String signData = jsonObject.getString("signData");
                String signResult = jsonObject.getString("signResult");
                String certData = jsonObject.getString("certData");
                WlyyPrescriptionSignDO prescriptionSignDO = new WlyyPrescriptionSignDO();
                prescriptionSignDO.setCertData(certData);
                prescriptionSignDO.setPrescriptionId(prescriptionDO.getId());
                prescriptionSignDO.setSignData(signData);
                prescriptionSignDO.setSignResult(signResult);
                prescriptionSignDO.setCreateTime(new Date());
                prescriptionSignDO.setUpdateTime(new Date());
                prescriptionSignDO.setRelationCode(prescriptionEmrDO.getId());
                prescriptionSignDao.save(prescriptionSignDO);
            }
            prescriptionDO.setSignFlag(1);
        }
    }
    //删除处方
    public WlyyPrescriptionDO deletePrescription(String id){
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(id);
        if (null!=wlyyPrescriptionDO){
            wlyyPrescriptionDO.setCheckStatus(4);
            wlyyPrescriptionDO.setStatus(-1);
        }
        wlyyPrescriptionDO =  prescriptionDao.save(wlyyPrescriptionDO);
        return wlyyPrescriptionDO;
    }



    public void updateHisStatusByOutpatientId(String outpatientId){
        outpatientDao.updateHisStatusById(outpatientId,1);
    }
    //更新患者的诊断记录
    public Envelop updatePatientDiagnosis(String outpatiendId,String icd10,String icd10Name){
       WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outpatiendId);
        Envelop envelop = new Envelop();
       if (null!=wlyyOutpatientDO){
           if(StringUtils.isNotBlank(icd10)){
               wlyyOutpatientDO.setIcd10(icd10);
           }
           if(StringUtils.isNotBlank(icd10Name)){
               wlyyOutpatientDO.setIcd10Name(icd10Name);
           }
           outpatientDao.save(wlyyOutpatientDO);
           envelop.setMessage("添加成功");
           envelop.setStatus(200);
       }else {
           envelop.setMessage("无该患者门诊记录");
           envelop.setStatus(-1);
       }
       return envelop;
    }
    //应声开具处方管理
    public MixEnvelop prescriptionManage(String keyWord,String doctorId,String startTime,String endTime,String checkStatus,String status,Integer page,Integer pageSize){
        String sql = " select p.create_time as \"createTime\"," +
                " p.patient_name as \"patientName\"," +
                " o.idcard as \"idcard\"," +
                " o.card_no as \"cardNo\"," +
                " p.check_status as \"checkStatus\"," +
                " p.id as \"id\"," +
                " p.status as \"status\"," +
                " p.check_reason as \"checkReason\" " +
                " from wlyy_prescription p left join wlyy_outpatient o on p.outpatient_id  = o.id" +
                " where  1=1 ";
        if (StringUtils.isNotBlank(keyWord)){
            sql+=" and (p.patient_name like '%"+keyWord+"%' or p.idcard = '"+keyWord+"'" +
                    " or o.card_no = '"+keyWord+"')";
        }
        if(StringUtils.isNotBlank(checkStatus)){
            sql+=" and p.check_status ="+checkStatus;
        }else {
            sql+=" and p.check_status != 4";
        }
        if(StringUtils.isNotBlank(status)){
            if ("0".equalsIgnoreCase(status)){
                sql+=" and p.status = 20";
            }else if ("-4".equalsIgnoreCase(status)){
                sql+=" and p.status = -4";
            } else {
                sql+=" and p.status > 20";
            }

        }
        if(StringUtils.isNotBlank(doctorId)){
            sql+=" and p.doctor = '"+doctorId+"'";
        }
        if(StringUtils.isNotBlank(startTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and p.create_time > '" + startTime + " 00:00:00'";
                }else {
                    sql+=" and p.create_time > to_date('" + startTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and p.create_time > '" + startTime + " 00:00:00' ";
            }
        }
        if(StringUtils.isNotBlank(endTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+="  and p.create_time<'" + endTime + " 23:59:59'";
                }else {
                    sql+=" and p.create_time< to_date('" + endTime + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
                }
            }else{
                sql+="  and p.create_time<'" + endTime + " 23:59:59'";
            }
        }
        sql+=" order by p.create_time desc";
        String sqlcount = "SELECT COUNT(1) AS \"total\" FROM ("+sql+") q";
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlcount);
        if(total!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        List<Map<String,Object>> resultList = hibenateUtils.createSQLQuery(sql,page,pageSize);
        for (Map<String,Object> map:resultList){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("createTime",null==map.get("createTime")?"":DateUtil.dateToStrLong(DateUtil.strToDateLong(map.get("createTime").toString())));
            String prescriptionId = map.get("id").toString();
            //获取处方信息
            List<WlyyPrescriptionDO> prescriptionDOs = null;
            prescriptionDOs = prescriptionDao.findById(prescriptionId);
            List<WlyyPrescriptionVO> prescriptionVOs = new ArrayList<>();
            List<BusinessOrderDO> businessOrders = new ArrayList<>();
            if (prescriptionDOs != null && prescriptionDOs.size() > 0) {
                convertToModels(prescriptionDOs, prescriptionVOs, WlyyPrescriptionVO.class);
                for (WlyyPrescriptionVO vo : prescriptionVOs) {
                    List<WlyyPrescriptionCheckDO> prescriptionCheckDO = prescriptionCheckDao.findByPrescriptionId(vo.getId());
                    //疾病信息
                    vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                    if(null!=prescriptionCheckDO&&prescriptionCheckDO.size()>0){
                        vo.setDispUser(prescriptionCheckDO.get(0).getOperate());
                        vo.setDispUserName(prescriptionCheckDO.get(0).getOperateName());
                    }

                    //药品信息
                    List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                    System.out.println("=====PrescriptionId======"+vo.getId());
                    convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(), 1), infoVOs, WlyyPrescriptionInfoVO.class);
                    vo.setInfoVOs(infoVOs);

                    //检查检验信息
                    List<WlyyInspectionVO> inspectionVOs = new ArrayList<>();
                    vo.setInspectionVOs(convertToModels(wlyyInspectionDao.findByPrescriptionId(vo.getId(), 1), inspectionVOs, WlyyInspectionVO.class));

                    //支付信息
                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(vo.getId());
                    if (null!=businessOrderDO){
                        businessOrders.add(businessOrderDO);
                    }
                }

            }
            map.put("prescriptions",prescriptionVOs);
        }
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setDetailModelList(resultList);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setTotalCount(count.intValue());
        return  mixEnvelop;
    }
    //作废处方
    public String disablePrescription(String prescriptionId) throws  Exception{
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (null!=prescriptionDO){
            String hisId = prescriptionDO.getHisId();
            if("xm_xzzx_wx".equalsIgnoreCase(wechatId)){
                List<WlyyPrescriptionDiagnosisDO> wlyyPrescriptionDiagnosisDOs = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionId,1);
                if (null!=wlyyPrescriptionDiagnosisDOs&&wlyyPrescriptionDiagnosisDOs.size()>0){
                    xzzxEntranceService.deleteCheckInputInfo(hisId,"0",prescriptionDO.getDoctor(),prescriptionDO.getPatientCode(),wlyyPrescriptionDiagnosisDOs);
                    if (StringUtils.isNotBlank(prescriptionDO.getRealOrder())){
                        xzzxEntranceService.deletePrescriptionToEntrance(prescriptionDO.getRealOrder());
                    }
                }
            }
            if("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                /*prescriptionDao.updateCheckStatus(prescriptionId,2,reason,20);*/
                logger.info("作废处方开始" + prescriptionDO.getCheckStatus());
                WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
                WlyyOutpatientDO outpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
                DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
                List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId, 1);
                List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
                List<WlyyPrescriptionDiagnosisDO> prescriptionDiagnosisDOS = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionId,1);
                List<WlyyPrescriptionExpressageDO> expressageDOS = prescriptionExpressageDao.findByOutpatientId(outpatientDO.getId());
                com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
                for (WlyyPrescriptionInfoDO info : infoDOS) {
                    //设置his药品查询条件
                    setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, info, outpatientDO.getIcd10());
                }
                for (WlyyInspectionDO ins : inspectionDOS) {
                    //设置his药品查询条件
                    setInspectionParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, ins, outpatientDO.getIcd10());
                }
                if (expressageDOS!=null&&expressageDOS.size()!=0){
                    WlyyPrescriptionExpressageDO prescriptionExpressageDO = expressageDOS.get(0);
                    if (prescriptionExpressageDO!=null&&prescriptionExpressageDO.getOneselfPickupFlg()==0){
                        for (int i=0;i<jsonData.size();i++){
                            com.alibaba.fastjson.JSONObject object = jsonData.getJSONObject(i);
                            object.put("selfDelivered",0);
                        }
                    }else if (prescriptionExpressageDO!=null&&prescriptionExpressageDO.getOneselfPickupFlg()==1){
                        for (int i=0;i<jsonData.size();i++){
                            com.alibaba.fastjson.JSONObject object = jsonData.getJSONObject(i);
                            object.put("selfDelivered",1);
                        }
                    }
                }
                try {
                    net.sf.json.JSONObject jsonObject = entranceService.BS10112(jsonData.toJSONString(), demoFlag);
                    wlyyHttpLogDO.setResponse(jsonObject.toString());
                }catch (Exception e){
                    e.printStackTrace();
                    return "作废失败";
                }
                wlyyHttpLogDO.setRequest(jsonData.toJSONString());
                wlyyHttpLogDO.setName("作废处方");
                wlyyHttpLogDO.setCreateTime(new Date());
                wlyyHttpLogDO.setCode(outpatientDO.getId());
                wlyyHttpLogDao.save(wlyyHttpLogDO);
            }

            prescriptionDO.setStatus(-4);
            prescriptionDO.setDisableTime(new Date());
            prescriptionDO.setCheckStatus(5);
            prescriptionDO.setCheckReason("已作废");
            prescriptionDao.save(prescriptionDO);
            return "已作废";
        }else {
            return "作废失败";
        }
    }


    /**
     * 腾讯视频生成签名
     * @param userId
     * @return
     */
    public String appletSign(String userId){
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("SDKAPPID");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("SECRETKEY");
        if (sysDictDO!=null&&hospitalSysDictDO!=null){
            return GenerateUserSig.GenTLSSignature(Long.parseLong(sysDictDO.getDictValue()),userId,604800,null,hospitalSysDictDO.getDictValue());
        }
        return null;
    }


    public String yxToken(String userId,String channelName){
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("YXAPPKEY");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("YXAPPSECRET");
        if (sysDictDO==null){
            return  "找不到对应的key";
        }
        String appKey = sysDictDO.getDictValue();
        String appSecret = hospitalSysDictDO.getDictValue();
        String nonce =  randomInt(10);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        String url = "https://api.netease.im/nimserver/user/getToken.action";
        Map<String,Object> httpPost = new HashedMap();
        // 设置请求的header
        httpPost.put("AppKey", appKey);
        httpPost.put("Nonce", nonce);
        httpPost.put("CurTime", curTime);
        httpPost.put("CheckSum", checkSum);
        httpPost.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("uid", userId));
        nvps.add(new BasicNameValuePair("channelName",channelName));
        String response = httpClientUtil.headerPost(url,nvps,"UTF-8",httpPost);
        logger.info("返回日志"+response);
        if(StringUtils.isNoneBlank(response)){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
            if (jsonObject.getString("code").equalsIgnoreCase("200")){
                return jsonObject.getString("token");
            }
        }
        return null;
    }
    public String yxToken2(String userId,String channelName){
        YxTokenMappingDO yxTokenMappingDO = yxTokenMappingDao.findMappingByAccid(userId);
        if (yxTokenMappingDO!=null){
            return yxTokenMappingDO.getToken();
        }
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("YXAPPKEY");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("YXAPPSECRET");
        if (sysDictDO==null){
            return  "找不到对应的key";
        }
        String appKey = sysDictDO.getDictValue();
        String appSecret = hospitalSysDictDO.getDictValue();
        String nonce =  randomInt(10);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        String url = "https://api.netease.im/nimserver/user/create.action";
        Map<String,Object> httpPost = new HashedMap();
        // 设置请求的header
        httpPost.put("AppKey", appKey);
        httpPost.put("Nonce", nonce);
        httpPost.put("CurTime", curTime);
        httpPost.put("CheckSum", checkSum);
        httpPost.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", userId));
        YxTokenMappingDO yxTokenMappingDO1 = new YxTokenMappingDO();
        if (StringUtils.isNoneBlank(channelName)){
            nvps.add(new BasicNameValuePair("name",channelName));
            yxTokenMappingDO1.setName(channelName);
        }
        String response = httpClientUtil.headerPost(url,nvps,"UTF-8",httpPost);
        logger.info("返回日志"+response);
        if(StringUtils.isNoneBlank(response)){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
            if (jsonObject.getString("code").equalsIgnoreCase("200")){
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.getString("info"));
                if (StringUtils.isNoneBlank(jsonObject1.getString("token"))){
                    yxTokenMappingDO1.setAccid(userId);
                    yxTokenMappingDO1.setToken(jsonObject1.getString("token"));
                    yxTokenMappingDao.save(yxTokenMappingDO1);
                }
                return jsonObject1.getString("token");
            }else if (jsonObject.getString("code").equalsIgnoreCase("414")&&jsonObject.getString("desc").contains("already")){
                return  refreshToken(userId);
            }
        }
        return null;
    }

    /**
     * 重置云信token
     * @param userId
     * @return
     */
    public String refreshToken(String userId){
        YxTokenMappingDO yxTokenMappingDO = yxTokenMappingDao.findMappingByAccid(userId);
        if (yxTokenMappingDO!=null){
            return yxTokenMappingDO.getToken();
        }
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("YXAPPKEY");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("YXAPPSECRET");
        if (sysDictDO==null){
            return  "找不到对应的key";
        }
        String appKey = sysDictDO.getDictValue();
        String appSecret = hospitalSysDictDO.getDictValue();
        String nonce =  randomInt(10);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        String url = "https://api.netease.im/nimserver/user/refreshToken.action";
        Map<String,Object> httpPost = new HashedMap();
        // 设置请求的header
        httpPost.put("AppKey", appKey);
        httpPost.put("Nonce", nonce);
        httpPost.put("CurTime", curTime);
        httpPost.put("CheckSum", checkSum);
        httpPost.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", userId));
        YxTokenMappingDO yxTokenMappingDO1 = new YxTokenMappingDO();
        String response = httpClientUtil.headerPost(url,nvps,"UTF-8",httpPost);
        logger.info("重置云信"+response);
        if(StringUtils.isNoneBlank(response)){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
            if (jsonObject.getString("code").equalsIgnoreCase("200")){
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.getString("info"));
                if (StringUtils.isNoneBlank(jsonObject1.getString("token"))){
                    yxTokenMappingDO1.setAccid(userId);
                    yxTokenMappingDO1.setToken(jsonObject1.getString("token"));
                    yxTokenMappingDao.save(yxTokenMappingDO1);
                }
                return jsonObject1.getString("token");
            }
        }
        return null;
    }


    public static void main(String[] args) {
        String ss = DateUtil.getStringDateShort();
        System.out.println(ss);
    }
    public com.alibaba.fastjson.JSONObject selectHospitalInfo(String doctorId,String orgCode){
        /**
         * 1、今日待就诊：今日当前家庭医生在当前医院的未完成的协同门诊书

         2、下一次就诊时间：当前家庭医生在当前医院下一次未接诊的就诊时间。

         3、服务评分：当前医院的综合服务评分

         4、在线医生：当前医院在班的专科医生数

         5、可预约医生：当前医院有开通协同门诊业务的医生数（包含当前在线）

         6、累计就诊：当前医院累计协同门诊的已接诊数量
         */
        String nowDate = DateUtil.getStringDateShort();
        Date startTime  = DateUtil.strToDateLong(nowDate+" 00:00:00");
        Date endTime  = DateUtil.strToDateLong(nowDate+" 23:59:59");

        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        // 1、今日待就诊：今日当前家庭医生在当前医院的未完成的协同门诊书
        List<WlyyOutpatientDO> outpatientDOS =  outpatientDao.findByGeneralDoctorAndStatusAndDate(doctorId,startTime,endTime,"0,1,2");
        jsonObject.put("NowWaitTotal",outpatientDOS.size());
        //2、下一次就诊时间：当前家庭医生在当前医院下一次未接诊的就诊时间。
        List<WlyyOutpatientDO> outpatientDOList =  outpatientDao.findByGeneralDoctorAndStatus(doctorId,"0");
        if (outpatientDOList!=null&&outpatientDOList.size()!=0){
            jsonObject.put("nextTime",DateUtil.dateToStrLong(outpatientDOList.get(0).getRegisterDate()));
        }else {
            jsonObject.put("nextTime",null);
        }
        //3、服务评分：当前医院的综合服务评分
        //在线医生：当前医院在班的专科医生数
        Map<String, Object> params = new HashedMap();
        String timeCondition="";
        if("xm_ykyy_wx".equals(wechatId)){
            if (flag){
                timeCondition+="AND t.start_time >= '"+nowDate+" 00:00:00'";
                timeCondition+="AND t.start_time <= '"+nowDate+" 23:59:59'";
            }else {
                timeCondition+="AND t.start_time >= to_date('"+nowDate+" 00:00:00','yyyy-mm-dd hh24:mi:ss')";
                timeCondition+="AND t.start_time <= to_date('"+nowDate+" 23:59:59','yyyy-mm-dd hh24:mi:ss')";
            }
        }else{
            timeCondition+="AND t.start_time >= '"+nowDate+" 00:00:00'";
            timeCondition+="AND t.start_time <= '"+nowDate+" 23:59:59'";
        }
        String sql ="SELECT d.id as \"id\",d.name as \"name\" FROM base_doctor d WHERE (EXISTS (SELECT 1 FROM wlyy_doctor_work_time t WHERE t.doctor = d.id "+timeCondition+"  ) OR  d.consult_status = '1')";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params);
        jsonObject.put("onlineDoctors",list.size());

        //可预约医生：当前医院有开通协同门诊业务的医生数（包含当前在线）
        sql += " AND outpatient_type IN('xt') ";
        List<Map<String, Object>> specialist = hibenateUtils.createSQLQuery(sql, params);
        jsonObject.put("xtOnlineDoctors",specialist.size());
        //累计就诊：当前医院累计协同门诊的已接诊数量
        List<WlyyOutpatientDO> wlyyOutpatientDOList = outpatientDao.findOutpatientListByOutpatientType("xt",new Date());
        jsonObject.put("xtOupatients",wlyyOutpatientDOList.size());
        BaseOrgDO orgDO = baseOrgDao.findByCode(orgCode);
        jsonObject.put("orgName",orgDO.getName());
        jsonObject.put("orgPhoto",orgDO.getPhoto());
        jsonObject.put("description",orgDO.getIntro());
        return jsonObject;
    }


    /**
     *
     * @param price
     * @param type
     * @param flag
     * @return
     */
    public String synYktZxPrice(String idcard,Integer price,Integer type,String flag) throws Exception {
        if (StringUtils.isNoneBlank(flag)){
            List<BaseDoctorDO> doctorDOList = baseDoctorDao.findByDel();
            for (BaseDoctorDO doctorDO:doctorDOList){
                String yktDoctor = null;
                DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctorDO.getId());
                if (doctorMappingDO!=null){
                    String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(doctorResponse);
                    if (jsonObject.getInteger("code")==200){
                        com.alibaba.fastjson.JSONArray array1 = jsonObject.getJSONArray("data");
                        if (array1!=null&&array1.size()!=0){
                            yktDoctor=array1.getJSONObject(0).getString("DOCTORUSERID");
                        }
                    }
                    if (StringUtils.isNoneBlank(yktDoctor)){
                        doctorDO.setYktDoctorId(yktDoctor);
                        //图文
                        String twResponse =ykyyService.GetVasPriceByTypeForJkzl(yktDoctor,1);
                        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(twResponse);
                        if (object.getInteger("code")==10000){
                            if (object.containsKey("value")){
                                com.alibaba.fastjson.JSONObject object1 = object.getJSONObject("value");
                                Integer twPrcie=object1.getInteger("price");
                                Double twPrcie1 = Double.parseDouble(twPrcie+"");
                                WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByReqFee(twPrcie1);
                                if (chargeDictDO==null){
                                    chargeDictDO = new WlyyChargeDictDO();
                                    chargeDictDO.setCreateTime(new Date());
                                    chargeDictDO.setReqFee(twPrcie1);
                                    chargeDictDO.setChargeType(twPrcie+"");
                                    chargeDictDO.setChargeName(twPrcie+"");
                                    chargeDictDO.setIsDel("1");
                                    chargeDictDO = wlyyChargeDictDao.save(chargeDictDO);
                                }
                                doctorDO.setTwzxChargeType(chargeDictDO.getChargeType());
                                if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())){
                                    if (!doctorDO.getOutpatientType().contains("zj")){
                                        doctorDO.setOutpatientType(doctorDO.getOutpatientType()+",zj");
                                    }
                                }else {
                                    doctorDO.setOutpatientType("zj");
                                }

                            }else {
                                if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())){
                                    if (doctorDO.getOutpatientType().contains("zj")){
                                        doctorDO.getOutpatientType().replace(",zj","");
                                    }
                                }else {
                                    doctorDO.setOutpatientType("zj");
                                }

                            }
                        }
                        //视频
                        String spResponse =ykyyService.GetVasPriceByTypeForJkzl(yktDoctor,3);
                        com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(spResponse);
                        if (jsonObject1.getInteger("code")==10000){
                            if (jsonObject1.containsKey("value")){
                                com.alibaba.fastjson.JSONObject object1 = jsonObject1.getJSONObject("value");
                                Integer spPrcie=object1.getInteger("price");
                                Double spPrcie1 = Double.parseDouble(spPrcie+"");
                                WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByReqFee(spPrcie1);
                                if (chargeDictDO==null){
                                    chargeDictDO = new WlyyChargeDictDO();
                                    chargeDictDO.setCreateTime(new Date());
                                    chargeDictDO.setReqFee(spPrcie1);
                                    chargeDictDO.setChargeType(spPrcie+"");
                                    chargeDictDO.setChargeName(spPrcie+"");
                                    chargeDictDO.setIsDel("1");
                                    chargeDictDO = wlyyChargeDictDao.save(chargeDictDO);
                                }
                                doctorDO.setSpzxChargeType(chargeDictDO.getChargeType());
                                if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())){
                                    if (!doctorDO.getOutpatientType().contains("zxsp")){
                                        doctorDO.setOutpatientType(doctorDO.getOutpatientType()+",zxsp");
                                    }
                                }else {
                                    doctorDO.setOutpatientType("zxsp");
                                }
                            }else {
                                if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())){
                                    if (doctorDO.getOutpatientType().contains("zxsp")){
                                        doctorDO.getOutpatientType().replace(",zxsp","");
                                    }
                                }else{
                                    doctorDO.setOutpatientType("zxsp");
                                }

                            }
                        }
                    }
                    baseDoctorDao.save(doctorDO);
                }
            }
            return "ok";
        }else {
            BaseDoctorDO doctorDO = baseDoctorDao.findByIdcardAndId(idcard);
            if (price==-1){
                if (doctorDO!=null){
                    if (type==1){
                        if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())) {
                            if (doctorDO.getOutpatientType().contains("zj")) {
                                doctorDO.getOutpatientType().replace(",zj", "");
                            }
                        }else {
                            doctorDO.setOutpatientType("zj");
                        }
                    }else if (type==3){
                        if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())) {
                            if (doctorDO.getOutpatientType().contains("zj")) {
                                doctorDO.getOutpatientType().replace(",zj", "");
                            }
                        }else {
                            doctorDO.setOutpatientType("zj");
                        }
                    }
                }else {
                    if (doctorDO==null){
                        return "找不到医生信息！";
                    }
                }

            }else {
                if (doctorDO!=null){
                    if (!StringUtils.isNoneBlank(doctorDO.getYktDoctorId())){
                        String yktDoctor = null;
                        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctorDO.getId());
                        if (doctorMappingDO!=null){
                            String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
                            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(doctorResponse);
                            if (jsonObject.getInteger("code")==200){
                                com.alibaba.fastjson.JSONArray array1 = jsonObject.getJSONArray("data");
                                if (array1!=null&&array1.size()!=0){
                                    yktDoctor=array1.getJSONObject(0).getString("DOCTORUSERID");
                                }
                            }
                            doctorDO.setYktDoctorId(yktDoctor);
                        }
                    }
                    if (type!=null&&type==1) {
                        Double price1 = Double.parseDouble(price + "");
                        WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByReqFee(price1);
                        if (chargeDictDO == null) {
                            chargeDictDO = new WlyyChargeDictDO();
                            chargeDictDO.setCreateTime(new Date());
                            chargeDictDO.setReqFee(price1);
                            chargeDictDO.setChargeType(price + "");
                            chargeDictDO.setChargeName(price + "");
                            chargeDictDO.setIsDel("1");
                            chargeDictDO = wlyyChargeDictDao.save(chargeDictDO);
                        }
                        doctorDO.setTwzxChargeType(chargeDictDO.getChargeType());
                        if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())) {
                            if (!doctorDO.getOutpatientType().contains("zj")) {
                                doctorDO.setOutpatientType(doctorDO.getOutpatientType() + ",zj");
                            }
                        }else {
                            doctorDO.setOutpatientType("zj");
                        }
                    }else if (type!=null&&type==3) {
                        Double price1 = Double.parseDouble(price + "");
                        WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByReqFee(price1);
                        if (chargeDictDO == null) {
                            chargeDictDO = new WlyyChargeDictDO();
                            chargeDictDO.setCreateTime(new Date());
                            chargeDictDO.setReqFee(price1);
                            chargeDictDO.setChargeType(price + "");
                            chargeDictDO.setChargeName(price + "");
                            chargeDictDO.setIsDel("1");
                            chargeDictDO = wlyyChargeDictDao.save(chargeDictDO);
                        }
                        doctorDO.setSpzxChargeType(chargeDictDO.getChargeType());
                        if (StringUtils.isNoneBlank(doctorDO.getOutpatientType())) {
                            if (!doctorDO.getOutpatientType().contains("zxsp")) {
                                doctorDO.setOutpatientType(doctorDO.getOutpatientType() + ",zxsp");
                            }
                        }else {
                            doctorDO.setOutpatientType("zxsp");
                        }
                    }
                    baseDoctorDao.save(doctorDO);
                    return "ok";
                }else {
                    return "找不到医生信息！";
                }
            }
            return "ok";
        }
    }
    public List<Map<String,Object>> findOutpatientAndPatient(String startTime,String endTime){
        String sql  = "SELECT\n" +
                "\tt.status as \"status\",\n" +
                "\tt.source as \"source\",\n" +
                "\tt.outpatient_type as \"outpatientType\",\n" +
                "\tt.create_time as \"createTime\",\n" +
                "\th.org_code as \"orgCode\",\n" +
                "\tb.idcard as \"idCard\" \n" +
                "FROM\n" +
                "\twlyy_outpatient t\n" +
                "\tLEFT JOIN base_patient b ON t.patient = b.id " +
                " left join base_doctor_hospital h on t.doctor = h.doctor_code where 1=1 ";
        if (StringUtils.isNoneBlank(startTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.create_time >= '" + startTime + " ' ";
                }else {
                    sql+=" and t.create_time >= to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time >= '" + startTime + "' ";
            }
        }
        if (StringUtils.isNoneBlank(endTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.create_time <= '" + endTime + "' ";
                }else {
                    sql+=" and t.create_time <= to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time <= '" + endTime + "'";
            }
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        for (Map<String,Object> map:list){
            if (map.get("createTime")!=null){
                map.put("createTime",DateUtil.dateToStrLong(DateUtil.strToDateLong(map.get("createTime").toString())));
            }
        }


        return list;
    }
    public com.alibaba.fastjson.JSONObject getWorkDoctorCount(String nowTime,String orgCode){
        String sql = "select count(*) as \"total\",t.doctor as \"doctor\" from wlyy_doctor_work_time t " +
                " left join base_doctor_hospital b on t.doctor = b.doctor_code where 1=1 ";
        if(StringUtils.isNoneBlank(nowTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.start_time >= '" + nowTime + " 00:00:00' and t.end_time <='"+nowTime+" 23:59:59' ";
                }else {
                    sql+=" and t.start_time >= to_date('" + nowTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') and t.end_time <=to_date('"+nowTime+" 23:59:59', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.start_time >= '" + nowTime + " 00:00:00' and t.end_time <='"+nowTime+" 23:59:59' ";
            }
        }
        if(StringUtils.isNoneBlank(orgCode)){
            sql+=" and b.org_code ='"+orgCode+"'";
        }
        sql+=" group by t.doctor";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        long count =0;
        if(list!=null){
            count = list.size();
        }
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("workDoctorCount",count);
        return  jsonObject;
    }
    public List<WlyyHospitalSysDictDO> findAllDict(){
        List<WlyyHospitalSysDictDO> wlyyHospitalSysDictDOS = wlyyHospitalSysDictDao.findAlldict();
        return  wlyyHospitalSysDictDOS;
    }
    public WlyyHospitalSysDictDO findDictById(String dictId){
        WlyyHospitalSysDictDO wlyyHospitalSysDictDOS = wlyyHospitalSysDictDao.findById(dictId);
        return  wlyyHospitalSysDictDOS;
    }
    public WlyyHospitalSysDictDO updateDictById(String dictId,String dictValue){
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById(dictId);
        if(wlyyHospitalSysDictDO!=null){
            if (StringUtils.isNoneBlank(dictValue)){
                wlyyHospitalSysDictDO.setDictValue(dictValue);
                wlyyHospitalSysDictDao.save(wlyyHospitalSysDictDO);
            }
        }
        return  wlyyHospitalSysDictDO;
    }
    public List<WlyyHospitalSysDictDO> findSysByDictCode(String dictCode){
        List<WlyyHospitalSysDictDO> isWork=sysDictDao.findByDictCode(dictCode);
        return isWork;
    }


    /**
     * 上门复诊
     *
     * @param outpatientJson
     * @param expressageJson
     * @return
     * @throws Exception
     */
    @Transactional
    public WlyyOutpatientDO appointmentRevisitOnDoor(String outpatientJson, String expressageJson, String registerJson, String chargeType) throws Exception {
        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        BaseDoctorDO doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());

        outpatientDO.setMjz("mz");
        outpatientDO.setStatus("3");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setIdcard(patientDO.getIdcard());
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setOutpatientType("4");//4为上门复诊
        outpatientDO.setType("1");//1为图文复诊（上门默认图文复诊）

        if (outpatientDO.getRegisterDate() == null) {
            outpatientDO.setRegisterDate(new Date());
        }
        outpatientDO.setPayStatus(1);
        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        if (StringUtils.isNoneBlank(expressageJson)){
            WlyyPrescriptionExpressageDO expressageDO = new WlyyPrescriptionExpressageDO();
            expressageDO = objectMapper.readValue(expressageJson, WlyyPrescriptionExpressageDO.class);
            System.out.println("写入自取信息");
            String drugStoreCode = expressageDO.getHospitalCode();
            BaseDrugStoreDO baseDrugStoreDO = baseDrugStoreDao.findDrugByid(drugStoreCode);
            if (null!=baseDrugStoreDO){
                expressageDO.setCityCode(baseDrugStoreDO.getCityCode());
                expressageDO.setCityName(baseDrugStoreDO.getCityName());
                expressageDO.setProvinceCode(baseDrugStoreDO.getProvinceCode());
                expressageDO.setProvinceName(baseDrugStoreDO.getProvinceName());
                expressageDO.setTownCode(baseDrugStoreDO.getTownCode());
                expressageDO.setTownName(baseDrugStoreDO.getTownName());
                expressageDO.setHospitalCode(baseDrugStoreDO.getDrugStoreCode());
                expressageDO.setHospitalName(baseDrugStoreDO.getHospitalName());
                expressageDO.setHospitalAddress(baseDrugStoreDO.getAddress());
            }
            expressageDO.setDel(1);
            expressageDO.setCreateTime(new Date());
            expressageDO.setOutpatientId(outpatient.getId());
            prescriptionExpressageDao.save(expressageDO);
        }
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("WX_MONEY");
        Double price = 0.0;
        String chargeType1 = null;
        if (doctorDO!=null){
            if (outpatient.getOutpatientType().equalsIgnoreCase("1")){
                if(outpatientDO.getType().equalsIgnoreCase("1")){
                    chargeType1 = doctorDO.getTwfzChargeType();
                }else if(outpatientDO.getType().equalsIgnoreCase("2")){
                    chargeType1 = doctorDO.getSpfzChargeType();
                }
            }else if (outpatient.getOutpatientType().equalsIgnoreCase("3")){
                if(outpatientDO.getType().equalsIgnoreCase("1")){
                    chargeType1 = doctorDO.getTwzxChargeType();
                }else if(outpatientDO.getType().equalsIgnoreCase("2")){
                    chargeType1 = doctorDO.getSpzxChargeType();
                }
            }else if (outpatient.getOutpatientType().equalsIgnoreCase("2")){
                chargeType1 = doctorDO.getXtfzChargeType();
            }else if (outpatient.getOutpatientType().equalsIgnoreCase("4")){
                chargeType1 = "on_door_type";
            }
            if(doctorDO!=null){
                if (StringUtils.isNoneBlank(chargeType1)){
                    WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByChargeType(chargeType1);
                    if (chargeDictDO!=null){
                        price = chargeDictDO.getReqFee();
                    }else {
                        price = Double.parseDouble(hospitalSysDictDO.getDictValue());
                    }
                }
            }else {
                price = Double.parseDouble(hospitalSysDictDO.getDictValue());
            }
        }else {
            if (StringUtils.isNoneBlank(chargeType)){
                WlyyChargeDictDO chargeDictDO = wlyyChargeDictDao.findByChargeType(chargeType);
                if (chargeDictDO!=null){
                    price = chargeDictDO.getReqFee();
                }else {
                    price = Double.parseDouble(hospitalSysDictDO.getDictValue());
                }
            }
        }
        outpatient.setFee(price);
        outpatientDao.save(outpatient);
        /*if (doctorDO != null && StringUtils.isNoneBlank(doctorDO.getFee())) {
            price = Double.parseDouble(doctorDO.getFee());
        }else {
            price = Double.parseDouble(hospitalSysDictDO.getDictValue());
        }*/

        /*if (price == 0.0) {

        } else {
            outpatientDO.setPayStatus(0);
        }*/

        if (outpatient.getOutpatientType().equalsIgnoreCase("1")){
            if (outpatient.getType().equalsIgnoreCase("1")){
                businessOrderService.recharge(outpatient.getId(), "图文复诊-诊查费", "2", "图文复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
            }else if (outpatient.getType().equalsIgnoreCase("2")){
                businessOrderService.recharge(outpatient.getId(), "视频复诊-诊查费", "3", "视频复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
            }
        }else if (outpatient.getOutpatientType().equalsIgnoreCase("2")){
            businessOrderService.recharge(outpatient.getId(), "协同复诊-诊查费", "5", "协同复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }else if ("3".equalsIgnoreCase(outpatient.getOutpatientType())){
            BusinessOrderDO businessOrderDO = businessOrderService.recharge(outpatient.getId(), "专家咨询费", "1", "专家咨询费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }


        WlyyPatientRegisterTimeDO registerTimeDO = null;
        WlyyPatientRegisterTimeDO wlyyPatientRegisterTimeDO =new WlyyPatientRegisterTimeDO();
        try {
            //如果是视频预约咨询
            if (StringUtils.isNotBlank(registerJson)) {
                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                wlyyPatientRegisterTimeDO = patientRegisterTimeDao.save(registerTimeDO);
            }
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约，请选择其他号源");
        }
        if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
            logger.info("心脏中心同步患者开始");
            xzzxEntranceService.updatePatientMapping(outpatient.getConsumer(),outpatient.getCardNo());
            logger.info("同步患者id成功");
        }


        //3.创建候诊室
        //createRoom(outpatient, chargeType);
        String content = "向您发起了图文复诊，点击查看";

        return outpatient;
    }
    public String savePrescriptionToDoorService(String orderId,String prescriptionId){
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("doorServiceUrl");
        String url = "";
        if (wlyyHospitalSysDictDO!=null){
            url = wlyyHospitalSysDictDO.getDictValue();
        }
        logger.info("url:"+url);
        String res = "";
        Map map = new HashMap();
        map.put("orderId",orderId);
        map.put("prescriptionCode",prescriptionId);
        logger.info("入参："+map);
        try {
            res = httpClientUtil.httpPost(url,map);
            logger.info("调用保存上门开方信息接口返回结果=>"+res);
            if (StringUtils.isNoneBlank(res)){
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res);
                if ("200".equalsIgnoreCase(jsonObject.getString("status"))){
                    return jsonObject.getString("msg");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "接口调用失败";
    }
    /**
     * 根据doctorid获取待服务数量
     *
     * @return
     */
    public Long waitUpdoorCount(String doctor) {
       WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("waitUpdoorCount");
       String url = "";
       if (wlyyHospitalSysDictDO!=null){
           url = wlyyHospitalSysDictDO.getDictValue();
       }
       logger.info("waitUpdoorCountUrl:"+url);
       if (StringUtils.isNoneBlank(doctor)){
           url+="?doctor="+doctor;
       }
        Long doorServiceCount = 0L;
       try {
           String res = httpClientUtil.get(url,"UTF-8");
           logger.info("waitUpdoorCountres:"+res);
           if (StringUtils.isNoneBlank(res)){
               com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res);
               if (jsonObject!=null&&"200".equalsIgnoreCase(jsonObject.getString("status"))){
                   String dataCount = jsonObject.getString("data");
                   doorServiceCount = Long.parseLong(dataCount);
               }
           }
       }catch (Exception e){
           return doorServiceCount;
       }
       return doorServiceCount;
    }
    public MixEnvelop findJobCategory(){
        String sqlPid = "select id as \"id\",name as \"name\",code as \"code\",pid as \"pid\" from base_job_category  where pid = 0 and del = 1";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sqlPid);
        if (list.size()>0){
            for (Map<String,Object> map:list){
                String child = "select id as \"id\",name as \"name\",code as \"code\",pid as \"pid\" from base_job_category  where del = 1";
                String pid = map.get("id").toString();
                child+=" and pid = "+pid;
                List<Map<String,Object>> childList = hibenateUtils.createSQLQuery(child);
                map.put("childList",childList);
            }
        }
        MixEnvelop envelop = new MixEnvelop();
        envelop.setDetailModelList(list);
        return  envelop;
    }
    public Map<String,Object> findRandomDoctor(){
        String sql = "select t.id as \"id\"," +
                "t.doctor_mapping_code as \"doctorMappingCode\"," +
                "t.doctor_code as \"doctorCode\"," +
                "t.dept_code as \"deptCode\"," +
                "t.start_time as \"startTime\"," +
                "t.end_time as \"endTime\"," +
                "t.doctor_name as \"doctorName\"," +
                "t.dept_name  as \"deptName\" from base_doctor_time_mapping t where 1=1 ";
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            sql+=" order by dbms_random.value";
        }else {
            sql+=" ORDER BY RAND() ";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        if (list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }

    public Map saveNatAppointment(String chargeAmount,String inspectionName,String mediaCard,String patientId,String name,String cardNo,String cardType,String mobile,
                                   String firstJobCode,String firstJobName,String secondJobCode,String secondJobName,String natTime,String address,String provinceName,String cityName,String townName,String streetName,String pm,String pushFlag,String cardNoType,String consumer,
                                  String checkPart,String chargeFlag,String chargeCode,String icdCode,String preNo,String idnoType) throws Exception {
        Map returnMap = new HashMap();
        Integer winNo = 6;
        if (checkPart==null||checkPart==""){
            List<WlyyHospitalSysDictDO> natConfigList = wlyyHospitalSysDictDao.findByDictName("natConfigList");
            checkPart = "鼻/咽拭子";
            chargeFlag = "2";
            chargeCode = "361322";
            icdCode = "Z00.000";
            for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:natConfigList){
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"checkPart".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    checkPart = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"chargeFlag".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    chargeFlag = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"chargeCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    chargeCode = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"icdCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    icdCode = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"winNo".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    winNo = Integer.parseInt(wlyyHospitalSysDictDO.getDictValue());
                }
            }
        }
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
            net.sf.json.JSONObject jsondate = new JSONObject();
            jsondate.put("checkPart",checkPart);
            jsondate.put("cardNo",mediaCard);
            jsondate.put("chargeFlag",chargeFlag);
            jsondate.put("chargeCode",chargeCode);
            jsondate.put("icdCode",icdCode);
            jsondate.put("socialNo",cardNo);
            jsondate.put("tellPhone",mobile);
            jsondate.put("address1",provinceName);
            jsondate.put("address2",cityName);
            jsondate.put("address3",townName);
            jsondate.put("address4",streetName);
            jsondate.put("address5",address);
            jsondate.put("area",townName);
            jsondate.put("winNo",winNo);
            jsondate.put("targetChild",secondJobName);
            jsondate.put("target",firstJobName);
            jsondate.put("quantity",1);
            jsondate.put("idnoType",idnoType);
            Map<String,Object> map = findRandomDoctor();
            net.sf.json.JSONObject rs = new JSONObject();
            if (map!=null){
                //先进行核算检测预约
                String result = entranceService.BS10144("3150000","0001",natTime,mediaCard,name,cardNo,mobile,pm,demoFlag);
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(result);
                logger.info("核酸检测预约结束"+result);
                Boolean flag = false;
                if (object!=null){
                    com.alibaba.fastjson.JSONObject jsonObject = object.getJSONObject("MsgInfo");
                    String Msg = jsonObject.getString("Msg");
                    if (Msg.contains("Error")){
                            returnMap.put("msg",Msg);
                            returnMap.put("status","-1");
                            return  returnMap;
                    }else {
                        flag = true;
                    }
                }
                if (flag){
                    BaseNatAppointmentDO baseNatAppointmentDO= new BaseNatAppointmentDO();
                    baseNatAppointmentDO.setChargeAmount(chargeAmount);
                    baseNatAppointmentDO.setMedicare(mediaCard);
                    baseNatAppointmentDO.setName(name);
                    baseNatAppointmentDO.setCardNo(cardNo);
                    baseNatAppointmentDO.setCardType(cardType);
                    baseNatAppointmentDO.setAddress(address);
                    baseNatAppointmentDO.setAppointmentTime(DateUtil.strToDateLong(natTime));
                    baseNatAppointmentDO.setCityName(cityName);
                    baseNatAppointmentDO.setFirstJobCode(firstJobCode);
                    baseNatAppointmentDO.setFirstJobName(firstJobName);
                    baseNatAppointmentDO.setSecondJobCode(secondJobCode);
                    baseNatAppointmentDO.setSecondJobName(secondJobName);
                    baseNatAppointmentDO.setProvinceName(provinceName);
                    baseNatAppointmentDO.setTownName(townName);
                    baseNatAppointmentDO.setStreetName(streetName);
                    baseNatAppointmentDO.setPatientId(patientId);
                    baseNatAppointmentDO.setIsSuccess("0");
                    baseNatAppointmentDO.setCardNoType(cardNoType);
                    baseNatAppointmentDO.setPayStatus("0");
                    baseNatAppointmentDO.setCreateTime(new Date());
                    baseNatAppointmentDO.setMobile(mobile);
                    baseNatAppointmentDO.setInspectionCode(chargeCode);
                    baseNatAppointmentDO.setInspectionName(inspectionName);
                    baseNatAppointmentDO.setIcdCode(icdCode);
                    baseNatAppointmentDO.setChargeCode(chargeCode);
                    baseNatAppointmentDO.setWinNo(String.valueOf(winNo));
                    baseNatAppointmentDO.setIdnoType(idnoType);
                    baseNatAppointmentDO.setDept("3150000");
                    baseNatAppointmentDO.setDeptName("感染疾病科");
                    baseNatAppointmentDO.setAmpm(pm);
                    baseNatAppointmentDO= baseNatAppointmentDao.save(baseNatAppointmentDO);
                    try {
                        rs = entranceService.BS10111(mediaCard, map.get("doctorMappingCode").toString(), map.get("deptCode").toString(), "31", "6", demoFlag);
                        net.sf.json.JSONObject res = rs.getJSONObject("resquest");
                        logger.info("挂号结果 res: " + res.toString());
                        String rsCode = res.getString("@RESULT");
                        if ("0".equals(rsCode)) {
                            //存储挂号号
                            // {"resquest":{"@RESULT":"0","@MSG":"完成","@serial_no":"47770476","@times":"28"}}
                            String serialNo = (String) res.get("@serial_no");
                            String conNo = (String) res.get("@times");
                            String xtgzh = (String) res.get("@xtgzh");
                            String realOrder = (String) res.get("@real_order");
                            logger.info("挂号流水 @serial_no: " + serialNo + " @times: " + conNo);
                            jsondate.put("serialNo",serialNo);
                            jsondate.put("dept",map.get("deptCode").toString());
                            jsondate.put("doctor",map.get("doctorMappingCode").toString());
                            baseNatAppointmentDO.setRegisterNo(serialNo);
                            //保存日志
                            WlyyHttpLogDO log = new WlyyHttpLogDO();
                            log.setCode("registerOutPatient");
                            log.setName("挂号");
                            log.setPatient(patientId);
                            log.setDoctor(map.get("doctorCode").toString());
                            log.setResponse(rs.toString());
                            log.setStatus(rsCode);
                            log.setCreateTime(new Date());
                            wlyyHttpLogDao.save(log);

                        } else if ("-2".equals(rsCode)) {
                            String serialNo = (String) res.get("@serial_no");
                            String xtgzh = (String) res.get("@xtgzh");
                            String realOrder = (String) res.get("@real_order");
                            String conNo = (String) res.get("@times");
                            jsondate.put("serialNo",serialNo);
                            jsondate.put("dept",map.get("deptCode").toString());
                            jsondate.put("doctor",map.get("doctorMappingCode").toString());
                            logger.info("挂号流水 @serial_no: " + serialNo + " @times: " + conNo);
                            //保存日志
                            WlyyHttpLogDO log = new WlyyHttpLogDO();
                            log.setCode("registerOutPatient");
                            log.setName("挂号");
                            log.setPatient(patientId);
                            log.setDoctor(map.get("doctorCode").toString());
                            log.setResponse(rs.toString());
                            log.setStatus(rsCode);
                            log.setCreateTime(new Date());
                            wlyyHttpLogDao.save(log);
                        }else {
                            returnMap.put("msg","请求挂号失败");
                            returnMap.put("status","-1");
                            returnMap.put("id",baseNatAppointmentDO.getId());
                            return returnMap;
                        }
                        baseNatAppointmentDO.setDoctorId(map.get("doctorMappingCode").toString());
                        baseNatAppointmentDO.setDoctorName(map.get("doctorName").toString());

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("开单开始");
                    logger.info("saveNatAppointment params:"+jsondate.toString());
                    com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
                    array.add(jsondate);
                    try {
                        JSONObject jsonObject  = entranceService.BS10112(array.toString(),demoFlag);
                        //判断返回结果
                        String prers = jsonObject.getString("@RESULT");
                        //保存日志
                        WlyyHttpLogDO log = new WlyyHttpLogDO();
                        log.setCode("saveNatAppointment");
                        log.setName("核酸检测开方");
                        log.setPatient(patientId);
                        log.setDoctor(map.get("doctorCode").toString());
                        log.setResponse(jsonObject.toString());
                        log.setRequest(jsondate.toString());
                        log.setCreateTime(new Date());
                        wlyyHttpLogDao.save(log);
                        if ("0".equals(prers)) {
                            String realOrder = jsonObject.getString("@real_order");
                            String voucherNo = jsonObject.getString("@xtgzh0");
                            baseNatAppointmentDO.setRealOrder(realOrder);
                            baseNatAppointmentDO.setIsSuccess("1");
                            baseNatAppointmentDO.setVoucherNo(voucherNo);
                            baseNatAppointmentDO =baseNatAppointmentDao.save(baseNatAppointmentDO);
                            /*logger.info("模板消息推送标识pushFlag"+pushFlag);
                            if (!StringUtils.isNoneBlank(pushFlag)){
                                String recipeTime = DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss");
                                String applyDepaName = map.get("deptName").toString();
                                String applyDoctorName = map.get("doctorName").toString();
                                BasePatientDO patientDO = basePatientDao.findById(patientId);
                                String userName = null;
                                String idcard = null;
                                if (patientDO != null) {
                                    userName = patientDO.getName();
                                    idcard = patientDO.getIdcard();
                                }
                                String hisId = patientMappingService.findHisPatNoByPatient(patientId,mediaCard);
                                logger.info("cardNo:" + cardNo);
                                JSONObject jsonObject1 =entranceService.BS15054(hisId,realOrder,demoFlag);
                                net.sf.json.JSONObject res = jsonObject1.getJSONObject("resquest");
                                logger.info("获取待结算数据 res: " + res.toString());
                                String rsCode = res.getString("@RESULT");
                                String free= 0+"";
                                if ("0".equals(rsCode)) {
                                    free = res.getString("@total_charge");
                                }
                                ylzPayService.msgPush("01", mediaCard, "01", patientDO.getMobile(), "00", hisId, userName, idcard, voucherNo, applyDepaName, applyDoctorName, recipeTime, free, "1",pushChannel);
                            }else {

                            String title="您在厦门大学附属中山医院有一笔交易已支付完成！";
                            String pushPayLog = payInfoNoticeService.pushPrescriptionPayAndHsjc(baseNatAppointmentDO.getPatientId(),baseNatAppointmentDO.getDoctorName(),waitPayDetailVO.getVoucherNo(),natAppointmentDO.getId()+"",fee,title,null,waitPayDetailVO.getRecipeNo());
                            }*/


                        /*//成功后发送模板消息
                        sendNatWxTemplat(name,cardNo,mobile,natTime,realOrder,"natAppointmentRemind");*/
                        }else{
                            returnMap.put("msg","核酸检测开方失败");
                            returnMap.put("status","-1");
                            returnMap.put("id",baseNatAppointmentDO.getId());
                            return returnMap;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    returnMap.put("msg","预约成功");
                    returnMap.put("status","200");
                    returnMap.put("id",baseNatAppointmentDO.getId());
                    returnMap.put("realOrder",baseNatAppointmentDO.getRealOrder());
                }
            }
            return returnMap;
        }else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
            Double natFee = 8000.0;
            if(StringUtils.isNoneBlank(chargeAmount)){
                natFee= Double.parseDouble(chargeAmount)*100;
            }
            BaseNatAppointmentDO baseNatAppointmentDO= new BaseNatAppointmentDO();
            baseNatAppointmentDO.setMedicare(mediaCard);
            baseNatAppointmentDO.setChargeAmount(chargeAmount);
            baseNatAppointmentDO.setName(name);
            baseNatAppointmentDO.setCardNo(cardNo);
            baseNatAppointmentDO.setCardType(cardType);
            baseNatAppointmentDO.setAddress(address);
            baseNatAppointmentDO.setAppointmentTime(DateUtil.strToDateLong(natTime));
            baseNatAppointmentDO.setCityName(cityName);
            baseNatAppointmentDO.setFirstJobCode(firstJobCode);
            baseNatAppointmentDO.setFirstJobName(firstJobName);
            baseNatAppointmentDO.setSecondJobCode(secondJobCode);
            baseNatAppointmentDO.setSecondJobName(secondJobName);
            baseNatAppointmentDO.setProvinceName(provinceName);
            baseNatAppointmentDO.setTownName(townName);
            baseNatAppointmentDO.setStreetName(streetName);
            baseNatAppointmentDO.setPatientId(patientId);
            baseNatAppointmentDO.setIsSuccess("0");
            baseNatAppointmentDO.setPayStatus("0");
            baseNatAppointmentDO.setCreateTime(new Date());
            baseNatAppointmentDO.setMobile(mobile);
            baseNatAppointmentDO.setInspectionCode(chargeCode);
            baseNatAppointmentDO.setInspectionName(inspectionName);
            baseNatAppointmentDO.setIcdCode(icdCode);
            baseNatAppointmentDO.setChargeCode(chargeCode);
            baseNatAppointmentDO.setWinNo(String.valueOf(winNo));
            baseNatAppointmentDO.setDept("3150000");
            baseNatAppointmentDO.setDeptName("感染疾病科");
            baseNatAppointmentDO.setAmpm(pm);
            baseNatAppointmentDO.setHospitalFlag(pushFlag);
            baseNatAppointmentDO.setConsumer(consumer);
            baseNatAppointmentDO.setIdnoType(idnoType);
            BasePatientDO basePatientDO = basePatientDao.findById(consumer);
            baseNatAppointmentDO.setConsumerName(basePatientDO.getName());
            baseNatAppointmentDO= baseNatAppointmentDao.save(baseNatAppointmentDO);
            //添加订单
            BusinessOrderDO businessDO = new BusinessOrderDO();
            businessDO.setPatient(consumer);
            businessDO.setPatientName(basePatientDO.getName());
            businessDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            businessDO.setCreateTime(new Date());
            businessDO.setStatus(0);
            businessDO.setRelationCode(baseNatAppointmentDO.getId()+"");
            businessDO.setRelationName("核酸检测订单");
            businessDO.setOrderCategory("6");
            businessDO.setOrderType(12);
            businessDO.setPayPrice(natFee);
            businessDO.setRematk("核酸检测订单");
            businessDO.setDescription("核酸检测订单");
            businessDO.setPayType(1);
            businessDO.setUpdateTime(new Date());
            businessOrderDao.save(businessDO);
            logger.info("建档开始");
            com.alibaba.fastjson.JSONObject jdObject = ykyyEntranceService.patientJDKH(cardNo,name,mobile,mediaCard,null);
            logger.info("建档结束");
            logger.info("更新建档信息");
            BaseJobCategoryDO jobCategoryDO =jobCategoryDao.findByName(firstJobName);
            Float zy= 0f;
            if (jobCategoryDO!=null){
                zy=Float.parseFloat(jobCategoryDO.getId()+"");
            }
            ykyyEntranceService.updatePatientJd(patientId,address,mobile,zy,demoFlag);
            //同步眼科医院
            logger.info("开始同步眼科医院");
            ykyyEntranceService.saveKsjc(baseNatAppointmentDO,demoFlag);

            //预约成功后发送支付模板消息
            sendYktemplateMessage(baseNatAppointmentDO.getId(),false);
            logger.info("结束同步眼科医院");
            returnMap.put("msg","预约成功");
            returnMap.put("status","200");
            returnMap.put("id",baseNatAppointmentDO.getId());
            returnMap.put("realOrder",baseNatAppointmentDO.getRealOrder());
            return returnMap;
        }else if (wechatId.equalsIgnoreCase("xm_tasy_wx")){
            BasePatientDO  basePatientDO = basePatientDao.findById(patientId);
            List<WlyyHospitalSysDictDO> tasyList = wlyyHospitalSysDictDao.findByDictName("natConfigList");
            String deptCode = "0001";
            String staffNo = "0001";
            String staffName = "0001";
            String regDept="";
            String deptName="";
            String itemPrice="";
            for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:tasyList){
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"deptCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    deptCode = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"staffNo".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    staffNo = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"regDept".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    regDept = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"deptName".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    deptName = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"staffName".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    staffName = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"itemPrice".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    itemPrice = wlyyHospitalSysDictDO.getDictValue();
                }
            }
            Double natFee = 8000.0;
            if(StringUtils.isNoneBlank(itemPrice)){
                natFee= Double.parseDouble(itemPrice)*100;
            }
            //先预约号源
            Date format2 = null;
            format2 = new SimpleDateFormat("yyyy-MM-dd").parse(natTime);
            String shortDate = new SimpleDateFormat("yyyyMMdd").format(format2);
            System.out.println("yyyy-MM-dd转yyyyMMdd:"+shortDate);
            String regRes=tasyNatService.saveRegOrder(regDept,shortDate,pm,preNo,cardNo,mobile,name,"3");
            com.alibaba.fastjson.JSONObject regObj = com.alibaba.fastjson.JSONObject.parseObject(regRes);
            String HisSeqNo="";
            String orderNum="";
            if (regObj!=null){
                if ("true".equalsIgnoreCase(regObj.getString("success"))){
                    com.alibaba.fastjson.JSONObject dataObj = com.alibaba.fastjson.JSONObject.parseObject(regObj.getString("data"));
                    HisSeqNo=dataObj.getString("HisSeqNo").trim();
                    orderNum=dataObj.getString("OrderNumber").trim();
                }else {
                    returnMap.put("msg",regObj.getString("data"));
                    returnMap.put("status","-1");
                    return  returnMap;
                }
            }
            //先进行核算检测预约
            String realOrder="";
            String addressNow=provinceName+cityName+townName+streetName+address;
            String result = tasyNatService.initNatParams(HisSeqNo,name.trim(),mediaCard.trim(),addressNow,firstJobCode,secondJobCode);
            Boolean flag = false;
            if (StringUtils.isNoneBlank(result)){
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(result);
                logger.info("核酸检测预约结束"+result);
                if (object!=null){
                    String returnCode = object.getString("ReturnCode");
                    System.out.println("returnCode"+returnCode);
                    if ("0".equalsIgnoreCase(returnCode)){
                        returnMap.put("msg",object.getString("data"));
                        returnMap.put("status","-1");
                        tasyNatService.cancleOrder(cardNo,HisSeqNo,orderNum);
                        return  returnMap;
                    }else {
                        flag = true;
                        System.out.println(flag);
                        realOrder=object.getString("hisTradeNo");
                        System.out.println(realOrder);
                    }
                }

            }
            if (flag){
                logger.info("BaseNatAppointmentDO保存开始");
                BaseNatAppointmentDO baseNatAppointmentDO= new BaseNatAppointmentDO();
                baseNatAppointmentDO.setChargeAmount(itemPrice);
                baseNatAppointmentDO.setMedicare(mediaCard.trim());
                baseNatAppointmentDO.setRegisterNo(HisSeqNo);
                baseNatAppointmentDO.setName(name);
                baseNatAppointmentDO.setCardNo(cardNo.trim());
                baseNatAppointmentDO.setCardType(cardType);
                baseNatAppointmentDO.setIdnoType(idnoType);
                baseNatAppointmentDO.setAddress(address);
                baseNatAppointmentDO.setAppointmentTime(DateUtil.strToDateLong(natTime));
                baseNatAppointmentDO.setOderNum(orderNum);
                baseNatAppointmentDO.setCityName(cityName);
                baseNatAppointmentDO.setFirstJobCode(firstJobCode);
                baseNatAppointmentDO.setFirstJobName(firstJobName);
                baseNatAppointmentDO.setSecondJobCode(secondJobCode);
                baseNatAppointmentDO.setSecondJobName(secondJobName);
                baseNatAppointmentDO.setProvinceName(provinceName);
                baseNatAppointmentDO.setTownName(townName);
                baseNatAppointmentDO.setStreetName(streetName);
                baseNatAppointmentDO.setPatientId(patientId);
                baseNatAppointmentDO.setIsSuccess("0");
                baseNatAppointmentDO.setCardNoType(cardNoType);
                baseNatAppointmentDO.setPayStatus("0");
                baseNatAppointmentDO.setCreateTime(new Date());
                baseNatAppointmentDO.setMobile(mobile);
                baseNatAppointmentDO.setInspectionCode(chargeCode);
                baseNatAppointmentDO.setInspectionName(inspectionName);
                baseNatAppointmentDO.setIcdCode(icdCode);
                baseNatAppointmentDO.setChargeCode(chargeCode);
                baseNatAppointmentDO.setWinNo(String.valueOf(winNo));
                baseNatAppointmentDO.setDept(deptCode);
                baseNatAppointmentDO.setDeptName(deptName);
                baseNatAppointmentDO.setRealOrder(realOrder);
                baseNatAppointmentDO.setAmpm(pm);
                baseNatAppointmentDO.setDoctorId(staffNo);
                baseNatAppointmentDO.setConsumer(consumer);
                baseNatAppointmentDO.setDoctorName(staffName);
                baseNatAppointmentDO.setAppointmentTime(DateUtil.strToDateLong(natTime));
                baseNatAppointmentDO= baseNatAppointmentDao.save(baseNatAppointmentDO);
                logger.info("BaseNatAppointmentDO保存结束"+baseNatAppointmentDO.getId());
                //添加订单
                BusinessOrderDO businessDO = new BusinessOrderDO();
                businessDO.setPatient(consumer);
                businessDO.setPatientName(basePatientDO.getName());
                businessDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
                businessDO.setCreateTime(new Date());
                businessDO.setStatus(0);
                businessDO.setRelationCode(baseNatAppointmentDO.getId()+"");
                businessDO.setRelationName("核酸检测订单");
                businessDO.setOrderCategory("6");
                businessDO.setOrderType(12);
                businessDO.setPayPrice(natFee);
                businessDO.setRematk("核酸检测订单");
                businessDO.setDescription("核酸检测订单");
                businessDO.setPayType(1);
                businessDO.setUpdateTime(new Date());
                businessDO=businessOrderDao.save(businessDO);
                String openId="";
                List<BasePatientWechatDo> basePatientWechatDo = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,consumer);
                if (basePatientWechatDo!=null&&basePatientWechatDo.size()>0){
                    openId=basePatientWechatDo.get(0).getOpenid();
                }
                //亿同支付创建订单
                com.alibaba.fastjson.JSONObject orderObj= new com.alibaba.fastjson.JSONObject();
                orderObj.put("payType",1);
                orderObj.put("tradeNo",businessDO.getOrderNo());
                orderObj.put("openId",openId);
                orderObj.put("name",name);
                orderObj.put("idNo",cardNo.trim());
                Map mapHis=tasyNatService.getPatientHisId(cardNo.trim(),mediaCard.trim());
                orderObj.put("patientId",mapHis.get("Patientid").toString());
                orderObj.put("mobile",mapHis.get("MobilePhone").toString());
                //orderObj.put("socialCard","");
                orderObj.put("icCard",mediaCard);
                BigDecimal b = new BigDecimal(itemPrice);
                b=b.setScale(2, BigDecimal.ROUND_DOWN);
                System.out.println("amount"+b);
                orderObj.put("amount",b);
                String orderRes=tasyNatService.placeOrder(orderObj);
                if (StringUtils.isNoneBlank(orderRes)){
                    com.alibaba.fastjson.JSONObject jsonObject= JSON.parseObject(orderRes);
                    if (jsonObject!=null){
                        if("0".equalsIgnoreCase(jsonObject.getString("code"))){
                            com.alibaba.fastjson.JSONObject dataObj= com.alibaba.fastjson.JSONObject.parseObject(jsonObject.getString("data"));
                            businessDO.setTraceNo(dataObj.getString("orderNo"));
                            businessDO.setRematk(dataObj.toJSONString());
                            businessDO=businessOrderDao.save(businessDO);
                        }
                    }
                }
                try {
                    tasyNatService.sendWxtemplateMessaeg(baseNatAppointmentDO.getConsumer(),baseNatAppointmentDO.getName(),"hszftx",baseNatAppointmentDO.getId().toString());
                    tasyNatService.sendWxtemplateMessaeg(baseNatAppointmentDO.getConsumer(),baseNatAppointmentDO.getName(),"hsyycg",baseNatAppointmentDO.getId().toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
                logger.info("开单结束");
                returnMap.put("msg","预约成功");
                returnMap.put("status","200");
                returnMap.put("id",baseNatAppointmentDO.getId());
                returnMap.put("realOrder",baseNatAppointmentDO.getRealOrder());
                baseNatAppointmentDO.setIsSuccess("1");
                baseNatAppointmentDO= baseNatAppointmentDao.save(baseNatAppointmentDO);
            }else {
                returnMap.put("msg","核酸开方失败");
                returnMap.put("status","-1");
                return returnMap;
            }
            return returnMap;
        }
        return returnMap;
    }

    public String sendMessage(Integer id,String pushChannel,String pushFlag) throws Exception {
        BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(id);
        if (baseNatAppointmentDO==null){
            throw new Exception("预约记录不存在");
        }
        if (!StringUtils.isNoneBlank(baseNatAppointmentDO.getRealOrder())){
            throw new Exception("核酸项目不存在");
        }
        logger.info("模板消息推送标识pushFlag"+pushFlag);
        if (!StringUtils.isNoneBlank(pushFlag)){
            String recipeTime = DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss");
            String applyDepaName = baseNatAppointmentDO.getDeptName();
            String applyDoctorName = baseNatAppointmentDO.getDoctorName();
            BasePatientDO patientDO = basePatientDao.findById(baseNatAppointmentDO.getPatientId());
            String userName = null;
            String idcard = null;
            if (patientDO != null) {
                userName = patientDO.getName();
                idcard = patientDO.getIdcard();
            }
            String hisId = patientMappingService.findHisPatNoByPatient(baseNatAppointmentDO.getPatientId(),baseNatAppointmentDO.getMedicare());
            logger.info("cardNo:" + baseNatAppointmentDO.getMedicare());
            JSONObject jsonObject1 =entranceService.BS15054(hisId,baseNatAppointmentDO.getRealOrder(),demoFlag);
            net.sf.json.JSONObject res = jsonObject1.getJSONObject("resquest");
            logger.info("获取待结算数据 res: " + res.toString());
            String rsCode = res.getString("@RESULT");
            String free= 0+"";
            if ("0".equals(rsCode)) {
                free = res.getString("@total_charge");
            }
            ylzPayService.msgPush("01", baseNatAppointmentDO.getMedicare(), "01", patientDO.getMobile(), "00", hisId, userName, idcard, baseNatAppointmentDO.getVoucherNo(), applyDepaName, applyDoctorName, recipeTime, free, "1",pushChannel);
        }else {
            if (pushChannel.equalsIgnoreCase("WX_PUB")){
                String first="尊敬的用户"+baseNatAppointmentDO.getName()+"，您已完成线上自助核酸检测预约申请";
                String responseMsg="";
                String url="";
                String date = DateUtil.dateToStrLong(baseNatAppointmentDO.getAppointmentTime());
                String contentMsg="申请人："+baseNatAppointmentDO.getName()+"\r\n预约时间："+date;
                String remark = "1、请于预约时间"+date+"前，携带医保卡/就诊卡/电子健康卡到院区自助机进行结算。\r\n" +
                        "2、结算完成后请您持核酸预约申请信息和发票流水号、医保卡/就诊卡/电子健康卡，准时至我院五号楼北侧（急诊部后侧）核酸检测点领取标本试管窗口绑定检测。\r\n" +
                        "3、核酸检测标本采集24小时后出具报告。请关注厦门大学附属中山医院微信公众号查询；如需打印，请至厦门大学附属中山医院核酸检测点自助机打印。";
                if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)) {
                    responseMsg = entranceService.ehospitalNotice(
                            baseNatAppointmentDO.getName(),
                            baseNatAppointmentDO.getCardNo(),
                            baseNatAppointmentDO.getMobile(),
                            first,
                            url,
                            contentMsg,
                            remark);
                    logger.info("中山发送模板消息返回结果="+responseMsg);
                    System.out.println("结束发送模板消息");
                }
            }else if (pushChannel.equalsIgnoreCase("ALI_PUB")){
                BasePatientDO patientDO = basePatientDao.findById(baseNatAppointmentDO.getPatientId());
                com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                jsonObject.put("code","13");
                jsonObject.put("open_id",patientDO.getAlipayId());
                jsonObject.put("first","尊敬的用户"+baseNatAppointmentDO.getName()+"，您已完成线上自助核酸检测预约申请");
                jsonObject.put("keyword1",DateUtil.getStringDate());
                String date = DateUtil.dateToStrLong(baseNatAppointmentDO.getAppointmentTime());
                jsonObject.put("keyword2","申请人："+baseNatAppointmentDO.getName()+"\n预约时间："+date);
                String remark =  "1、请于预约时间"+date+"前，携带医保卡/就诊卡/电子健康卡到院区自助机进行结算。\n" +
                        "2、结算完成后请您持核酸预约申请信息和发票流水号、医保卡/就诊卡/电子健康卡，准时至我院五号楼北侧（急诊部后侧）核酸检测点领取标本试管窗口绑定检测。\n" +
                        "3、核酸检测标本采集24小时后出具报告。请关注厦门大学附属中山医院微信公众号查询；如需打印，请至厦门大学附属中山医院核酸检测点自助机打印。";
                jsonObject.put("remark",remark);
                jsonObject.put("url","111111");
                String url = "https://xmzsyyfwc.xmpbinfo.cn/weixin/1/notification/push/nucleictest";
                logger.info("jsonObject"+jsonObject.toJSONString());
                String encdata = AES.encrypt("3bdc154ed1e44a9c9f44451a16d8e0aa",jsonObject.toJSONString());
                Map<String, String> params = new HashedMap();
                params.put("encdata",encdata);
                String reponse = httpClientUtil.httpPost(url,params);
                logger.info("支付宝模板消息"+reponse);

            }

         }
         return "发送成功！";
    }
    public String sendYktemplateMessage(Integer id,boolean isPayed)  {
        BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(id);
        if (baseNatAppointmentDO==null){
            return "核酸项目不存在，发送失败";
        }
        List<BasePatientWechatDo> ps = new ArrayList<BasePatientWechatDo>();
        BasePatientDO patientDO = basePatientDao.findById(baseNatAppointmentDO.getPatientId());
        String userName = "";
        if (patientDO != null) {
            userName = patientDO.getName();
        }
        if (StringUtils.isNotEmpty(baseNatAppointmentDO.getConsumer())){
            ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId, baseNatAppointmentDO.getConsumer());
        }
        if (ps.isEmpty()) {
            logger.info("该用户没有openid,无法推送模版消息，用户ID：" + baseNatAppointmentDO.getConsumer() + "wechatId:" + wechatId);
        }
        Map<String,Object> map = ykyyEntranceService.findYkDoctor(baseNatAppointmentDO.getHospitalFlag());
        WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
        for (BasePatientWechatDo one : ps) {
            try {
                if (isPayed){
                    //眼科预约成功后消息提醒
                    WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
                    String scene = "hsyycgtx";
                    WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_hsyycg_notice", scene, 1);
                    BeanUtils.copyProperties(config, newConfig);
                    newConfig.setFirst(config.getFirst().replace("key1",userName));
                    if ("3".equalsIgnoreCase(baseNatAppointmentDO.getHospitalFlag())){
                        newConfig.setKeyword2("厦门大学附属厦门眼科中心思北院区");
                    }else {
                        newConfig.setKeyword2("厦门大学附属厦门眼科中心五缘院区");
                    }
                    newConfig.setKeyword3(map.get("doctorName")==null?"":map.get("doctorName").toString());
                    newConfig.setKeyword4(userName);
                    newConfig.setKeyword5(DateUtil.dateToStrLong(baseNatAppointmentDO.getAppointmentTime()));
                    newConfig.setRemark(config.getRemark().replace("key1",userName).replace("key2",DateUtil.dateToStrLong(baseNatAppointmentDO.getAppointmentTime())));
                    newConfig.setUrl(newConfig.getUrl()+baseNatAppointmentDO.getId());
                    logger.info("=======setUrlhsyycgtx========" + newConfig.getUrl());
                    logger.info("发送的消息="+ com.alibaba.fastjson.JSONObject.toJSONString(newConfig));
                    logger.info("调用眼科微信模板消息接口的入参：AccessToken="+wxAccessTokenDO.getAccessToken()+"---Openid="+one.getOpenid());
                    weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), one.getOpenid(), newConfig);
                    //保存发送模板记录,
                    WxPushLogDO wxPushLogDO = new WxPushLogDO();
                    wxPushLogDO.setCreateTime(new Date());
                    wxPushLogDO.setOpenid(one.getOpenid());
                    wxPushLogDO.setReceiver(baseNatAppointmentDO.getPatientId());
                    wxPushLogDO.setWechatId(wechatId);
                    wxPushLogDO.setScene(scene);
                    wxPushLogDao.save(wxPushLogDO);
                }else {
                    WxTemplateConfigDO newPayNotice = new WxTemplateConfigDO();
                    String scenePayNotice= "hszftx";
                    //眼科核酸预约成功后支付提醒
                    WxTemplateConfigDO configPayNotice = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_hszf_notice", scenePayNotice, 1);
                    BeanUtils.copyProperties(configPayNotice, newPayNotice);
                    newPayNotice.setFirst(configPayNotice.getFirst().replace("key1",userName));
                    if ("3".equalsIgnoreCase(baseNatAppointmentDO.getHospitalFlag())){
                        newPayNotice.setKeyword2("厦门大学附属厦门眼科中心思北院区");
                    }else {
                        newPayNotice.setKeyword2("厦门大学附属厦门眼科中心五缘院区");
                    }
                    newPayNotice.setKeyword3(map.get("doctorName")==null?"":map.get("doctorName").toString());
                    newPayNotice.setRemark(configPayNotice.getRemark());
                    newPayNotice.setUrl(configPayNotice.getUrl()+baseNatAppointmentDO.getId());
                    logger.info("=======setUrlhszftx========" + newPayNotice.getUrl());
                    logger.info("发送的消息="+ com.alibaba.fastjson.JSONObject.toJSONString(newPayNotice));
                    logger.info("发送核酸预约模板消息成功");
                    logger.info("调用眼科微信模板消息支付提醒接口的入参：AccessToken="+wxAccessTokenDO.getAccessToken()+"---Openid="+one.getOpenid());
                    weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), one.getOpenid(), newPayNotice);
                    //保存发送模板记录,
                    WxPushLogDO wxPushLogDO = new WxPushLogDO();
                    wxPushLogDO.setCreateTime(new Date());
                    wxPushLogDO.setOpenid(one.getOpenid());
                    wxPushLogDO.setReceiver(baseNatAppointmentDO.getPatientId());
                    wxPushLogDO.setWechatId(wechatId);
                    wxPushLogDO.setScene(scenePayNotice);
                    wxPushLogDao.save(wxPushLogDO);
                    logger.info("发送核酸预约模板消息支付提醒成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("发送核酸预约模板消息失败，error="+e.getMessage());
            }
        }
        return "发送成功！";
    }

    public MixEnvelop getNatRecords(String patientId,String id,String payStatus,String appointmentTime, String isSuccess,Integer page ,Integer pageSize){
        String sql = "select t.name as \"name\"," +
                "t.card_no as \"cardNo\"," +
                "t.card_type as \"cardType\"," +
                "t.mobile as \"mobile\"," +
                "t.inspection_name as \"inspectionName\"," +
                "t.real_order as \"realOrder\"," +
                "t.is_success as \"isSuccess\"," +
                "t.create_time as \"createTime\"," +
                "t.pay_status as \"payStatus\"," +
                "t.medicare as \"medicare\","+
                "t.voucher_no as \"voucherNo\","+
                "t.dept as \"dept\","+
                "t.dept_name as \"deptName\","+
                "t.id as \"id\"," +
                "t.card_no_type as \"cardNoType\"," +
                "t.HOSPITAL_FLAG as \"hospitalFlag\"," +
                "t.charge_amount as \"chargeAmount\"," ;
        if ("xm_tasy_wx".equalsIgnoreCase(wechatId)){
            sql+=" date_format(t.appointment_time ,'%Y-%m-%d' ) as \"appointmentTime\" ";
        }else {
            sql+=" t.appointment_time as \"appointmentTime\"";
        }
        sql+=  " from base_nat_appointment t where 1=1 ";

        if (StringUtils.isNoneBlank(patientId)){
            if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
                sql+=" and t.consumer ='"+patientId+"'";
            }else if (wechatId.equalsIgnoreCase("xm_tasy_wx")){
                sql+=" and t.consumer ='"+patientId+"'";
            } else {
                sql+=" and t.patient_id ='"+patientId+"'";
            }

        }
        if (StringUtils.isNoneBlank(id)){
            sql+=" and t.id ='"+id+"'";
        }
        if (StringUtils.isNoneBlank(payStatus)){
            sql+=" and t.pay_status ='"+payStatus+"'";
            sql+=" and t.is_success =1 ";
        }

        if (StringUtils.isNoneBlank(isSuccess)){
            sql+=" and t.is_success ="+isSuccess;
        }


        if (StringUtils.isNoneBlank(appointmentTime)){
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                sql+=" and t.appointment_time >= to_date('" + appointmentTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss')";
                sql+=" and t.appointment_time <= to_date('" + appointmentTime + " 23:59:59', 'yyyy-mm-dd hh24:mi:ss')";
            }else {
                sql+=" and t.appointment_time >='"+appointmentTime+" 00:00:00'";
                sql+=" and t.appointment_time <='"+appointmentTime+" 23:59:59'";
            }
        }

        sql+=" order by t.appointment_time desc ";
        List<Map<String ,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String ,Object>> listCount = hibenateUtils.createSQLQuery(sql);
        logger.info("查询数据"+sql);
        MixEnvelop mixnvelop = new MixEnvelop();
        if (listCount!=null&&listCount.size()>0){
            mixnvelop.setCurrPage(page);
            mixnvelop.setPageSize(pageSize);
            mixnvelop.setTotalCount(listCount.size());
            mixnvelop.setDetailModelList(list);

        }
        return mixnvelop;

    }


    public void savePayStatusByHis(String patientId) throws Exception {
        List<BaseNatAppointmentDO> baseNatAppointmentDOList = baseNatAppointmentDao.findPayStatusByPatientId(patientId);
        for (BaseNatAppointmentDO baseNatAppointmentDO:baseNatAppointmentDOList){
            String hisId = patientMappingService.findHisPatNoByPatient(patientId,baseNatAppointmentDO.getMedicare());
            logger.info("cardNo:" + baseNatAppointmentDO.getMedicare());
            JSONObject jsonObject1 =entranceService.BS15054(hisId,baseNatAppointmentDO.getRealOrder(),demoFlag);
            net.sf.json.JSONObject res = jsonObject1.getJSONObject("resquest");
            logger.info("获取待结算数据 res: " + res.toString());
            String rsCode = res.getString("@RESULT");
            String free= 0+"";
            String settleFlag = "";
            if ("0".equals(rsCode)) {
                free = res.getString("@total_charge");
                settleFlag = res.getString("@settle_flag");
                if (StringUtils.isNoneBlank(settleFlag)&&settleFlag.equalsIgnoreCase("Y")){
                    baseNatAppointmentDO.setPayStatus("1");
                }

                if (StringUtils.isNoneBlank(free)&&free.equalsIgnoreCase("0")){
                    baseNatAppointmentDO.setPayStatus("1");
                }
                baseNatAppointmentDao.save(baseNatAppointmentDO);
            }
        }
    }

    public List<Map<String,Object>> findBaseAddress(String addressFlag,String parentName){
        String sql="";
        if ("1".equalsIgnoreCase(addressFlag)){
            sql+="select  t.province_name as \"provinceName\" from base_address_mapping t group by t.province_name ";
        }else if("2".equalsIgnoreCase(addressFlag)){
            sql+="select  t.city_name as \"cityName\" from base_address_mapping t where t.province_name ='"+parentName+"'  and city_name is not null group by t.city_name ";
        }else if("3".equalsIgnoreCase(addressFlag)){
            sql+="select  t.town_name as \"townName\" from base_address_mapping t  where t.city_name ='"+parentName+"'  and town_name is not null  group by t.town_name";
        }else if("4".equalsIgnoreCase(addressFlag)){
            sql+="select  t.street_name as \"streetName\" from base_address_mapping t  where t.town_name ='"+parentName+"'  and street_name is not null";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        list.stream().forEach(one->{
            String firstSpell = null;
            if ("1".equalsIgnoreCase(addressFlag)){
                firstSpell = PinYinUtils.getFirstSpell(one.get("provinceName").toString());
            }else if("2".equalsIgnoreCase(addressFlag)){
                firstSpell = PinYinUtils.getFirstSpell(one.get("cityName").toString());
            }else if("3".equalsIgnoreCase(addressFlag)){
                firstSpell = PinYinUtils.getFirstSpell(one.get("townName").toString());
            }else if("4".equalsIgnoreCase(addressFlag)){
                firstSpell = PinYinUtils.getFirstSpell(one.get("streetName").toString());
            }
            one.put("firstSpell",firstSpell);
        });
        return list;

    }
    //患者取消预约
    public String cancelNatAppointment (Integer id,String patientId ){
        BasePatientDO patientDO = basePatientDao.findById(patientId);
        String res = "";
        if (patientDO!=null){
            try {
                BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(id);
                if (null!=baseNatAppointmentDO){
                    if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                        res = entranceService.BS10145("3150000","0001",DateUtil.dateToStrLong(baseNatAppointmentDO.getAppointmentTime()),baseNatAppointmentDO.getMedicare(),baseNatAppointmentDO.getName(),baseNatAppointmentDO.getCardNo(),baseNatAppointmentDO.getMobile(),baseNatAppointmentDO.getAmpm(),demoFlag);
                        logger.info("核酸检测预约取消"+res);
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res);
                        Boolean flag = false;
                        if (jsonObject!=null){
                            com.alibaba.fastjson.JSONObject object = jsonObject.getJSONObject("MsgInfo");
                            String Msg = object.getString("Msg");
                            if (Msg.contains("Error")){
                                throw new Exception(Msg);
                            }else {
                                baseNatAppointmentDO.setIsSuccess("-1");
                                baseNatAppointmentDO.setCancelReson("患者本人取消");
                                baseNatAppointmentDO.setCancelTime(new Date());
                                baseNatAppointmentDO.setCancelBy(patientId);
                                baseNatAppointmentDao.save(baseNatAppointmentDO);
                                if (StringUtils.isNoneBlank(baseNatAppointmentDO.getRealOrder())){
                                    List<WlyyHospitalSysDictDO> natConfigList = wlyyHospitalSysDictDao.findByDictName("natConfigList");
                                    String checkPart = "鼻/咽拭子";
                                    String chargeFlag = "2";
                                    String icdCode = "Z00.000";
                                    Integer winNo = 6;
                                    for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:natConfigList){
                                        if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"checkPart".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                                            checkPart = wlyyHospitalSysDictDO.getDictValue();
                                        }
                                        if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"chargeFlag".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                                            chargeFlag = wlyyHospitalSysDictDO.getDictValue();
                                        }
                                        if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"icdCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                                            icdCode = wlyyHospitalSysDictDO.getDictValue();
                                        }
                                        if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"winNo".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                                            winNo = Integer.parseInt(wlyyHospitalSysDictDO.getDictValue());
                                        }
                                    }
                                    //删除处方
                                    logger.info("删除处方开始");
                                    net.sf.json.JSONObject jsondate = new JSONObject();
                                    jsondate.put("checkPart",checkPart);
                                    jsondate.put("cardNo",baseNatAppointmentDO.getMedicare());
                                    jsondate.put("chargeFlag",chargeFlag);
                                    jsondate.put("chargeCode",baseNatAppointmentDO.getChargeCode());
                                    jsondate.put("icdCode",icdCode);
                                    jsondate.put("socialNo",baseNatAppointmentDO.getCardNo());
                                    jsondate.put("tellPhone",baseNatAppointmentDO.getMobile());
                                    jsondate.put("address1",baseNatAppointmentDO.getProvinceName());
                                    jsondate.put("address2",baseNatAppointmentDO.getCityName());
                                    jsondate.put("address3",baseNatAppointmentDO.getTownName());
                                    jsondate.put("address4",baseNatAppointmentDO.getStreetName());
                                    jsondate.put("address5",baseNatAppointmentDO.getAddress());
                                    jsondate.put("area",baseNatAppointmentDO.getTownName());
                                    jsondate.put("winNo",winNo);
                                    if (StringUtils.isNoneBlank(baseNatAppointmentDO.getSecondJobName())){
                                        jsondate.put("target",baseNatAppointmentDO.getSecondJobName());
                                    }else {
                                        jsondate.put("target",baseNatAppointmentDO.getFirstJobName());
                                    }
                                    jsondate.put("quantity",1);
                                    jsondate.put("serialNo",baseNatAppointmentDO.getRegisterNo());
                                    jsondate.put("dept",baseNatAppointmentDO.getDept());
                                    jsondate.put("doctor",baseNatAppointmentDO.getDoctorId());
                                    jsondate.put("realOrder",baseNatAppointmentDO.getRealOrder());
                                    JSONArray array = new JSONArray();
                                    array.add(jsondate);
                                    JSONObject object1  = entranceService.BS10112(array.toString(),demoFlag);
                                    logger.info("删除处方结束");
                                }

                            }
                        }
                    }else if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                        baseNatAppointmentDO.setIsSuccess("-1");
                        baseNatAppointmentDO.setCancelReson("患者本人取消");
                        baseNatAppointmentDO.setCancelTime(new Date());
                        baseNatAppointmentDO.setCancelBy(patientId);
                        baseNatAppointmentDao.save(baseNatAppointmentDO);
                        if (StringUtils.isNoneBlank(baseNatAppointmentDO.getRealOrder())){
                            logger.info("同步his订单状态"+baseNatAppointmentDO.getRealOrder());
                            String updateJcsq = "update V_EMR_JCSQ set ZFBZ = 1 where yjxh = "+baseNatAppointmentDO.getRealOrder();
                            ykyyEntranceService.updateHisStatus(updateJcsq);
                            String update01sq = "update V_MS_YJ01 set ZFPB = 1 where yjxh = "+baseNatAppointmentDO.getRealOrder();
                            ykyyEntranceService.updateHisStatus(update01sq);
                        }

                    }else if("xm_tasy_wx".equalsIgnoreCase(wechatId)){
                        if (StringUtils.isNoneBlank(baseNatAppointmentDO.getRealOrder())){
                            logger.info("同步his订单状态"+baseNatAppointmentDO.getRealOrder());
                            //取消号源
                            String registerCancel =tasyNatService.cancleOrder(baseNatAppointmentDO.getCardNo(),baseNatAppointmentDO.getRegisterNo(),baseNatAppointmentDO.getOderNum());
                            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(registerCancel);
                            String isSuccess=jsonObject.getString("success");
                            String natCancel=tasyNatService.cancelNat(baseNatAppointmentDO.getRealOrder(),baseNatAppointmentDO.getMedicare().trim(),baseNatAppointmentDO.getName());
                            com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(natCancel);
                            String returnCode=jsonObject1.getString("ReturnCode");
                            if ("1".equalsIgnoreCase(returnCode)){
                                System.out.println("11111");
                                baseNatAppointmentDO.setIsSuccess("-1");
                                baseNatAppointmentDO.setCancelReson("患者本人取消");
                                baseNatAppointmentDO.setCancelTime(new Date());
                                baseNatAppointmentDO.setCancelBy(patientId);
                                baseNatAppointmentDao.save(baseNatAppointmentDO);
                                res="success";
                            }
                            /*String backMsg="";
                            if ("0".equalsIgnoreCase(returnCode)){
                                backMsg+=jsonObject1.getString("ReturnMsg");
                            }
                            if (!"true".equalsIgnoreCase(isSuccess)){
                                String data=jsonObject1.getString("data");
                                backMsg+=jsonObject1.getString("ReturnMsg");
                            }*/
                        }
                    }


                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return res;
    }


    public String sendAlipayMessage(String patientId,String code,String fee,String redirdctUrl,String reserverTime,String realorder) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
      /*  ⽀付提醒通知：
        code: 通知代码，⽀付提醒为“2” open_id：⽀付宝⽤户ID user_name: 姓名 order_id: 订单号
        create_time: 订单创建时间 fee: ⾦额 url：通知详情跳转链接*/
        /*预约成功通知：
        code: 通知代码，预约为“4” open_id: ⽀付宝⽤户ID user_name: 姓名 unit_name: 科室名
        doctor_name: 医⽣名 order_time: 预约时间 order_no: 预约号*/

        /* ⽀付成功通知：
        code：通知代码，⽀付成功为“3” open_id：⽀付宝⽤户ID first: 您好,恭喜⽀付成功！ fee: ⾦额
        fee_type_name: 费⽤类型 url: 通知详情跳转链接 remark: 备注，以\n换⾏*/

        BasePatientDO patientDO = basePatientDao.findById(patientId);

        if (code.equalsIgnoreCase("3")){
            jsonObject.put("code",code);
            jsonObject.put("open_id",patientDO.getAlipayId());
            jsonObject.put("first",patientDO.getName()+"您好，您有一笔交易支付成功！支付明细如下：");
            jsonObject.put("fee_type_name","核酸预约申请");
            jsonObject.put("fee",fee);
            jsonObject.put("url",redirdctUrl);
            String remark = "发票流水号："+realorder+"\n" +
                    "点击查看核酸预约开单信息\n" ;
            jsonObject.put("remark",remark);
        }else if (code.equalsIgnoreCase("13")){
           /* code: 通知代码，预约为“13” open_id: ⽀付宝⽤户ID first: 第⼀⾏ keyword1: 第⼆⾏ keyword2: 第三⾏
            remark: 备注 url: 详情链接*/
            jsonObject.put("code",code);
            jsonObject.put("open_id",patientDO.getAlipayId());
            jsonObject.put("first","尊敬的用户"+patientDO.getName()+"，您已完成线上自助核酸检测预约申请");
            jsonObject.put("keyword1",DateUtil.getStringDate());
            jsonObject.put("keyword2","申请人："+patientDO.getName()+"\n" +
                    "预约时间："+reserverTime+"\n" +
                    "发票流水号："+realorder+"");
            String remark = "1、请您持核酸预约申请信息和发票流水号、医保卡/就诊卡/电子健康卡，准时至我院五号楼北侧（急诊部后侧）核酸检测点领取标本试管窗口绑定检测。\n" +
                    "2、核酸检测标本采集24小时后出具报告。请关注厦门大学附属中山医院微信公众号查询；如需打印，请至厦门大学附属中山医院核酸检测点自助机打印。";
            jsonObject.put("remark",remark);
            jsonObject.put("url",redirdctUrl);
        }

        String url = "https://xmzsyyfwc.xmpbinfo.cn/weixin/1/notification/push/nucleictest";
        logger.info("jsonObject"+jsonObject.toJSONString());
        String encdata = AES.encrypt("3bdc154ed1e44a9c9f44451a16d8e0aa",jsonObject.toJSONString());
        Map<String, String> params = new HashedMap();
        params.put("encdata",encdata);
        String reponse = httpClientUtil.httpPost(url,params);
        logger.info("支付宝模板消息"+reponse);
        return reponse;

    }

    /**
     * 获取核酸检测记录
     * @param realOrder 处方号
     * @param name 居民姓名
     * @param hospitalFlag 机构
     * @param mobile 电话
     * @param idcard 身份证
     * @param payStatus 支付状态
     * @param medicare 社保卡
     * @param appointmentTimeStart
     * @param appointmentTimeEnd
     * @param page
     * @param pageSize
     * @return
     */
    public Envelop getNatAppointmentList(String realOrder, String name, String hospitalFlag, String mobile, String idcard, String payStatus, String medicare, String createTimeStart, String createTimeEnd, String appointmentTimeStart, String appointmentTimeEnd, Integer isSuccess, Integer page, Integer pageSize,String orderNo) {
        String sql = "select t.name as \"name\"," +
                "t.card_no as \"cardNo\"," +
                "t.card_type as \"cardType\"," +
                "t.mobile as \"mobile\"," +
                "t.inspection_name as \"inspectionName\"," +
                "t.real_order as \"realOrder\"," +
                "t.is_success as \"isSuccess\"," +
                "t.create_time as \"createTime\"," +
                "t.pay_status as \"payStatus\"," +
                "t.medicare as \"medicare\"," +
                "t.voucher_no as \"voucherNo\"," +
                "t.dept as \"dept\"," +
                "t.dept_name as \"deptName\"," +
                "t.id as \"id\"," +
                "t.card_no_type as \"cardNoType\"," +
                "t.HOSPITAL_FLAG as \"hospitalFlag\"," +
                "m.order_no as \"orderNo\"," +
                "t.charge_amount as \"chargeAmount\"," +
                "t.appointment_time as \"appointmentTime\" " +
                " from base_nat_appointment t left join base_business_order_pay m ";
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            sql+=" on to_char(t.id) = m.relation_code " +
                    " where 1=1 ";
        }else{
            sql+=" on cast(t.id as char) = m.relation_code " +
                    " where 1=1 ";
        }
        if (StringUtils.isNotBlank(realOrder)) {
            sql += " and t.real_order like '%" + realOrder + "%' ";
        }
        if (StringUtils.isNotBlank(name)) {
            sql += " and t.name like '%" + name + "%'";
        }
        if (StringUtils.isNotBlank(mobile)) {
            sql += " and t.mobile like '%" + mobile + "%' ";
        }
        if (StringUtils.isNotBlank(idcard)) {
            sql += " and t.card_no like '%" + idcard + "%' ";
        }
        if (StringUtils.isNoneBlank(orderNo)){
            sql+=" and m.order_no = '"+orderNo+"' ";
        }
        //支付状态
        if (StringUtils.isNotBlank(payStatus)) {
            sql += " and t.pay_status ='" + payStatus + "' ";
        }
        //社保卡
        if (StringUtils.isNotBlank(medicare)) {
            sql += " and t.medicare like '%" + medicare + "%' ";
        }
        if (StringUtils.isNotBlank(hospitalFlag)) {
            sql += " and t.hospital_flag ='" + hospitalFlag + "' ";
        }
        if(isSuccess != null){
            sql += " and t.is_success = " + isSuccess ;
        }
        if (StringUtils.isNotBlank(appointmentTimeStart)) {
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                sql += " and t.appointment_time >= to_date('" + appointmentTimeStart + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss')";
//                sql += " and t.appointment_time <= to_date('" + appointmentTime + " 23:59:59', 'yyyy-mm-dd hh24:mi:ss')";
            } else {
                sql += " and t.appointment_time >='" + appointmentTimeStart + " 00:00:00'";
//                sql += " and t.appointment_time <='" + appointmentTime + " 23:59:59'";
            }
        }
        if (StringUtils.isNotBlank(appointmentTimeEnd)) {
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                sql += " and t.appointment_time <= to_date('" + appointmentTimeEnd + " 23:59:59', 'yyyy-mm-dd hh24:mi:ss')";
            } else {
                sql += " and t.appointment_time <='" + appointmentTimeEnd + " 23:59:59' ";
            }
        }
        if (StringUtils.isNotBlank(createTimeStart)) {
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                sql += " and t.create_time >= to_date('" + createTimeStart + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss')";
//                sql+=" and t.create_time <= to_date('" + createTime + " 23:59:59', 'yyyy-mm-dd hh24:mi:ss')";
            } else {
                sql += " and t.create_time >='" + createTimeStart + " 00:00:00' ";
//                sql+=" and t.create_time <='"+createTime+" 23:59:59'";
            }
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                sql+=" and t.create_time <= to_date('" + createTimeEnd + " 23:59:59', 'yyyy-mm-dd hh24:mi:ss')";
            } else {
                sql+=" and t.create_time <='"+createTimeEnd+" 23:59:59'";
            }
        }

        sql += " order by t.create_time desc ";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, pageSize);
        List<Map<String, Object>> listCount = hibenateUtils.createSQLQuery(sql);
        logger.info("查询数据" + sql);
        if (page != null && pageSize != null) {
            MixEnvelop envelop = new MixEnvelop();
            envelop.setStatus(200);
            envelop.setMessage("获取成功!");
            if (listCount != null && listCount.size() > 0) {
                envelop.setCurrPage(page);
                envelop.setPageSize(pageSize);
                envelop.setTotalCount(listCount.size());
                envelop.setDetailModelList(list);
            }
            return envelop;
        }else {
            ListEnvelop envelop = new ListEnvelop();
            envelop.setStatus(200);
            envelop.setMessage("获取成功!");
            envelop.setDetailModelList(list);
            return envelop;
        }

    }
    public  BaseDoctorDO findByIdCard(String idCard){
        return  baseDoctorDao.findByIdcardAndDel(idCard);
    }


    public  void updateChannelId(String id,String channelId){
        outpatientDao.updateChannelId(id,channelId);
    }

    /**
     *
     * @param userId 用户id 实例：["22222"]
     * @param alert 通知内容
     * @param title 通知标题
     * @param extras 扩展参数 {"type","","id":""}
     * @return
     */
    public String jPushMessage(String isDoctor,String userId, String alert, String title, com.alibaba.fastjson.JSONObject extras){
        List<WlyyHospitalSysDictDO> hospitalSysDictDOList = hospitalSysDictDao.findByDictName("JPUSH");
        String appKey = null;
        String masterSecret =null;
        for (WlyyHospitalSysDictDO hospitalSysDictDO:hospitalSysDictDOList){
            if ("1".equalsIgnoreCase(isDoctor)){
                if (hospitalSysDictDO.getDictCode().equalsIgnoreCase("appKey")){
                    appKey=hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getDictCode().equalsIgnoreCase("masterSecret")){
                    masterSecret = hospitalSysDictDO.getDictValue();
                }
            }else {
                if (hospitalSysDictDO.getDictCode().equalsIgnoreCase("appKeyPatient")){
                    appKey=hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getDictCode().equalsIgnoreCase("masterSecretPatient")){
                    masterSecret = hospitalSysDictDO.getDictValue();
                }
            }
        }
        logger.info("appKey"+appKey+"======"+"masterSecret"+masterSecret);
        logger.info("addExtra++++"+extras.toString());
        JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());

        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.alias(userId)).build())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setBadge(5)
                                .setSound("default")
                                .addExtra("type", extras.getString("type"))
                                .addExtra("id", extras.getString("id"))
                                .addExtra("outpatientId", extras.getString("outpatientId"))
                                .addExtra("consultType", extras.getString("consultType"))
                                .addExtra("patientName", extras.getString("patientName"))
                                .setBadge(1)
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .setTitle(title)
                                .setBuilderId(1)
                                .addExtra("type", extras.getString("type"))
                                .addExtra("outpatientId", extras.getString("outpatientId"))
                                .addExtra("id", extras.getString("id"))
                                .addExtra("consultType", extras.getString("consultType"))
                                .addExtra("patientName", extras.getString("patientName"))
                                .build())
                        .build())
                .build();
        try {
            PushResult result = jPushClient.sendPush(payload);
            logger.info("极光推送返回日志==="+result);
            WlyyHttpLogDO httpLogDO = new WlyyHttpLogDO();
            httpLogDO.setCode("JPUSH");
            httpLogDO.setCreateTime(new Date());
            httpLogDO.setRequest(extras==null?"":extras.toString());
            httpLogDO.setResponse(result==null?"":result.toString());
            wlyyHttpLogDao.save(httpLogDO);
            logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            logger.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
        }


        return null;

    }
    public String wxTempalteJPush(String templateCode,WlyyOutpatientDO wlyyOutpatientDO ,ConsultTeamDo consultTeamDo,String drugName ,String mailNo,String mailStatus,String prescriptionId){
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
        String userId = "";
        String content = "";
        String title="";
        String isDoctor="0";//0患者 1医生
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        if("give_score".equalsIgnoreCase(templateCode)){//评分
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                content = baseJpushTemplateDO.getPushContent();
                if(1==consultTeamDo.getType()){
                    content= content.replace("{{咨询类型}}","图文咨询");
                }else if(9==consultTeamDo.getType()){
                    content= content.replace("{{咨询类型}}","图文复诊");
                }
                else if(16==consultTeamDo.getType()){
                    content=  content.replace("{{咨询类型}}","视频复诊");
                }
                else if(17==consultTeamDo.getType()){
                    content=  content.replace("{{咨询类型}}","视频咨询");
                }
                title=baseJpushTemplateDO.getPushHeader();
            }
            userId = consultTeamDo.getPatient();
            jsonObject.put("type",10);
            jsonObject.put("id",consultTeamDo.getConsult());
        }else if("video_invite".equalsIgnoreCase(templateCode)){//视频邀请
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                content = baseJpushTemplateDO.getPushContent().replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());;

                title=baseJpushTemplateDO.getPushHeader();
            }
            userId = wlyyOutpatientDO.getConsumer();
            jsonObject.put("type",30);
            jsonObject.put("id",wlyyOutpatientDO.getId());
        }else if("consult_remind".equalsIgnoreCase(templateCode)){//医生向患者发消息提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                content = baseJpushTemplateDO.getPushContent();
                content= content.replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                title=baseJpushTemplateDO.getPushHeader().replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
            }
            userId = wlyyOutpatientDO.getConsumer();
            jsonObject.put("type",31);
            jsonObject.put("id",wlyyOutpatientDO.getId());

        }else if("consult_remind_doctor".equalsIgnoreCase(templateCode)){//患者向医生发消息提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                //content = baseJpushTemplateDO.getPushContent();
                content= drugName;
                title=baseJpushTemplateDO.getPushHeader().replace("{{患者姓名}}",consultTeamDo.getName());
            }
            userId = consultTeamDo.getDoctor();
            jsonObject.put("type",33);
            jsonObject.put("id",consultTeamDo.getRelationCode());
            jsonObject.put("consultType",consultTeamDo.getType());
            jsonObject.put("patientName",consultTeamDo.getName());
            isDoctor = "1";
        }  else if("prescription_pay".equalsIgnoreCase(templateCode)){//处方支付提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                content = baseJpushTemplateDO.getPushContent();
                content= content.replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                title=baseJpushTemplateDO.getPushHeader();
            }
            userId = wlyyOutpatientDO.getConsumer();
            jsonObject.put("type",6);
            jsonObject.put("id",prescriptionId);
            jsonObject.put("outpatientId",wlyyOutpatientDO.getId());
        } else if("outpatient_pay".equalsIgnoreCase(templateCode)){//诊查费支付提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文复诊");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文复诊");
                    jsonObject.put("consultType",9);
                }else if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频复诊");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频复诊");
                    jsonObject.put("consultType",16);
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文咨询");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文咨询");
                    jsonObject.put("consultType",1);
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频咨询");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频咨询");
                    jsonObject.put("consultType",17);
                }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","协同复诊");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","协同复诊");
                    jsonObject.put("consultType",12);
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","家医咨询");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","家医咨询");
                    jsonObject.put("consultType",15);
                }
            }
            userId = wlyyOutpatientDO.getConsumer();
            jsonObject.put("type",11);
            jsonObject.put("id",wlyyOutpatientDO.getId());
        } else if("cancel_remind".equalsIgnoreCase(templateCode)){//医生取消接诊提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文复诊");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文复诊");
                }else if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频复诊");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频复诊");
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文咨询");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文咨询");
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频咨询");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频咨询");
                }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","协同复诊");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","协同复诊");
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","家医咨询");
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","家医咨询");
                }
            }
            userId = wlyyOutpatientDO.getConsumer();
            jsonObject.put("type",12);
            jsonObject.put("id",wlyyOutpatientDO.getId());
        }else if("outpatient_remind".equalsIgnoreCase(templateCode)){//患者发起复诊向医生推消息
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文复诊").replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文复诊");
                    jsonObject.put("type",1);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频复诊").replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                    content+= "视频复诊预约时间为:"+wlyyOutpatientDO.getRegisterDate();
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频复诊");
                    jsonObject.put("type",2);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文咨询").replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文咨询");
                    jsonObject.put("type",18);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频咨询").replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频咨询");
                    content+= "视频咨询预约时间为:"+wlyyOutpatientDO.getRegisterDate();
                    jsonObject.put("type",17);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","协同复诊").replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","协同复诊");
                    jsonObject.put("type",3);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","家医咨询").replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","家医咨询");
                    jsonObject.put("type",15);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }
            }
            userId = wlyyOutpatientDO.getDoctor();
            jsonObject.put("id",wlyyOutpatientDO.getId());
            isDoctor="1";
        } else if("prescription_refuse".equalsIgnoreCase(templateCode)){//处方审方失败提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                content = baseJpushTemplateDO.getPushContent();
                content=  content.replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName()).replace("{{医生姓名}}",wlyyOutpatientDO.getDoctorName());
                title=baseJpushTemplateDO.getPushHeader().replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
            }
            userId = wlyyOutpatientDO.getDoctor();
            jsonObject.put("type",8);
            jsonObject.put("id",prescriptionId);
            isDoctor="1";
        } else if("logistics_remind".equalsIgnoreCase(templateCode)){//物流消息提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                content = baseJpushTemplateDO.getPushContent();
                content=  content.replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName()).replace("{{药品名称}}",drugName)
                .replace("{{物流状态}}",mailStatus).replace("{{运单号}}",mailNo);
                title=baseJpushTemplateDO.getPushHeader();
            }
            userId = wlyyOutpatientDO.getConsumer();
            jsonObject.put("type",32);
            jsonObject.put("id",prescriptionId);
            jsonObject.put("outpatientId",wlyyOutpatientDO.getId());
        }else if("remind_doctor_pickup".equalsIgnoreCase(templateCode)){//接诊下消息提醒
            BaseJpushTemplateDO baseJpushTemplateDO = baseJpushTemplateDao.findByCode(templateCode);
            if(baseJpushTemplateDO!=null){
                if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文复诊").replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文复诊接诊提醒");
                    jsonObject.put("type",51);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频复诊").replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                    content+= "视频复诊预约时间为:"+wlyyOutpatientDO.getRegisterDate();
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频复诊接诊提醒");
                    jsonObject.put("type",52);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","图文咨询").replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","图文咨询接诊提醒");
                    jsonObject.put("type",58);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","视频咨询").replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","视频咨询接诊提醒");
                    content+= "视频咨询预约时间为:"+wlyyOutpatientDO.getRegisterDate();
                    jsonObject.put("type",57);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","协同复诊").replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","协同复诊接诊提醒");
                    jsonObject.put("type",53);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    content = baseJpushTemplateDO.getPushContent().replace("{{咨询类型}}","家医咨询").replace("{{患者姓名}}",wlyyOutpatientDO.getPatientName());
                    title=baseJpushTemplateDO.getPushHeader().replace("{{咨询类型}}","家医咨询接诊提醒");
                    jsonObject.put("type",55);
                    jsonObject.put("patientName",wlyyOutpatientDO.getPatientName());
                }
                String sex = IdCardUtil.getSexNameForIdcard_new(wlyyOutpatientDO.getIdcard());
                Integer age = IdCardUtil.getAgeForIdcard(wlyyOutpatientDO.getIdcard());
                Long createTime = wlyyOutpatientDO.getCreateTime().getTime();
                Long nowTime = new Date().getTime();
                Long minusts = TimeUnit.MILLISECONDS.toMinutes(nowTime - createTime);
                content = content.replace("{{性别年龄}}",sex+age+"岁").replace("{{等待时间}}",minusts.toString());
            }
            userId = wlyyOutpatientDO.getDoctor();
            jsonObject.put("id",wlyyOutpatientDO.getId());
            isDoctor="1";
        }

        return jPushMessage(isDoctor,userId,content,title,jsonObject);
        }
        return "";

    }

    //中山消息中心业务接口
    public String sendZsMsgFlow(String msgType ,String outpatientId,String prescriptionId,String jumpUrl,String remark){
        try {
            String visitId ="";//挂号流水号
            String msgId ="";//挂号流水号
            String idType ="01";//证件类型 01:身份证 * 02:户口簿* 03:护照* 04:军官证* 05:驾驶证* 06:港澳居民往来内地通行证* 07:台湾居民往来内地通行证* 99:其他法定有效证件
            String idNo ="";//证件号
            String patientName ="";//患者姓名
            String msgTime ="";//消息时间yyyy-MM-dd HH:mm:sss
            String msgContent ="";//消息内容
            String jumpType ="1";
            String miniAppId ="";
            String miniAppUrl ="";
            String sender ="";//发送系统
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if ("OL_PAY_SUCCESS".equalsIgnoreCase(msgType)){//在线问诊-已支付问诊费
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
                BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientId);
                if(businessOrderDO!=null){
                    msgId=businessOrderDO.getOrderNo().substring(5);
                    visitId = businessOrderDO.getOrderNo().substring(5);
                }
                if (wlyyOutpatientDO!=null){
                    idNo=wlyyOutpatientDO.getIdcard();
                    patientName = wlyyOutpatientDO.getPatientName();
                    msgTime = sf.format(new Date());
                    sender ="ZJXL";
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    DoctorMappingDO doctorMappingDO =doctorMappingDao.findByDoctor(wlyyOutpatientDO.getDoctor());
                    if(doctorMappingDO!=null){
                        jsonObject.put("doctorId",doctorMappingDO.getMappingCode());
                    }
                    jsonObject.put("patientName",patientName);
                    jsonObject.put("idType",idType);
                    jsonObject.put("idNo",idNo);
                    jsonObject.put("doctorName",wlyyOutpatientDO.getDoctorName());
                    jsonObject.put("deptId",wlyyOutpatientDO.getDept());
                    jsonObject.put("deptName",wlyyOutpatientDO.getDeptName());
                    jsonObject.put("visitTime",sf.format(wlyyOutpatientDO.getCreateTime()));
                    msgContent= jsonObject.toString();
                }

            }else if ("OL_WZ_CANCEL".equalsIgnoreCase(msgType)||"OL_WZCS_CANCEL".equalsIgnoreCase(msgType)){
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
                BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientId);
                if(businessOrderDO!=null){
                    msgId=businessOrderDO.getOrderNo().substring(5);
                    visitId = businessOrderDO.getOrderNo().substring(5);
                }
                if (wlyyOutpatientDO!=null){
                    idNo=wlyyOutpatientDO.getIdcard();
                    patientName = wlyyOutpatientDO.getPatientName();
                    msgTime = sf.format(new Date());
                    sender ="ZJXL";
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("patientName",patientName);
                    jsonObject.put("idType",idType);
                    jsonObject.put("idNo",idNo);
                    jsonObject.put("doctorName",wlyyOutpatientDO.getDoctorName());
                    jsonObject.put("deptName",wlyyOutpatientDO.getDeptName());
                    jsonObject.put("visitTime",sf.format(wlyyOutpatientDO.getCreateTime()));
                    msgContent= jsonObject.toString();
                }

            }else if ("OL_WZ_START".equalsIgnoreCase(msgType)||"OL_WZ_END".equalsIgnoreCase(msgType)||"OL_YSTZ".equalsIgnoreCase(msgType)||"OL_JSTX".equalsIgnoreCase(msgType)){
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
                if (wlyyOutpatientDO!=null){
                    visitId = wlyyOutpatientDO.getRegisterNo();
                    if (StringUtils.isNoneBlank(prescriptionId)){
                        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
                        if(wlyyPrescriptionDO!=null){
                            msgId=wlyyPrescriptionDO.getVoucherNo();
                        }
                    }else {
                        msgId = wlyyOutpatientDO.getRegisterNo();
                    }
                    idNo=wlyyOutpatientDO.getIdcard();
                    patientName = wlyyOutpatientDO.getPatientName();
                    msgTime = sf.format(new Date());
                    sender ="ZJXL";
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("patientName",patientName);
                    jsonObject.put("idType",idType);
                    jsonObject.put("idNo",idNo);
                    jsonObject.put("doctorName",wlyyOutpatientDO.getDoctorName());
                    jsonObject.put("deptName",wlyyOutpatientDO.getDeptName());
                    jsonObject.put("visitTime",sf.format(wlyyOutpatientDO.getCreateTime()));
                    msgContent= jsonObject.toString();
                }

            } else if ("OL_JS_SUCCESS".equalsIgnoreCase(msgType)){
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
                if (wlyyOutpatientDO!=null){
                    visitId = wlyyOutpatientDO.getRegisterNo();
                    if (StringUtils.isNoneBlank(prescriptionId)){
                        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
                        if(wlyyPrescriptionDO!=null){
                            msgId=wlyyPrescriptionDO.getVoucherNo();
                        }
                    }else {
                        msgId = wlyyOutpatientDO.getRegisterNo();
                    }
                    idNo=wlyyOutpatientDO.getIdcard();
                    patientName = wlyyOutpatientDO.getPatientName();
                    msgTime = sf.format(new Date());
                    sender ="ZJXL";
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("patientName",patientName);
                    List<WlyyPrescriptionInfoDO> list=prescriptionInfoDao.findByPrescriptionId(prescriptionId,1);

                    String drugName="";
                    if (list!=null&&list.size()>0){
                        for (int i=0;i<list.size();i++){
                            if(i==0){
                                drugName = list.get(0).getDrugName();
                            }else {
                                drugName+=","+list.get(i).getDrugName();
                            }
                        }
                    }
                    jsonObject.put("drugsName",drugName);
                    msgContent= jsonObject.toString();
                }

            }

            return entranceService.zsMsgFlow(visitId,msgId,idType,idNo,patientName,msgTime,msgType,msgContent,jumpType,jumpUrl,"","",remark,sender);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }


    /*public void testHikar(){
        try{
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + dataSource.getPoolName() + ")");
            HikariPoolMXBean poolProxy = JMX.newMXBeanProxy(mBeanServer, poolName, HikariPoolMXBean.class);
            if(poolProxy == null) {
                System.out.println("Hikari not initialized,please wait...");
            }else {
                System.out.println("HikariPoolState = "
                        + "Active=[" + String.valueOf(poolProxy.getActiveConnections() + "] "
                        + "Idle=[" + String.valueOf(poolProxy.getIdleConnections() + "] "
                        + "Wait=["+poolProxy.getThreadsAwaitingConnection()+"] "
                        + "Total=["+poolProxy.getTotalConnections()+"]")));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }*/
    public String findDomainUrlInDict(){
        try {
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("domainUrl");
            if (wlyyHospitalSysDictDO!=null){
                return wlyyHospitalSysDictDO.getDictValue();
            }else {
                return "";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 获取患者待结算信息页面
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public JSONObject getSettlementInfo(String outpatientId) throws Exception {
        logger.info("获取患者待结算信息开始!");
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(outpatientId);
        if(outpatientDO==null){
            throw new Exception("门诊信息为空");
        }
        String registerNo = outpatientDO.getRegisterNo();
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("ylzConfigOrgCode");
        if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
            xzzxEntranceService.getSettleInfHospital(outpatientDO.getCardNo(),registerNo,sysDictDO.getDictValue());
        }
        logger.info("获取患者待结算信息结束!");
        logger.info("医保挂号开始!");
        String register = healthCareService.registerToEntrance(registerNo);
        logger.info("医保挂号结束!");
        logger.info("医保费用明细上传开始!");
        String feeDetailUpload= healthCareService.feeDetailUploadToEntrance(registerNo);
        logger.info("医保费用明细上传结束!");

        logger.info("医保预结算信息开始!");
        YlzMedicalRelationDO ylzMedicalRelationDO =  healthCareService.preSettlementToEntrance(registerNo);
        logger.info("医保预结算信息结束!");

        logger.info("获取医保结算页面地址开始!");
        String getSettlementResultUrl = healthCareService.getSettlementResultUrlToEntrance(registerNo);
        logger.info("获取医保结算页面地址结束!");
        JSONObject object = new JSONObject();
        object.put("register",register);
        object.put("feeDetailUpload",feeDetailUpload);
        object.put("preSettlement",ylzMedicalRelationDO);
        object.put("getSettlementResultUrl",getSettlementResultUrl);
        object.put("cardNo",outpatientDO.getCardNo());
        object.put("deptName",outpatientDO.getPatientName());
        return object;
    }


    /**
     * 医保结算页面
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String confirmSettlementInfo(String outpatientId,String code) throws Exception {
        logger.info("获取患者待结算信息开始!");
        String result = "";
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(outpatientId);
        if(outpatientDO==null){
            throw new Exception("门诊信息为空");
        }
        if (StringUtils.isNoneBlank(code)){
            logger.info("医保结算结果获取start！");
            result = healthCareService.getSettlementResult(code);
            logger.info("医保结算结果获取end！");

        }else{
            logger.info("医保结算页面start！");
            String registerNo = outpatientDO.getRegisterNo();
            result = healthCareService.getSettlementResultUrl(registerNo);
            logger.info("医保结算页面end！");
        }
        return result;
    }


    /**
     *
     * @param receiverType 1医生、2患者
     * @param oupatientId
     * @param sendType 1系统、2短信、3全部
     * @return
     */
    public String sendMessageManger(String receiver,String receiverType,String oupatientId,String businessType,String sendType){
        String msg = "";
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(oupatientId);
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(wlyyOutpatientDO.getDoctor());
        if (StringUtils.isNoneBlank(receiverType)&&receiver.equalsIgnoreCase("1")){
            if (sendType.equalsIgnoreCase("2")){
                ykyySMSService.sendSmsByTempcode("outpatient_remind",wlyyOutpatientDO,null,baseDoctorDO.getMobile());
            }else if (sendType.equalsIgnoreCase("1")){
                wxTempalteJPush("remind_doctor_pickup",wlyyOutpatientDO,null,"","","","");
            }else if (sendType.equalsIgnoreCase("3")){
                ykyySMSService.sendSmsByTempcode("outpatient_remind",wlyyOutpatientDO,null,baseDoctorDO.getMobile());
                wxTempalteJPush("remind_doctor_pickup",wlyyOutpatientDO,null,"","","","");
            }
        }else if (StringUtils.isNoneBlank(receiverType)&&receiver.equalsIgnoreCase("2")){
            if (sendType.equalsIgnoreCase("2")){
                ykyySMSService.sendSmsByTempcode("outpatient_remind",wlyyOutpatientDO,null,baseDoctorDO.getMobile());
            }else if (sendType.equalsIgnoreCase("1")){
                wxTempalteJPush("remind_doctor_pickup",wlyyOutpatientDO,null,"","","","");
            }else if (sendType.equalsIgnoreCase("3")){
                ykyySMSService.sendSmsByTempcode("outpatient_remind",wlyyOutpatientDO,null,baseDoctorDO.getMobile());
                wxTempalteJPush("remind_doctor_pickup",wlyyOutpatientDO,null,"","","","");
            }
        }
        return "成功";
    }


}
