Bläddra i källkod

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

huangwenjie 5 år sedan
förälder
incheckning
8674b7a4d3
15 ändrade filer med 5705 tillägg och 14 borttagningar
  1. 4962 0
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/YkyyPrescriptionService.java
  2. 155 10
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/YkyyEntranceService.java
  3. 4 0
      business/base-service/src/main/java/com/yihu/jw/utils/hibernate/HibenateUtils.java
  4. 3 2
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/HlwCf02DO.java
  5. 14 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/WlyyOutpatientDO.java
  6. 14 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/WlyyPrescriptionDO.java
  7. 28 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/WlyyPrescriptionInfoDO.java
  8. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderDO.java
  9. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderRefundDO.java
  10. 335 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/hospital/BaseHospitalRequestMapping.java
  11. 11 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyOutpatientVO.java
  12. 22 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyPrescriptionInfoVO.java
  13. 12 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyPrescriptionVO.java
  14. 121 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/prescription/YkyyPrescriptionEndpoint.java
  15. 22 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/ykyy/YkyyController.java

+ 4962 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/YkyyPrescriptionService.java

@ -0,0 +1,4962 @@
package com.yihu.jw.hospital.prescription.service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
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.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
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.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.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.httplog.WlyyHttpLogDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.entity.ylzinfo.OauthYlzConfigDO;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.consult.dao.HospitalWaitingRoomDao;
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.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.hospital.mapping.service.DoctorMappingService;
import com.yihu.jw.hospital.mapping.service.PatientMappingService;
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.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.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.WebserviceUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
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 jxl.write.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.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 java.io.IOException;
import java.io.OutputStream;
import java.lang.Boolean;
import java.util.*;
/**
 * Created by Trick on 2019/5/17.
 */
@Service
@Transactional
public class YkyyPrescriptionService extends BaseJpaService<WlyyPrescriptionDO, PrescriptionDao> {
    private static final Logger logger = LoggerFactory.getLogger(YkyyPrescriptionService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BasePatientMedicareCardDao basePatientMedicareCardDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    @Autowired
    private PrescriptionExpressageDao prescriptionExpressageDao;
    @Autowired
    private PrescriptionExpressageLogDao prescriptionExpressageLogDao;
    @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;
    @Value("${demo.flag}")
    private boolean demoFlag;
    /**
     * 获取居民就诊记录接口
     * @param patient
     * @param startTime
     * @param endTime
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public  List<WlyyOutpatientVO> findOutpatientList(String patient, String startTime, String endTime, boolean demoFlag)throws Exception{
        logger.info("findOutpatientList patient:"+patient);
        String patNo =patientMappingService.findHisPatNoByPatient(patient);
        if(StringUtils.isBlank(patNo)){
            return null;
        }
        logger.info("findOutpatientList patNo "+patNo);
        return entranceService.BS30025(patNo,null,startTime,endTime,demoFlag);
    }
    /**
     * 查询单条门诊记录
     * @param patient
     * @param conNo
     * @return
     */
    public WlyyOutpatientVO findOutpatientInfo(String patient,String conNo)throws Exception{
        logger.info("findOutpatientList patient:"+patient);
        String patNo =patientMappingService.findHisPatNoByPatient(patient);
        if(StringUtils.isBlank(patNo)){
            return null;
        }
        logger.info("findOutpatientList patNo:"+patNo);
        List<WlyyOutpatientVO> list = entranceService.BS30025(patNo,conNo,null,null,demoFlag);
        if(list!=null&&list.size()>0){
            WlyyOutpatientVO outpatientVO = list.get(0);
            BasePatientDO patientDO = basePatientDao.findById(patient);
            outpatientVO.setSex(patientDO.getSex()+"");
            outpatientVO.setBirthday(patientDO.getBirthday());
            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);
        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);
        return entranceService.BS16017(registerSn,realOrder,patNo,admNo,demoFlag);
    }
    /**
     * 获取单条处方记录
     * @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);
        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,Integer page,Integer size){
        String totalSql = "SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.patient = ? AND o.outpatient_type != '2' ";
        List<Object> totalParams = new ArrayList<>();
        totalParams.add(patient);
        if(status!=null){
            totalSql +=  " AND o.status = ? ";
            totalParams.add(status);
        }
        if(StringUtils.isNotBlank(startTime)){
            totalSql += " AND create_time >= ? ";
            totalParams.add(startTime+" 00:00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            totalSql += " AND create_time <= ? ";
            totalParams.add(endTime+" 23:59:59");
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql,totalParams.toArray());
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        String sql ="SELECT " +
                " o.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," +
                " o.hospital_name AS hospitalName," +
                " o.win_no AS winNo," +
                " o.type," +
                " 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.create_time AS createTime, " +
                " o.`status` AS `status`," +
                " o.register_date AS registerDate," +
                " o.evaluate_status AS evaluateStatus   " +
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.patient = ? ";
        List<Object> params = new ArrayList<>();
        params.add(patient);
        if(status!=null){
            sql +=  " AND o.status = ? ";
            params.add(status);
        }
        if(StringUtils.isNotBlank(startTime)){
            sql += " AND o.create_time >= ? ";
            params.add(startTime+" 00:00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            sql += " AND o.create_time <= ? ";
            params.add(endTime+" 23:59:59");
        }
        sql += " AND o.outpatient_type != '2' ORDER BY o.create_time DESC LIMIT " + (page - 1) * size + "," + size + " ";
        List<WlyyOutpatientVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyOutpatientVO.class),params.toArray());
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }
    /**
     * 获取单条复诊记录信息
     * @param outpatientId
     * @return
     */
    public com.alibaba.fastjson.JSONObject findReOutpatientInfo(String outpatientId,String prescriptionId){
        com.alibaba.fastjson.JSONObject rs = new com.alibaba.fastjson.JSONObject();
        //复诊信息
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        rs.put("outpatient",convertToModel(outpatientDO,WlyyOutpatientVO.class));
        //居民详情
        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"));
        //获取处方信息
        List<WlyyPrescriptionDO> prescriptionDOs = null;
        if(StringUtils.isNotBlank(prescriptionId)){
            prescriptionDOs = prescriptionDao.findById(prescriptionId);
        }else{
            prescriptionDOs = prescriptionDao.findByOutpatientId(outpatientId);
        }
        List<WlyyPrescriptionVO> prescriptionVOs = new ArrayList<>();
        if(prescriptionDOs!=null&&prescriptionDOs.size()>0){
            convertToModels(prescriptionDOs,prescriptionVOs,WlyyPrescriptionVO.class);
            for(WlyyPrescriptionVO vo:prescriptionVOs){
                //疾病信息
                vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                //药品信息
                List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                vo.setInfoVOs(convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId()),infoVOs,WlyyPrescriptionInfoVO.class));
                //检查检验信息
                List<WlyyInspectionVO> inspectionVOs = new ArrayList<>();
                vo.setInspectionVOs(convertToModels(wlyyInspectionDao.findByPrescriptionId(vo.getId()),inspectionVOs,WlyyInspectionVO.class));
            }
        }
        rs.put("prescriptions",prescriptionVOs);
        //物流信息
        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);
        }
        //预约记录
        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 totalSql ="SELECT " +
                " count(1) AS total " +
                " FROM " +
                " wlyy_prescription p ";
        totalSql += " WHERE 1=1 ";
        if(StringUtils.isNotBlank(patient)){
            totalSql+=" AND p.patient_code ='"+patient+"'";
        }
        if(StringUtils.isNotBlank(status)){
            totalSql+=" AND p.status IN ("+status+")";
        }
        if(StringUtils.isNotBlank(startTime)){
            totalSql += " AND create_time >='"+startTime+" 00:00:00'";
        }
        if(StringUtils.isNotBlank(endTime)){
            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) rstotal.get(0).get("total");
        }
        String sql ="SELECT " +
                " p.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 1=1 ";
        if(StringUtils.isNotBlank(patient)){
            sql+=" AND p.patient_code ='"+patient+"'";
        }
        if(StringUtils.isNotBlank(status)){
            sql+=" AND p.status IN ("+status+")";
        }
        if(StringUtils.isNotBlank(startTime)){
            sql += " AND create_time >='"+startTime+" 00:00:00'";
        }
        if(StringUtils.isNotBlank(endTime)){
            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()),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);
        List<WlyyPrescriptionDiagnosisVO> rs = new ArrayList<>();
        if(list!=null&&list.size()>0){
            return convertToModels(list,rs,WlyyPrescriptionDiagnosisVO.class);
        }
        return rs;
    }
    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()));
        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
     */
    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());
        outpatientDO.setMjz("mz");
        outpatientDO.setStatus("0");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setIdcard(patientDO.getIdcard());
        outpatientDO.setOutpatientType("1");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setPayStatus(0);
        if(outpatientDO.getRegisterDate()==null){
            outpatientDO.setRegisterDate(new Date());
        }
        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        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("号源已经被预约,请选择其他号源");
        }
        //2.物流信息
        WlyyPrescriptionExpressageDO expressageDO = objectMapper.readValue(expressageJson,WlyyPrescriptionExpressageDO.class);
        expressageDO.setDel(1);
        expressageDO.setCreateTime(new Date());
        expressageDO.setOutpatientId(outpatient.getId());
        prescriptionExpressageDao.save(expressageDO);
        //3.创建候诊室
        createRoom(outpatient,chargeType);
        return outpatient;
    }
    /**
     * 创建候诊室
     * @param outpatientDO
     * @return
     */
    public Boolean createRoom(WlyyOutpatientDO outpatientDO,String chargeType){
        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())){
            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");
                if("激活".equals(cardStat)){
                    rs.add(card);
                }
            }
        }
        return rs;
    }
    public Map<String,Object> checkOutpatient(String patient)throws Exception{
        //-1卡余额不足,,-2 存在未结束的诊断热 1成功
        Map<String,Object> rs = new HashedMap();
        //1.余额判断改到前端判断
        //net.sf.json.JSONObject json = entranceService.qutpatientBalance(cardNo,demoFlag);
        //2.判断是否有未结束的
        List<WlyyOutpatientDO> list = outpatientDao.findByPatientList(patient);
        if(list!=null&&list.size()>0){
            rs.put("outpatient",list.get(0));
            rs.put("code",-2);
            rs.put("mes","存在未结束的诊断");
            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\"" +
                " 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)) {
            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("findDoctorByHospitalAndDept 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 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)) {
            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\"" +
                " 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)) {
            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);
                doctor.put("workTime", times);
            }
            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) {
        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<>();
            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()));
                    }
                }
            }
            return timeVOs;
        }
        return null;
    }
    /**
     * 查询医生列表带月份排班状态
     *
     * @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'";
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equals(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'";
        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(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 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.findByPatientAndDateAndDoctor(outpatientDO.getPatient(), date, doctor);
        if (patientRegisterDOs != null && patientRegisterDOs.size() > 0) {
            WlyyPatientRegisterDO registerDO = patientRegisterDOs.get(0);
            //判断是否已经挂号,如果已经挂号
            if (StringUtils.isNotBlank(registerDO.getConNo()) && StringUtils.isNotBlank(registerDO.getRegisterNo())) {
                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());
                outpatientDao.save(outpatientDO);
                //调用电子病历注册
                manageType = 2;
                registDianziBingli(outpatientDO, basePatientDO, manageType, registerDO.getRegisterNo(), registerDO.getConNo());
                return res;
            }
        }
        JSONObject rs = entranceService.BS10111(outpatientDO.getCardNo(), doctorMappingDO.getMappingCode(), outpatientDO.getDept(), null, outpatientDO.getWinNo(), demoFlag);
        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);
            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.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());
        } else if ("-2".equals(rsCode)) {
            String serialNo = (String) res.get("@serial_no");
            outpatientDO.setRegisterNo(serialNo);
            String conNo = (String) res.get("@times");
            outpatientDO.setConNo(conNo);
            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.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 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 (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 advice, String type, String infoJsons, String diagnosisJson, String inspectionJson) throws Exception {
        Map<String, Object> result = new HashedMap();
        //获取门诊记录
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outPatientId);
        //设置医嘱
        outpatientDO.setAdvice(advice);
        //========================处方操作=============================================================
        //创建处方记录
        List<WlyyPrescriptionDO> prescriptionDOs = prescriptionDao.findByOutpatientId(outPatientId);
        WlyyPrescriptionDO prescriptionDO = null;
        if (prescriptionDOs != null && prescriptionDOs.size() > 0) {
            prescriptionDO = prescriptionDOs.get(0);
        } else {
            prescriptionDO = new WlyyPrescriptionDO();
            prescriptionDO.setOutpatientId(outPatientId);
        }
        prescriptionDO.setCreateTime(new Date());
        prescriptionDO.setStatus(10);
        prescriptionDO.setPatientCode(outpatientDO.getPatient());
        prescriptionDO.setPatientName(outpatientDO.getPatientName());
        prescriptionDO.setDoctor(outpatientDO.getDoctor());
        prescriptionDO.setDoctorName(outpatientDO.getDoctorName());
        WlyyPrescriptionDO prescription = prescriptionDao.save(prescriptionDO);
        //========================处方操作结束=============================================================
        //加入处方状态变更流水日志
        prescriptionLogService.addPrescriptionLog(prescription.getId(), 10, 2, outpatientDO.getDoctor(), outpatientDO.getDoctorName(), "", new Date());
        //============================下诊断==============================================================
        //删除之前诊断
        List<WlyyPrescriptionDiagnosisDO> ds = prescriptionDiagnosisDao.findByPrescriptionId(prescription.getId());
        if (ds != null && ds.size() > 0) {
            prescriptionDiagnosisDao.delete(ds);
        }
        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.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==============================================================
        //判断是否有检查检验或药品开方
        if ("1".equals(type)) {
            //doctor转换为his医生
            DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
            if (doctorMappingDO == null) {
                throw new RuntimeException("未找到医生映射信息");
            }
            //his处方拼接开方条件
            com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
            //===================药品操作======================================================
            // 删除原有药品信息
            List<WlyyPrescriptionInfoDO> oldInfos = prescriptionInfoDao.findByPrescriptionId(prescription.getId());
            if (oldInfos != null && oldInfos.size() > 0) {
                prescriptionInfoDao.delete(oldInfos);
            }
            //存储药品,构建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());
                    //设置his药品查询条件
                    setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, info, Icd10);
                }
                //保存药品信息
                prescriptionInfoDao.save(infoDOs);
                //计算药品费用
                prescription.setDrugFee(getInfoFee(infoDOs));
            }
            //=====================药品操作=======================================================================
            //=====================检查检验=======================================================================
            //存储检查检验,构建his开方入参
            //删除之前检查检验
            List<WlyyInspectionDO> inspectionDels = wlyyInspectionDao.findByOutpatientId(outPatientId);
            if (inspectionDels != null && inspectionDels.size() > 0) {
                wlyyInspectionDao.delete(inspectionDels);
            }
            if (StringUtils.isNotBlank(inspectionJson)) {
                List<WlyyInspectionDO> inspections = (List<WlyyInspectionDO>) com.alibaba.fastjson.JSONArray.parseArray(inspectionJson, WlyyInspectionDO.class);
                for (WlyyInspectionDO ins : inspections) {
                    ins.setCreateTime(new Date());
                    ins.setPrescriptionId(prescription.getId());
                    ins.setOutpatientId(outPatientId);
                    //设置his药品查询条件
                    setInspectionParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, ins, Icd10);
                }
                //保存检查检验。
                wlyyInspectionDao.save(inspections);
                //计算检查检验费用
                prescription.setDrugFee(getInsFee(inspections));
            }
            //=====================检查检验=======================================================================
            //保存挂号费用
            prescription.setRegFee(getChargeFee(outpatientDO.getDoctor()));
            //保存费用
            prescriptionDao.save(prescription);
            //上传his开方
            return sendHisDiagnosis(jsonData, outpatientDO, prescription);
        } else {
            outpatientDO.setStatus("2");
            outpatientDao.save(outpatientDO);
            result.put("code", 1);
            result.put("mes", "诊断完成");
            return result;
        }
    }
    /**
     * 计算药品费用
     *
     * @param infoDOs
     * @return
     */
    public Double getInfoFee(List<WlyyPrescriptionInfoDO> infoDOs) {
        Double fee = 0D;
        try {
            if (infoDOs != null && infoDOs.size() > 0) {
                for (WlyyPrescriptionInfoDO info : infoDOs) {
                    Integer quantity = Integer.parseInt(info.getQuantity());
                    fee += info.getPackRetprice() * quantity;
                }
            }
        } catch (Exception e) {
            logger.error("getInfoFee:" + e.toString());
        }
        return fee;
    }
    /**
     * 计算检查检验费用
     *
     * @param inspections
     * @return
     */
    public Double getInsFee(List<WlyyInspectionDO> inspections) {
        Double fee = 0D;
        try {
            if (inspections != null && inspections.size() > 0) {
                for (WlyyInspectionDO ins : inspections) {
                    Double chargeAmount = Double.parseDouble(ins.getChargeAmount());
                    fee += chargeAmount * ins.getQuantity();
                }
            }
        } catch (Exception e) {
            logger.error("getInsFee:" + e.toString());
        }
        return fee;
    }
    /**
     * 计算挂号费用
     *
     * @param doctor
     * @return
     */
    public Double getChargeFee(String doctor) {
        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());
        }
        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开方接口
        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");
            prescription.setAdmNo(admNo);
            prescription.setRealOrder(realOrder);
            prescriptionDao.save(prescription);
            outpatientDO.setAdmNo(admNo);
            outpatientDao.save(outpatientDO);
            result.put("code", 1);
            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 findExpressageList(String status, String oneselfPickupFlg, String nameKey, String startTime, String endTime, Integer page, Integer size) {
        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(startTime)) {
            totalSql += " AND e.create_time >='" + startTime + " 00:00:00'";
        }
        if (StringUtils.isNotBlank(endTime)) {
            totalSql += " AND e.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) rstotal.get(0).get("total");
        }
        String sql = "SELECT " +
                " e.create_time AS createTime, " +
                " e.`name`, " +
                " e.oneself_pickup_flg AS oneselfPickupFlg, " +
                " o.id AS outpatientId, " +
                " o.icd10_name AS icd10Name, " +
                " p.`status`, " +
                " p.id AS prescriptionId ," +
                " e.id AS expressageId" +
                " 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(startTime)) {
            sql += " AND e.create_time >='" + startTime + " 00:00:00'";
        }
        if (StringUtils.isNotBlank(endTime)) {
            sql += " AND e.create_time <='" + endTime + " 23:59:59'";
        }
        sql += " LIMIT " + (page - 1) * size + "," + size + "";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        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;
            for (Map<String, Object> m : ls) {
                addCell(ws, i, 0, DateUtil.dateToStr((Date) m.get("createTime"), "yyyy-MM-dd HH:mm:ss"), "");
                addCell(ws, i, 1, (String) m.get("name"), "");
                addCell(ws, i, 2, (String) m.get("icd10Name"), "");
                addCell(ws, i, 3, getOneselfPickupFlgString((Integer) m.get("oneselfPickupFlg")), "");
                addCell(ws, i, 4, getStatusName((Integer) m.get("status")), "");
                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 = wlyyChargeDictDao.findByDeptTypeCode(deptTypeCode);
        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 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){
        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("jobTitleCode",doctorDO.getJobTitleCode());
            rs.put("jobTitleName",doctorDO.getJobTitleName());
            rs.put("chargeType",doctorDO.getChargeType());
            rs.put("photo",doctorDO.getPhoto());
            rs.put("consultStatus",doctorDO.getConsultStatus());
            rs.put("outpatientType",doctorDO.getOutpatientType());
            rs.put("expertise",doctorDO.getExpertise());
            rs.put("introduce",doctorDO.getIntroduce());
            rs.put("consultStatus",doctorDO.getConsultStatus());// 咨询在线状态
            //机构科室信息
            List<BaseDoctorHospitalDO> hospitalDOs =  baseDoctorHospitalDao.findByDoctorCode(doctorDO.getId());
            if(hospitalDOs!=null&&hospitalDOs.size()>0){
               rs.put("hospital",hospitalDOs.get(0));
               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);
            }
            //医生角色
            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.findByDoctorAndStatus(doctor,"2");
//            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);
            //专家咨询
            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";
            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)_listscore.get("score");
                }
            }
            doctorScore = doctorScore/3;
            rs.put("doctorScore",doctorScore);
            if(listscore!=null&&listscore.size()>0){
                rs.put("scoreDoctor",listscore);
            }else{
                rs.put("scoreDoctor",null);
            }
            //查询评价明细
            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+"' ";
            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);
                        }
                    }
                }
                rs.put("scoreList",waitinglist);
            }else{
                rs.put("scoreList",null);
            }
        }
        return rs;
    }
    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());// 咨询在线状态
            //机构科室信息
            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());
                if(org!=null){
                    rs.put("winNo",org.getWinNo());
                    rs.put("deptName",hospitalDOs.get(0).getDeptName());
                    rs.put("deptCode",hospitalDOs.get(0).getDeptCode());
                }
            }else{
                rs.put("hospital",null);
                rs.put("winNo",null);
                rs.put("deptName",null);
                rs.put("deptCode",null);
            }
            //多科室兼容
            rs.put("hospitalList",hospitalDOs);
            //医生角色
            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);
            }
            //密码过期
            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){
        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");
        if (1 == operator){
            //居民取消
            wlyyOutpatientDO.setPatientCancelRemark(cancelRemark);
            wlyyOutpatientDO.setPatientCancelType(cancelType);
            wlyyOutpatientDO.setPatientCancelValue(cancelValue);
        }else{
            //医生拒绝接诊
            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;
    }
    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:视频诊室(视频复诊、协同门诊)
     * @query_status 0:图文复诊候诊 1:图文复诊抢单列表
     * @dept 部门
     * @return
     */
    public List<Map<String,Object>> findWaitingRoomOutpatientByDoctor(String doctor, Integer type,Integer query_status,String dept) {
        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," +
                "outpatient.mobile AS mobile," +
                "patient.birthday AS birthday," +
                "room.consult_type AS consult_type," +
                "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS timedate_format," +
                "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.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{
            //在线复诊
            sql += " AND room.reservation_type=1 AND room.consult_type="+type ;
        }
        if(StringUtils.isNoneBlank(dept)){
            sql += " AND outpatient.dept='"+dept+"' ";
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
            //根据身份证计算年龄
            for(Map<String,Object> outpatient :list){
                String idcard = (String)outpatient.get("idcard");
                outpatient.put("age",DateUtil.getAgeForIdcard(idcard));
            }
        }
        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 totalSql = "SELECT count(id) AS total FROM wlyy_hospital_waiting_room WHERE visit_status=1 ";
        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) {
        if(StringUtils.isBlank(date)){
            date = DateUtil.getStringDateShort();
        }
        //获取今天的排班列表
        String doctorsql ="SELECT doctor,doctor_name,dept,dept_name FROM wlyy_doctor_work_time WHERE date='"+date+"'";
        if(StringUtils.isNoneBlank(dept)){
            doctorsql = doctorsql + " and dept = '"+dept+"' ";
        }
        doctorsql = doctorsql+ " GROUP BY doctor";
        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("waiting_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+"' ";
        }
        waitingSql = waitingSql + "AND room.reservation_time>='"+date+" 00:00:00' AND room.reservation_time<='"+date+" 23:59:59' GROUP BY room.doctor; ";
        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) waitObj.get("waitCount");
                    if(result.keySet().contains(doctor)){
                        result.get(doctor).put("waiting_count",waitCount);
                    }else{
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id",doctor);
                        jsonObject.put("visit_status",1);
                        jsonObject.put("waiting_count",waitCount);
                        if(StringUtils.isNoneBlank((String)waitObj.get("doctorName"))){
                            jsonObject.put("doctor_name",(String)waitObj.get("doctorName"));
                        }else{
                            jsonObject.put("doctor_name","");
                        }
                        jsonObject.put("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," +
                "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS time," +
                "TIMESTAMPDIFF(MINUTE, room.reservation_time,NOW()) AS time_cost," +
                "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";
        List<Map<String,Object>> onlinelist = jdbcTemplate.queryForList(onlineSql);
        if(onlinelist!=null&&onlinelist.size()>0){
            //根据身份证计算年龄
            for(Map<String,Object> onlineObj :onlinelist){
                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) onlineObj.get("time_cost"));
                    }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) onlineObj.get("time_cost"));
                        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
     */
    public List<Map<String,Object>> findDoctorByHospitalAndDiseaseAndDept(String iswork,String patientid,String orgCode, String dept,
                                                                          String diseaseKey, String doctorNameKey,
                                                                          String jobTitleNameKey, String outpatientType,
                                                                          String keyName, String workingTime, String consultStatus,String chargType,String consutlSort,Integer page,Integer pagesize) {
      /*  if(page >=1){
            page --;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }*/
        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\"," +
                " d.consult_status AS \"consultStatus\"," +
                " d.outpatient_type AS \"outpatientType\"," +
                " a.total AS \"consultTotal\"," +
                " h.org_name AS \"orgName\"," +
                " follow.patient AS \"followid\"," +
                " h.org_code AS \"orgCode\"" +
                " FROM " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id "+
                " Left join base_doctor_patient_follow follow on follow.doctor = d.id and follow.patient='"+patientid+"'"+
                " Left join ( select count(id) as total,doctor from wlyy_outpatient where status = 2 GROUP BY doctor ) a on a.doctor = d.id ";
        if(StringUtils.isNotBlank(workingTime)){
            sql+=" JOIN wlyy_doctor_work_time wk on wk.doctor = d.id ";
        }
        sql +=  " WHERE  1=1 ";
        Map<String, Object> params = new HashedMap();
        if(StringUtils.isBlank(chargType)){
            sql +=" AND d.charge_type is not null ";
        }
        if(StringUtils.isNotBlank(chargType)){
            if("all".equals(chargType)){
                //不过滤
            }else{
                sql+=" AND d.charge_type = :chargType";
                params.put("chargType",chargType);
            }
        }
        if(StringUtils.isNotBlank(iswork)&&"1".equals(iswork)){
            logger.info("iswork:"+iswork);
            Date date = new Date();
            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 d.expertise 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.date = :workingTime ";
            params.put("workingTime",workingTime);
        }
        if(StringUtils.isNotBlank(consultStatus)){
            sql+=" AND d.consult_status = :consultStatus ";
            params.put("consultStatus",consultStatus);
        }
        sql += " and d.del='1' order by a.total "+ consutlSort;
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params,page,pagesize);
        logger.info("findDoctorByHospitalAndDiseaseAndDept end:"+DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss:SSS"));
        logger.info("sql:"+sql);
        return list;
    }
    /**
     * 获取常见疾病、热门部门、医生拒绝接诊原因 字典
     * @param dictName 字典名称
     * @return
     */
    public List<Map<String,Object>> findHotDeptAndDiseaseDict(String dictName) {
        String sql ="SELECT * from wlyy_hospital_sys_dict where dict_name='"+dictName+"' ORDER BY sort ASC";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(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;
    }
    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());
                    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 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);
        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());
        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 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," +
                "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) 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 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));
                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 com.alibaba.fastjson.JSONArray getWaitingForVisitVideoPrescriptionByDoctor(String doctor) {
        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," +
                "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS time," +
                "date_format(room.reservation_time ,'%Y-%m-%d' ) AS group_date," +
                "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 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"+"' ";
        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));
                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);
    }
    /**
     * 复诊视频咨询人数, 协同门诊人数
     * @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) rstotal.get(0).get("total");
        }
        return videoOnlineCount;
    }
    /**
     * 根据门诊唯一号,处方号,到顺丰下单,下单成功返回面单信息
     * @param admNo 门诊唯一号
     * @param realOrder 处方号
     * @return
     */
    public Object getSFExpressInfo(String admNo,String realOrder)throws Exception {
        //根据门诊唯一号取就诊记录
        List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByAdmNo(admNo);
        Object result = "";
        if(!wlyyOutpatientDOs.isEmpty() && wlyyOutpatientDOs.size()>0){
            List<WlyyPrescriptionExpressageDO> expressageDOList = sfexpressService.findByField("outpatientId",wlyyOutpatientDOs.get(0).getId());
            WlyyPrescriptionExpressageDO sfexpress_obj = null;
            if(CollectionUtils.isEmpty(expressageDOList)){
                throw new Exception("顺丰快递下单失败,未找到该处方的派送地址!");
            }else{
                sfexpress_obj = expressageDOList.get(0);
                //如果该处方的快递单号已生成,则说明已经下单成功,不需要重复下单,直接返回面单信息
                if(org.apache.commons.lang.StringUtils.isNotBlank(sfexpress_obj.getMailno())){
                    //处方已下单成功
                }else{
                    //如果该处方的快递单号未生成,则继续下单
                    //根据业务订单号判断是否已经下单成功
                    boolean go_on = sfexpressService.sfOrderSearchService(sfexpress_obj);
                    //如果该业务订单号未下单成功过,则重新下单
                    if(go_on){
                        //请求顺丰接口下单,成功下单后,返回快递单号
                        sfexpress_obj = sfexpressService.postSFOrderService(sfexpress_obj);
                        //保存快递单号和增加处方物流记录为配送
                        sfexpressService.updatePrescriptionExpressage(sfexpress_obj);
                    }
                }
                if(sfexpress_obj != null && StringUtils.isNoneBlank(sfexpress_obj.getMailno())){
                    com.alibaba.fastjson.JSONObject sfJsonObject = new com.alibaba.fastjson.JSONObject();
                    sfJsonObject.put("mailno", sfexpress_obj.getMailno());
                    sfJsonObject.put("mailtype", "标准快递");
                    sfJsonObject.put("destcode", "592");
                    sfJsonObject.put("j_name", "厦门大学附属中山医院");
                    sfJsonObject.put("j_provinceName", "福建省");
                    sfJsonObject.put("j_cityName", "厦门市");
                    sfJsonObject.put("j_townName", "思明区");
                    sfJsonObject.put("j_address", "湖滨南路201-209号");
                    sfJsonObject.put("j_phone", "4003008888");
                    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;
                }
            }
        }
        return result;
    }
    /**
     * 根据类型获取候诊居民数量
     * @param doctor
     * @param outpatient_type 1复诊  2协同
     * @param type 1图文 2视频
     * @return
     */
    public Long getWaitVideoCount(String doctor,String type,String outpatient_type) {
        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) " +
                "AND outpatient.doctor='"+doctor+"' " +
                "AND outpatient.outpatient_type= '"+outpatient_type+"' ";
        if("1".equals(outpatient_type)){//复诊
            sql =  sql + " AND outpatient.type= '"+type+"' ";
            if("2".equals(type)){//视频复诊才需要判断时间,
                sql =  sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
            }
        }else if("2".equals(outpatient_type)){
            //协同门诊也需要判断时间
            sql =  sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        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());
        if(outpatientDO.getRegisterDate()==null){
            outpatientDO.setRegisterDate(new Date());
        }
        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        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){
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        try{
            //1.在线复诊2.协同门诊
            if("2".equals(outpatient.getOutpatientType())){
                systemMessageDO.setTitle("协同门诊");
                systemMessageDO.setType("3");
            }else{
                //1.图文 2.视频
                if("1".equals(outpatient.getType())){
                    systemMessageDO.setTitle("图文复诊");
                    systemMessageDO.setType("1");
                }else {
                    systemMessageDO.setTitle("视频复诊");
                    systemMessageDO.setType("2");
                }
            }
            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("question",outpatient.getDescription());
            systemMessageDO.setData(data.toString());
            systemMessageService.saveMessage(systemMessageDO);
        }catch (Exception e){
            logger.error("sendOutPatientMes :"+e.toString());
            return null;
        }
        return systemMessageDO;
    }
    /**
     * 指定门诊医生医生
     * @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())){
            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());
        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);
            }
        }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.setChargeType(chargeType);
            }
            hospitalWaitingRoomDao.save(roomDOs);
        }
        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);
                        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 sqlTotal ="SELECT " +
                " count(1) AS total "+
                " FROM " +
                " wlyy_outpatient o " +
                " WHERE " +
                " o.general_doctor = '"+generalDoctor+"'";
        if(StringUtils.isNotBlank(startDate)){
            sqlTotal += " AND o.register_date >='"+startDate+" 00:00:00' ";
        }
        if(StringUtils.isNotBlank(endDate)){
            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) rstotal.get(0).get("total");
        }
        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)){
            sql+=" AND o.register_date >='"+startDate+" 00:00:00'";
        }
        if(StringUtils.isNotBlank(endDate)){
            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+" LIMIT " + (page - 1) * size + "," + size + "";
        }else{
            sql += " ORDER BY o.register_date ASC LIMIT " + (page - 1) * size + "," + size + "";
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        //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) oltotal.get(0).get("total");
        }
        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.dept='"+dept+"' ";
        List<Map<String, Object>> alltotal = jdbcTemplate.queryForList(sqlAll);
        Long totalsqlAll = 0l;
        if (alltotal != null && alltotal.size() > 0) {
            totalsqlAll = (Long) alltotal.get(0).get("total");
        }
        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 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) imgtotal.get(0).get("total");
        }
        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 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) sptotal.get(0).get("total");
        }
        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 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) xttotal.get(0).get("total");
        }
        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 sql ="SELECT date_format(p.register_date ,'%Y-%m-%d %H:%i:%S' ) AS time,d.NAME as doctorName,d.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 AND p.register_date 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 JSONObject setRecord(String json,String type)throws Exception{
        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());
            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);
        }
       return entranceService.BS10008(idcard,patientId,admitNum,ybcard,demoFlag);
    }
    /**
     * 获取医生信息
     * @param hospital
     * @param name
     * @return
     */
    public List<Map<String,Object>> findDoctorByName(String hospital, String name,String chargeType){
        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(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(patientid,doctorid);
        if("1".equals(type)){//关注
            if(list.isEmpty()){
                BaseDoctorPatientFollowDO baseOrgPatientFollowDO = new BaseDoctorPatientFollowDO();
                baseOrgPatientFollowDO.setDoctor(doctorid);
                baseOrgPatientFollowDO.setPatient(patientid);
                baseOrgPatientDao.save(baseOrgPatientFollowDO);
            }
        }else if("0".equals(type)){//取消关注
            if(!list.isEmpty()){
                for (BaseDoctorPatientFollowDO baseOrgPatientFollowDO:list){
                    baseOrgPatientDao.delete(baseOrgPatientFollowDO.getId());
                }
            }
        }else{}
    }
    
    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);
    }
}

+ 155 - 10
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/YkyyEntranceService.java

@ -3,6 +3,8 @@ package com.yihu.jw.hospital.prescription.service.entrance;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.webkit.dom.CSSStyleRuleImpl;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
@ -16,9 +18,7 @@ import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateDao;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateScoreDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
@ -27,23 +27,28 @@ import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.security.MD5;
import com.ylzinfo.ehc.common.utils.DateUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.io.IOException;
import java.util.*;
/**
 * 眼科医院专用service
@ -58,6 +63,8 @@ public class YkyyEntranceService {
    private final static String url="http://192.168.20.55:10023/ykyy/createSQLQuery";
    private final static String saveUrl="http://192.168.20.55:10023/ykyy/save";
    private final static String orgCode ="350211A5004";
    private final static String orgName ="厦门大学附属厦门眼科中心";
@ -83,9 +90,6 @@ public class YkyyEntranceService {
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private OutpatientDao outpatientDao;
@ -101,6 +105,12 @@ public class YkyyEntranceService {
    @Autowired
    private BaseEvaluateDao baseEvaluateDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private ObjectMapper objectMapper;
    public List<Map<String, Object>> createSQLQuery(String sql, Map<String, Object> params, Integer page, Integer size){
        return hibenateUtils.createSQLQuery(sql,params,page,size);
@ -557,4 +567,139 @@ public class YkyyEntranceService {
        BasePatientDO patientDO = basePatientDao.findById(patientMappingDO.getPatient());
        return patientDO;
    }
    public List<Map<String,Object>> findYkYpxx(String ypdm,String ypmc,String kusl){
        String sql ="SELECT yp.ypxh AS \"ypxh\", yp.ypdm AS \"ypdm\", yp.ypmc AS \"ypmc\", yp.yfgg AS \"yfgg\"," +
                "yp.yfdw AS \"yfdw\"," +
                "yp.yfbz AS \"yfbz\"," +
                "yp.ypsx AS \"ypsx\"," +
                "yp.ypjl AS \"ypjl\"," +
                "yp.jldw AS \"jldw\"," +
                "yp.pydm AS \"pydm\"," +
                "yp.fyfs AS \"fyfs\"," +
                "yp.gyff AS \"gyff\"," +
                "yp.yfzf AS \"yfzf\"," +
                "yp.ybfl AS \"ybfl\"," +
                "yp.lsjg AS \"lsjg\"," +
                "yp.kcsl AS \"kcsl\"," +
                "yp.ypcd AS \"ypcd\"," +
                "yp.zfpb AS \"zfpb\"," +
                "yp.jbywbz AS \"jbywbz\"," +
                "yp.ydyp AS \"ydyp\"," +
                "yp.ypmc2 AS \"ypmc2\" FROM" +
                "V_ZKSG_MZ_YPXX yp where 1=1 ";
        if (StringUtils.isNoneBlank(ypdm)){
            sql+=" and yp.ypdm like '%"+ypdm+"%' ";
        }
        if (StringUtils.isNoneBlank(ypmc)){
            sql+=" and yp.ypmc like '%"+ypmc+"%' ";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }
    public String findByRealOrder(String code) throws Exception {
        List<WlyyPrescriptionDO>  wlyyPrescriptionDOs = prescriptionDao.findByPatientCode(code);
        if (wlyyPrescriptionDOs!=null&&wlyyPrescriptionDOs.size()!=0){
            WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOs.get(0);
            JSONObject objectString = (JSONObject) JSONObject.toJSON(wlyyPrescriptionDO);
            WlyyPrescriptionVO prescriptionVO =  JSONObject.toJavaObject(objectString,WlyyPrescriptionVO.class);
            List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId());
            List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
            for (WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO:wlyyPrescriptionInfoDOS){
                JSONObject object = (JSONObject) JSONObject.toJSON(wlyyPrescriptionInfoDO);
                WlyyPrescriptionInfoVO prescriptionInfoVO = JSONObject.toJavaObject(object,WlyyPrescriptionInfoVO.class);
                wlyyPrescriptionInfoVOS.add(prescriptionInfoVO);
            }
            prescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
            synPrecriptionHis(prescriptionVO);
        }
        return null;
    }
    public WlyyPrescriptionVO synPrecriptionHis(WlyyPrescriptionVO wlyyPrescriptionVO) throws Exception {
        HlwCf01DO hlwCf01DO = new HlwCf01DO();
        if (wlyyPrescriptionVO!=null){
            hlwCf01DO.setSPZT(0);
            hlwCf01DO.setFKZT(wlyyPrescriptionVO.getPayStatus());
            hlwCf01DO.setYFSB(3);
            hlwCf01DO.setCFLX(wlyyPrescriptionVO.getType());
            hlwCf01DO.setKFRQ(DateUtil.strToDate(DateUtil.dateToStr(wlyyPrescriptionVO.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));
            hlwCf01DO.setZFPB(1);
            hlwCf01DO.setFYBZ(0);
            hlwCf01DO.setPYBZ(0);
            hlwCf01DO.setDJYBZ(0);
            hlwCf01DO.setCFTS(1);
            hlwCf01DO.setCFSB(Integer.parseInt(wlyyPrescriptionVO.getRealOrder()));
            hlwCf01DO.setYXPB(1);
            hlwCf01DO.setSCDDH(wlyyPrescriptionVO.getOrderNo());
            String patient = wlyyPrescriptionVO.getPatientCode();
            PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patient);
            hlwCf01DO.setBRID(Integer.parseInt(patientMappingDO.getMappingCode()));
            hlwCf01DO.setBRXM(wlyyPrescriptionVO.getPatientName());
            hlwCf01DO.setKSDM(Integer.parseInt(wlyyPrescriptionVO.getDept()));
            String doctor = wlyyPrescriptionVO.getDoctor();
            DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
            hlwCf01DO.setYSDM(doctorMappingDO.getMappingCode());
            hlwCf01DO.setJZKH(wlyyPrescriptionVO.getSsc());
            hlwCf01DO.setGUID(getCode());
            hibenateUtils.save(hlwCf01DO);
           /* String jsonString = JSONObject.toJSONString(hlwCf01DO);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","HLW_CF01");
            logger.info("HLW_CF01:"+jsonString);
            HttpResponse response = HttpUtils.doGet(url,params);
            if (response.getStatus()==200){
                logger.info("表HLW_CF01同步成功!");
            }else {
                logger.info("表HLW_CF01同步失败!"+response.getErrorMsg());
            }*/
            List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS =wlyyPrescriptionVO.getInfoVOs();
            for (WlyyPrescriptionInfoVO wlyyPrescriptionInfoVO:wlyyPrescriptionInfoVOS){
                HlwCf02DO hlwCf02DO = new HlwCf02DO();
                hlwCf02DO.setCFSB(Integer.parseInt(wlyyPrescriptionVO.getRealOrder()));
                hlwCf02DO.setYPXH(Integer.parseInt(wlyyPrescriptionInfoVO.getDrugNo()));
                hlwCf02DO.setYPCD(Integer.parseInt(wlyyPrescriptionInfoVO.getDrugPlace()));
                hlwCf02DO.setXMLX(1);
                hlwCf02DO.setCFTS(1);
                hlwCf02DO.setYPSL(Integer.parseInt(wlyyPrescriptionInfoVO.getQuantity()));
                hlwCf02DO.setYPDJ(wlyyPrescriptionInfoVO.getPackRetprice().intValue());
                hlwCf02DO.setHJJE(Integer.parseInt(wlyyPrescriptionInfoVO.getQuantity())*wlyyPrescriptionInfoVO.getPackRetprice().intValue());//划价价额
                hlwCf02DO.setYPZS(Integer.parseInt(wlyyPrescriptionInfoVO.getFrequency()));
                hlwCf02DO.setYCSL("0");
                hlwCf02DO.setFYGB(17);//费用归并
                hlwCf02DO.setZFBL(1);//自负比例
                hlwCf02DO.setYFDW(wlyyPrescriptionInfoVO.getPackUnitName());
                hlwCf02DO.setMRCS(Integer.parseInt(wlyyPrescriptionInfoVO.getDosage()));//每日次数
                hlwCf02DO.setYFBZ(wlyyPrescriptionInfoVO.getPackQuantity());
                hlwCf02DO.setYPYF(wlyyPrescriptionInfoVO.getUsageCode());
                hlwCf02DO.setYPZH(Integer.parseInt(wlyyPrescriptionInfoVO.getFrequency()));
                hlwCf02DO.setYFGG(wlyyPrescriptionInfoVO.getSpecification());
                hibenateUtils.save(hlwCf02DO);
              /*  String jsonString1 = JSONObject.toJSONString(hlwCf01DO);
                Map<String,Object> params1 = new HashedMap();
                params1.put("json",jsonString1);
                params1.put("table","HLW_CF02");
                logger.info("HLW_CF02:"+jsonString1);
                HttpResponse response1 = HttpUtils.doGet(url,params1);
                if (response1.getStatus()==200){
                    logger.info("表HLW_CF02同步成功!");
                }else {
                    logger.info("表HLW_CF02同步失败!"+response1.getErrorMsg());
                }
*/
            }
        }
        return null;
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

+ 4 - 0
business/base-service/src/main/java/com/yihu/jw/utils/hibernate/HibenateUtils.java

@ -2,6 +2,7 @@ package com.yihu.jw.utils.hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@ -158,7 +159,10 @@ public class HibenateUtils {
    public void save(Object object) {
        Session session = (Session) entityManager.getDelegate();
        Transaction transaction = session.beginTransaction();
        transaction.begin();
        session.save(object);
        transaction.commit();
    }
}

+ 3 - 2
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/HlwCf02DO.java

@ -10,7 +10,8 @@ import java.util.Date;
 *
 * */
@Entity
@Table(name = "HLW_CF02", catalog = "model")
@Table(name = "HLW_CF02")
@SequenceGenerator(name="id_generated", sequenceName="HLW_CF02_SEQ")
public class HlwCf02DO {
    private Integer sBXH;//NUMBER(18)   N注释
    private Integer cFSB;//NUMBER(18)   N识别序号
@ -57,7 +58,7 @@ public class HlwCf02DO {
    private String tHYY;//VARCHAR2(200) Y退回原因
    @Basic
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="id_generated")
    @Id
    @Column(name = "SBXH")
    public Integer getSBXH() {

+ 14 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/WlyyOutpatientDO.java

@ -226,6 +226,11 @@ public class WlyyOutpatientDO extends UuidIdentityEntity {
     */
    private String evaluateStatus;
    /**
     * 付款状态0未付款1付款
     */
    private Integer payStatus;
	@Column(name = "adm_no")
    public String getAdmNo() {
@ -574,4 +579,13 @@ public class WlyyOutpatientDO extends UuidIdentityEntity {
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    @Column(name = "pay_status")
    public Integer getPayStatus() {
        return payStatus;
    }
    public void setPayStatus(Integer payStatus) {
        this.payStatus = payStatus;
    }
}

+ 14 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/WlyyPrescriptionDO.java

@ -228,6 +228,11 @@ public class WlyyPrescriptionDO extends UuidIdentityEntity {
     */
    private Double regFee;
    /**
     * 订单号
     */
    private String orderNo;
    @Column(name = "outpatient_id")
    public String getOutpatientId() {
        return outpatientId;
@ -554,4 +559,13 @@ public class WlyyPrescriptionDO extends UuidIdentityEntity {
    public void setRegFee(Double regFee) {
        this.regFee = regFee;
    }
    @Column(name = "order_no")
    public String getOrderNo() {
        return orderNo;
    }
    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }
}

+ 28 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/prescription/WlyyPrescriptionInfoDO.java

@ -137,6 +137,16 @@ public class WlyyPrescriptionInfoDO extends UuidIdentityEntity {
     */
    private String comm;
    /**
     * 药品产地
     */
    private String drugPlace;
    /**
     * 药房包装
     */
    private Integer packQuantity;
    @Column(name = "prescription_id")
    public String getPrescriptionId() {
@ -342,4 +352,22 @@ public class WlyyPrescriptionInfoDO extends UuidIdentityEntity {
    public void setComm(String comm) {
        this.comm = comm;
    }
    @Column(name = "drug_place")
    public String getDrugPlace() {
        return drugPlace;
    }
    public void setDrugPlace(String drugPlace) {
        this.drugPlace = drugPlace;
    }
    @Column(name = "pack_quantity")
    public Integer getPackQuantity() {
        return packQuantity;
    }
    public void setPackQuantity(Integer packQuantity) {
        this.packQuantity = packQuantity;
    }
}

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderDO.java

@ -17,7 +17,7 @@ import java.util.Date;
 */
@Entity
@Table(name = "base_business_order_pay")
@SequenceGenerator(name="id_generated", sequenceName="BASE_BUSINESS_ORDER_PAY_SEQ")
@SequenceGenerator(name="id_generated", sequenceName="SEQ_BASE_BUSINESS_ORDER_PAY")
public class BusinessOrderDO extends IntegerIdentityEntity {
    private String patient;//居民code

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderRefundDO.java

@ -15,7 +15,7 @@ import java.util.Date;
 */
@Entity
@Table(name = "base_business_order_refund")
@SequenceGenerator(name="id_generated", sequenceName="BASE_BUSINESS_ORDER_REFUND_SEQ")
@SequenceGenerator(name="id_generated", sequenceName="SEQ_BASE_BUSINESS_ORDER_REFUND")
public class BusinessOrderRefundDO extends IntegerIdentityEntity {
    private String patient;//居民code

+ 335 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/hospital/BaseHospitalRequestMapping.java

@ -369,6 +369,341 @@ public class BaseHospitalRequestMapping {
    }
    public static class YkyyPrescription extends BaseHospitalRequestMapping.Basic {
        public static final String PREFIX  = "/ykyyPrescription";
        //=====================start=======================================
        /**
         * 获取门诊记录
         */
        public static final String findOutpatientList = "/findOutpatientList";
        /**
         * 查询单条门诊记录接口
         */
        public static final String findOutpatientInfo ="/findOutpatientInfo";
        /**
         * 查询单条复诊信息全部接口
         */
        public static final String findReOutpatientInfo = "/findReOutpatientInfo";
        /**
         * 获取复诊记录类别
         */
        public static final String findReOutpatientList ="/findReOutpatientList";
        /**
         * 查询患者就诊卡
         */
        public static final String findPatientCard = "/findPatientCard";
        /**
         * 判断是否可用发起门诊
         */
        public static final String checkOutpatient ="/checkOutpatient";
        /**
         * 居民发起复诊
         */
        public static final String appointmentRevisit = "/appointmentRevisit";
        /**
         * 查询所有机构
         */
        public static final String findAllHospital ="/findAllHospital";
        /**
         * 查询机构底下部门
         */
        public static final String findDeptByHospital ="/findDeptByHospital";
        /**
         * 查询有所有已开放的科室
         */
        public static final String findDeptByKeyWord ="/findDeptByKeyWord";
        /**
         * 查询部门下医生
         */
        public static final String findDoctorByHospitalAndDept = "/findDoctorByHospitalAndDept";
        /**
         * 根据疾病名称,热门部门查询医生
         */
        public static final String findDoctorByHospitalAndDiseaseAndDept = "/findDoctorByHospitalAndDiseaseAndDept";
        /**
         * 居民关注医院
         */
        public static final String followOrgByPatient = "/followOrgByPatient";
        /**
         * 获取常见疾病、热门部门、医生拒绝接诊原因 字典
         */
        public static final String findHotDeptAndDiseaseDict = "/findHotDeptAndDiseaseDict";
        /**
         * 挂号
         */
        public static final String registerOutPatient ="/registerOutPatient";
        /**
         * 获取ICD10诊断编码
         */
        public static final String getICD10 ="/getICD10";
        /**
         * 获取药品字典
         */
        public static final String getDrugDictionary ="/getDrugDictionary";
        /**
         * 获取用药方式
         */
        public static final String getDrugUse ="/getDrugUse";
        /**
         * 获取用药频次
         */
        public static final String getDrugFrequency="/getDrugFrequency";
        /**
         * 下诊断
         */
        public static final String makeDiagnosis="/makeDiagnosis";
        /**
         * 获取订单列表
         */
        public static final String findExpressageList="/findExpressageList";
        /**
         * 设置订单
         */
        public static final String setMailno="/setMailno";
        /**
         * 订单导出
         */
        public static final String pushListWrite="/pushListWrite";
        /**
         * 获取号别字典
         */
        public static final String findByDeptTypeCode="/findByDeptTypeCode";
        /**
         * 获取卡信息
         */
        public static final String getCardInfo="/getCardInfo";
        /**
         * 查询医生带排班
         */
        public static final String findDoctorWithWork="/findDoctorWithWork";
        /**
         * 获取具体号源
         */
        public static final String findWorkTimeInfo="/findWorkTimeInfo";
        /**
         * 获取获取医生信息
         */
        public static final String findDoctorInfo="/findDoctorInfo";
        public static final String findDoctorBaseInfo="/findDoctorBaseInfo";
        /**
         * 取消门诊
         */
        public static final String cancelOutPatient="/cancelOutPatient";
        /**
         * 居民取消原因字典
         */
        public static final String findCancelReasonList="/findCancelReasonList";
        /**
         * 獲取快速咨詢時間
         */
        public static final String findFastRegisterDate="/findFastRegisterDate";
        /**
         * 获取快速咨询时间分段
         */
        public static final String findByTimeSlot="/findByTimeSlot";
        /**
         * 获取医生列表,带当月排班状态
         */
        public static final String findDoctorWithMouthWork="/findDoctorWithMouthWork";
        /**
         * 查询某个医生某个月份排班记录
         */
        public static final String findDoctorWorkTimeByMonth="/findDoctorWorkTimeByMonth";
        /**
         * 查询排班规则
         */
        public static final String findWorkRule="/findWorkRule";
        /**
         * 保存排班规则
         */
        public static final String updateWorkRule="/updateWorkRule";
        /**
         * 排班批量保存接口
         */
        public static final String saveDoctorWorkTimeJson="/saveDoctorWorkTimeJson";
        /**
         * 获取居民基础信息
         */
        public static final String findPatientInfo = "/findPatientInfo";
        /**
         * 保存医生在线排班
         */
        public static final String saveDoctorOnlineWork = "/saveDoctorOnlineWork";
        /**
         * 删除医生在线排班
         */
        public static final String delDoctorOnlineWork = "/delDoctorOnlineWork";
        /**
         *查询医生在线排班列表
         */
        public static final String findDoctorOnlineWorkList = "/findDoctorOnlineWorkList";
        /**
         * 发起协同门诊
         */
        public static final String cooperativeOutpatient = "/cooperativeOutpatient";
        /**
         * 设置门诊医生
         */
        public static final String saveOutpatientDoctor = "/saveOutpatientDoctor";
        /**
         * 验证授权
         */
        public static final String checkOauthQRCode = "/checkOauthQRCode";
        /**
         * 全科医生协同门诊列表
         */
        public static final String findByGeneralDoctor = "/findByGeneralDoctor";
        /**
         * 全科医生首页统计信息
         */
        public static final String findGeneralDoctorInfo = "/findGeneralDoctorInfo";
        /**
         * 发送i健康系统消息
         */
        public static final String sendWlyyOutpatientMes = "/sendWlyyOutpatientMes";
        /**
         * 设置I健康消息已读
         */
        public static final String readWlyyOutpatientMes = "/readWlyyOutpatientMes";
        /**
         * 厦门I健康签约信息接口
         */
        public static final String findWlyyPatient = "/findWlyyPatient";
        /**
         *  厦门I健康获取居民身份证
         */
        public static final String findPatientListBySscOrIdCard = "/findPatientListBySscOrIdCard";
        /**
         * 获取Base64医生头像
         */
        public static final String makeBase64Qrcode = "/makeBase64Qrcode";
        //=================end=======================================
        /**
         * 原处方记录
         */
        public static final String findOriginPrescriptionList = "/getOriginPrescriptionList";
        /**
         * 获取原来处方详情
         */
        public static final String findOriginPrescription = "/getOriginPrescriptionInfo";
        /**
         * 续方记录
         */
        public static final String findPrescriptionList = "/findPrescriptionList";
        /**
         * 获取所有居民相关信息,续方信息,物流信息,药品信息
         */
        public static final String findPrescriptionInfo ="/findPrescriptionInfo";
        /**
         * 判断是否可续方
         */
        public static final String checkPrescription = "/checkPrescription";
        /**
         * 居民取消续方
         */
        public static final String cancelPrescription ="/cancelPrescription";
        //居民获取当日就诊列表
        public static final String getTodayOutpatinetList ="/getTodayOutpatinetList";
        //获取医生
        public static final String getDoctorMapping ="/getDoctorMapping";
        //获取检查检验接口
        public static final String getInspectionDictionary ="/getInspectionDictionary";
        public static final String findPrescriptionLogByPreId = "/findPrescriptionLogByPreId";
        public static final String findByPartsCode = "/findByPartsCode";
        public static final String findDictByName = "/findDictByName";
        public static final String getJcmb="/getJcmb";
        public static final String getJymb="/getJymb";
        public static final String getTcxz="/getTcxz";
        public static final String getTcChild="/getTcChild";
        public static final String getInsChild="/getInsChild";
        public static final String getDoctorPreSign ="/getDoctorPreSign";
        public static final String getDoctorIntroduction ="/getDoctorIntroduction";
        public static final String findByDict ="/findByDict";
        //根据居民CODE换取居民请求秘钥
        public static final String getPatientAccetokenByIdcard="/getPatientAccetokenByIdcard";
        //医生待办事项列表
        public static final String doctorUpcomingList = "/doctorUpcomingList";
        public static final String setRecord = "/setRecord";
        public static final String findPatientRecord = "/findPatientRecord";
        public static final String findDoctorByName = "/findDoctorByName";
        public static final String findDeptWithDoctorWorkTime = "/findDeptWithDoctorWorkTime";
        public static final String findWorkTimeRule = "/findWorkTimeRule";
        public static final String saveWorkTimeRule = "/saveWorkTimeRule";
        public static final String checkDoctorWork = "/checkDoctorWork";
        public static final String importDoctorWork = "/importDoctorWork";
    }
    /**
     * 门诊处方物流

+ 11 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyOutpatientVO.java

@ -210,6 +210,9 @@ public class WlyyOutpatientVO extends UuidIdentityVO {
    @ApiModelProperty(value = "医嘱", example = "模块1")
    private String advice;
    @ApiModelProperty(value = "付款状态", example = "付款状态")
    private Integer payStatus;
    public String getAdmNo() {
@ -466,4 +469,12 @@ public class WlyyOutpatientVO extends UuidIdentityVO {
    public void setAdvice(String advice) {
        this.advice = advice;
    }
    public Integer getPayStatus() {
        return payStatus;
    }
    public void setPayStatus(Integer payStatus) {
        this.payStatus = payStatus;
    }
}

+ 22 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyPrescriptionInfoVO.java

@ -143,6 +143,12 @@ public class WlyyPrescriptionInfoVO extends UuidIdentityVOWithOperator {
    @ApiModelProperty(value = "1可用 0删除", example = "模块1")
    private Integer del;
    @ApiModelProperty(value = "药品产地", example = "药品产地")
    private String drugPlace;
    @ApiModelProperty(value = "药房包装", example = "药房包装")
    private Integer packQuantity;
    private String comm;
@ -327,4 +333,20 @@ public class WlyyPrescriptionInfoVO extends UuidIdentityVOWithOperator {
    public void setComm(String comm) {
        this.comm = comm;
    }
    public String getDrugPlace() {
        return drugPlace;
    }
    public void setDrugPlace(String drugPlace) {
        this.drugPlace = drugPlace;
    }
    public Integer getPackQuantity() {
        return packQuantity;
    }
    public void setPackQuantity(Integer packQuantity) {
        this.packQuantity = packQuantity;
    }
}

+ 12 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyPrescriptionVO.java

@ -292,6 +292,10 @@ public class WlyyPrescriptionVO extends UuidIdentityVOWithOperator {
    @ApiModelProperty(value = "his-挂号费用", example = "模块1")
    private Integer hisRegisterFee;
    @ApiModelProperty(value = "订单号",example = "订单号")
    private String orderNo;
    /**
     * 处方结算状态,0为未结算,1为结算成功,默认为0
     */
@ -701,4 +705,12 @@ public class WlyyPrescriptionVO extends UuidIdentityVOWithOperator {
    public void setInspectionVOs(List<WlyyInspectionVO> inspectionVOs) {
        this.inspectionVOs = inspectionVOs;
    }
    public String getOrderNo() {
        return orderNo;
    }
    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }
}

+ 121 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/prescription/YkyyPrescriptionEndpoint.java

@ -0,0 +1,121 @@
package com.yihu.jw.hospital.endpoint.prescription;
import com.yihu.jw.doctor.service.excel.DoctorWorkTimeExcelReader;
import com.yihu.jw.doctor.service.excel.DoctorWorkTimeMainExcelDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDiagnosisDO;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.service.*;
import com.yihu.jw.hospital.prescription.service.entrance.DoctorPreSignService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.service.SystemMessage.HospitalSystemMessageService;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.restmodel.hospital.prescription.WlyyOutpatientVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
import com.yihu.jw.restmodel.im.ConsultVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.wlyy.service.WlyyBusinessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
 * Created by Trick on 2019/5/16
 */
@RestController
@RequestMapping(value = BaseHospitalRequestMapping.YkyyPrescription.PREFIX)
@Api(value = "眼科医院在线复诊", description = "眼科医院在线复诊接口", tags = {"眼科医院在线复诊接口"})
public class YkyyPrescriptionEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private YkyyPrescriptionService prescriptionService;
    @Autowired
    private WlyyBusinessService wlyyBusinessService;
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private InspectionService inspectionService;
    @Autowired
    private DoctorPreSignService doctorPreSignService;
    
    @Autowired
    private HospitalSystemMessageService hospitalSystemMessageService;
    @Autowired
    private WorkTimeService workTimeService;
    
    @Autowired
    private ImService imService;
    
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;
    @Value("${demo.flag}")
    private boolean demoFlag;
    @PostMapping(value = BaseHospitalRequestMapping.YkyyPrescription.appointmentRevisit)
    @ApiOperation(value = "居民发起复诊", notes = "居民发起复诊")
    public ObjEnvelop appointmentRevisit(@ApiParam(name = "outpatientJson", value = "居民门诊json")
                                         @RequestParam(value = "outpatientJson", required = false)String outpatientJson,
                                         @ApiParam(name = "expressageJson", value = "居民物流json")
                                         @RequestParam(value = "expressageJson", required = false)String expressageJson,
                                         @ApiParam(name = "registerJson", value = "预约时间")
                                         @RequestParam(value = "registerJson", required = false)String registerJson,
                                         @ApiParam(name = "chargeType", value = "预约实体json")
                                         @RequestParam(value = "chargeType", required = false)String chargeType)throws Exception {
        WlyyOutpatientDO wlyyOutpatientDO = prescriptionService.appointmentRevisit(outpatientJson,expressageJson,registerJson,chargeType);
       /* //发送系统消息
        SystemMessageDO systemMessageDO = prescriptionService.sendOutPatientMes(wlyyOutpatientDO);
        //发送IM消息
        hospitalSystemMessageService.sendImMessage(systemMessageDO);
        //发送医生抢单消息
        if(StringUtils.isBlank(wlyyOutpatientDO.getDoctor())){
            hospitalSystemMessageService.sendImPichCheckMessage(wlyyOutpatientDO);
        }*/
        return success(BaseHospitalRequestMapping.Prescription.api_success,wlyyOutpatientDO);
    }
    @GetMapping(value = BaseHospitalRequestMapping.Prescription.getDrugDictionary)
    @ApiOperation(value = "获取药品字典", notes = "获取药品字典")
    public ListEnvelop getDrugDictionary(@ApiParam(name = "drugNo", value = "药品编码")
                                         @RequestParam(value = "drugNo", required = false)String drugNo,
                                         @ApiParam(name = "pyKey", value = "拼音关键字")
                                         @RequestParam(value = "pyKey", required = false)String pyKey,
                                         @ApiParam(name = "winNo", value = "分部编码")
                                         @RequestParam(value = "winNo", required = false)String winNo,
                                         @ApiParam(name = "groupNo", value = "药房编码")
                                         @RequestParam(value = "groupNo", required = false)String groupNo)throws Exception {
        return success(prescriptionService.getDrugDictionary(drugNo,pyKey,winNo,groupNo));
    }
}

+ 22 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/ykyy/YkyyController.java

@ -38,6 +38,8 @@ public class YkyyController extends EnvelopRestEndpoint {
    private String wxId;
    @Autowired
    private BusinessOrderService businessOrderService;
    @Autowired
    private YkyyEntranceService ykyyEntranceService;
    @GetMapping(value = "/selectCardList")
@ -264,6 +266,26 @@ public class YkyyController extends EnvelopRestEndpoint {
    }
    /**
     *
     * his同步数据
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "ceshi", method = RequestMethod.POST)
    @ApiOperation("his同步数据")
    public ObjEnvelop findByRealOrder(
            @ApiParam(name = "code", value = "code", required = true)
            @RequestParam(required = true)String code) throws Exception {
        try {
            ykyyEntranceService.findByRealOrder(code);
            return ObjEnvelop.getSuccess("ok","");
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }