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.yihu.jw.dict.dao.DictDoctorDutyDao;
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.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.dict.BaseJobCategoryDO;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.dict.DictIcd10DO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
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.file_upload.FileUploadService;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.dict.YkDictIcd10Dao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.prescription.dao.*;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientMedicareCardDao;
import com.yihu.jw.restmodel.hospital.prescription.*;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.EntityUtils;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.YkyySMSService;
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 jxl.write.DateTime;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.DataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 眼科医院专用service
 * Created by Trick on 2020/1/19.
 */
@Service
@Transactional
public class YkyyEntranceService {

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


    private final static String url="http://192.168.20.55:10023/ykyy/createSQLQuery";
//    private final static String url="http://localhost:10023/ykyy/createSQLQuery";192.168.33.197

    private final static String saveUrl="http://192.168.20.55:10023/ykyy/save";
    private final static String orderUrl="http://192.168.20.55:10023/ykyy/outPatientOrder";

    private final static String updateUrl="http://192.168.20.55:10023/ykyy/updateBySql";

    private final static String updateEntityUrl="http://192.168.20.55:10023/ykyy/update";

    private final static String jdbcUrl="http://192.168.20.55:10023/ykyy/jdbcSQLQuery";

    private final static String updateJdxx="http://192.168.20.55:10023/ykyy/updateJdxx";

    private final static String updateJzkh = "http://192.168.20.55:10023/ykyy/updateJzkh";

    private final static String orgCode ="350211A5004";

    private final static String orgName ="厦门大学附属厦门眼科中心";

    private final static String saveJdxxUrl="http://192.168.20.55:10023/ykyy/saveJdxx";

    @Autowired
    private DictHospitalDeptDao hospitalDeptDao;

    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;

    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;

    @Autowired
    private DoctorMappingDao doctorMappingDao;

    @Autowired
    private BaseDoctorDao baseDoctorDao;

    @Autowired
    private PatientMappingDao patientMappingDao;

    @Autowired
    private BasePatientDao basePatientDao;

    @Autowired
    private OutpatientDao outpatientDao;

    @Autowired
    private PrescriptionDao prescriptionDao;

    @Autowired
    private BaseEvaluateScoreDao baseEvaluateScoreDao;

    @Autowired
    private BaseEvaluateDao baseEvaluateDao;

    @Autowired
    private HibenateUtils hibenateUtils;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private YkDictIcd10Dao ykDictIcd10Dao;
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientMedicareCardDao patientMedicareCardDao;
    @Autowired
    private WlyyInspectionDao wlyyInspectionDao;

    @Autowired
    private YkyyService ykyyService;
    @Autowired
    private PrescriptionEmrDao prescriptionEmrDao;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private BaseNatAppointmentDao baseNatAppointmentDao;
    @Autowired
    private YkyySMSService ykyySMSService;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;
    @Autowired
    private PrescriptionExpressageDao prescriptionExpressageDao;


    public List<Map<String, Object>> createSQLQuery(String sql, Map<String, Object> params, Integer page, Integer size){
        return hibenateUtils.createSQLQuery(sql,params,page,size);
    }

    public List<Map<String, Object>> jdbcSQLQuery(String sql){
        return jdbcTemplate.queryForList(sql);
    }


    public void save(Object object){
        hibenateUtils.save(object);
    }

    public void update(Object object){
        hibenateUtils.update(object);
    }

    public void updateBySql(String sql){
        hibenateUtils.updateBySql(sql);
    }
    /**
     * 同步科室信息
     * @return
     * @throws Exception
     */
    public JSONArray findDeptByYq(String yqFlag,String deptCode,String deptName)throws Exception{
        String sql = "select code AS \"code\",name as \"name\",consultdeptflag as \"consultDeptFlag\",to_char(yjsy) as \"yjsy\" ,to_char(yqdm) as \"orgCode\" from V_HLW_KSXX where 1=1 and yjsy = 'Y'";
        if (StringUtils.isNoneBlank(yqFlag)){
            sql+=" and yqdm = '"+yqFlag+"'";
        }
        if (StringUtils.isNoneBlank(deptCode)){
            sql+=" and code = '"+deptCode+"'";
        }
        if (StringUtils.isNoneBlank(deptName)){
            sql+=" and name like  '%"+deptName+"%'";
        }
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("findDeptByYq："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            JSONArray array = rs.getJSONArray("detailModelList");
            logger.info("dept size:"+array.size());
            if(array!=null&&array.size()>0){
                for(int i=0;i<array.size();i++){
                    JSONObject deptjson = array.getJSONObject(i);
                    String orgCode = deptjson.getString("orgCode");
                    if ("1001".equalsIgnoreCase(orgCode)){
                        deptjson.put("orgName","思北院区");
                    }else {
                        deptjson.put("orgName","五缘院区");
                    }
                }
                return array;
            }
        }
        return  null;
    }


    /**
     * 同步科室信息
     * @return
     * @throws Exception
     */
    public String updateYkyyDept()throws Exception{
        String sql ="select code AS \"code\",name as \"name\",consultdeptflag as \"consultDeptFlag\" from V_HLW_KSXX";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("updateYkyyDept："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            JSONArray array = rs.getJSONArray("detailModelList");
            logger.info("dept size:"+array.size());
            if(array!=null&&array.size()>0){
                for(int i=0;i<array.size();i++){
                    JSONObject deptjson = array.getJSONObject(i);
                    String code = deptjson.getString("code");

                    List<DictHospitalDeptDO> list = hospitalDeptDao.findByOrgCodeAndCode(orgCode,code);
                    if(list!=null&&list.size()>0){
                        DictHospitalDeptDO deptDO = list.get(0);
                        deptDO.setName(deptjson.getString("name"));
                        deptDO.setConsultDeptFlag(deptjson.getString("consultDeptFlag"));
                        hospitalDeptDao.save(deptDO);
                    }else {
                        //新增
                        DictHospitalDeptDO deptDO = new DictHospitalDeptDO();
                        deptDO.setOrgCode(orgCode);
                        deptDO.setCode(code);
                        deptDO.setName(deptjson.getString("name"));
                        deptDO.setConsultDeptFlag(deptjson.getString("consultDeptFlag"));
                        deptDO.setCreateTime(new Date());
                        hospitalDeptDao.save(deptDO);
                    }

                }

            }
        }
        return "success";
    }

    /**
     * 检验信息列表
     * @param patient
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    public JSONArray vlisReportMasterlist(String patient,Integer page,Integer size,String startTime,String endTime) throws Exception{
        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patient);
        if(patientMappingDO==null){
            return new JSONArray();
        }
        String sql ="select * from VLIS_REPORT_MASTER where PATIENT_NO = 'XMYK"+patientMappingDO.getMappingCode()+"'";
        if(StringUtils.isNoneBlank(startTime)){
            sql+=" and REPORT_TIME >= '"+startTime.replace("-",".")+"'";
        }
        if(StringUtils.isNoneBlank(endTime)){
            sql+=" and REPORT_TIME <= '"+endTime.replace("-",".")+"'";
        }
        sql+="  order by REPORT_TIME desc";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        params.put("size",size);
        params.put("page",page);
        logger.info("vpacsReportList："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * 检查信息明细
     * @param REPORT_ID
     * @return
     * @throws Exception
     */
    public JSONObject vlisReportMasterDetail(String REPORT_ID) throws Exception{
        String sql ="select * from VLIS_REPORT_MASTER where REPORT_ID = '"+REPORT_ID+"'";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("vlisReportMasterDetail："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONObject res = new JSONObject();
        if(status!=null&&status == 200){
            res = rs.getJSONArray("detailModelList").getJSONObject(0);
        }

        BasePatientDO patientDO = findPatientByMapingCode(res.getString("PATIENT_ID"));
        JSONObject patientJson = new JSONObject();
        if(patientDO==null){
            patientJson.put("name","");
            patientJson.put("sex","");
            patientJson.put("birthday","");
        }else {
            patientJson.put("name",patientDO.getName());
            patientJson.put("sex",patientDO.getSex());
            patientJson.put("birthday",patientDO.getBirthday());
        }
        res.put("patient",patientJson);

        //LIS 常规报告细视图
        String detail1 = "select * from VLIS_REPORT_DETAIL where REPORT_ID = '"+REPORT_ID+"'";
        Map<String,Object> detailParams1 = new HashedMap();
        detailParams1.put("sql",detail1);
        logger.info("VLIS_REPORT_DETAIL："+detail1);
        HttpResponse detailresponse1 = HttpUtils.doGet(url,detailParams1);
        String detailcontent1 = detailresponse1.getContent();
        logger.info("response:"+detailcontent1);
        JSONObject detailrs1 = JSON.parseObject(detailcontent1);
        if(detailrs1.getInteger("status")!=null&&detailrs1.getInteger("status") == 200){
            res.put("detail1",detailrs1.getJSONArray("detailModelList"));
        }

        //LIS 药敏报告细视图
        String detail2 = "select * from VLIS_REPORT_DETAIL2 where REPORT_ID = '"+REPORT_ID+"'";
        Map<String,Object> detailParams2 = new HashedMap();
        detailParams2.put("sql",detail2);
        logger.info("VLIS_REPORT_DETAIL2："+detail2);
        HttpResponse detailresponse2 = HttpUtils.doGet(url,detailParams2);
        String detailcontent2 = detailresponse2.getContent();
        logger.info("response:"+detailcontent2);
        JSONObject detailrs2 = JSON.parseObject(detailcontent2);
        if(detailrs2.getInteger("status")!=null&&detailrs2.getInteger("status") == 200){
            res.put("detail2",detailrs2.getJSONArray("detailModelList"));
        }

        //LIS 细菌培养说明细视图
/*        String detail3 = "select * from VLIS_REPORT_DETAIL3 where REPORT_ID = '"+REPORT_ID+"'";
        Map<String,Object> detailParams3 = new HashedMap();
        detailParams3.put("sql",detail3);
        logger.info("VLIS_REPORT_DETAIL："+detail3);
        HttpResponse detailresponse3 = HttpUtils.doGet(url,detailParams3);
        String detailcontent3 = detailresponse3.getContent();
        logger.info("response:"+detailcontent3);
        JSONObject detailrs3 = JSON.parseObject(detailcontent3);
        if(detailrs3.getInteger("status")!=null&&detailrs3.getInteger("status") == 200){
            res.put("detail3",detailrs3.getJSONArray("detailModelList"));
        }*/

        return res;
    }


    /**
     * 检查信息列表
     * @param patient
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    public JSONArray vpacsReportList(String patient,Integer page,Integer size) throws Exception{
        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patient);
        if(patientMappingDO==null){
            return null;
        }
        String sql ="select * from VPACS_REPORT where PATIENT_ID = '"+patientMappingDO.getMappingCode()+"'";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        params.put("size",size);
        params.put("page",page);
        logger.info("vpacsReportList："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * 检查信息明细
     * @param REPORT_ID
     * @return
     * @throws Exception
     */
    public JSONObject vpacsReportDetail(String REPORT_ID) throws Exception{
        String sql ="select * from VPACS_REPORT where REPORT_ID = '"+REPORT_ID+"'";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("vpacsReportDetail："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList").getJSONObject(0);
        }
        return new JSONObject();
    }

    /**
     * 患者门诊就诊记录
     * 使用时间查询的话，很可能会超时。时间没有索引，所以超时时间需要加长
     *
     * @param PAT_NO    居民唯一号 一个居民在该医院只有一个号，该接口必须输入的参数
     * @param conNo     就诊次数，使用居民唯一号+就诊次数获取唯一一条就诊记录
     *                  // *  @param admNo 就诊唯一号 每一次就诊都有一个唯一号：居民号+就诊次数，查询确定的一条就诊记录时需要传，否则传null
     *                  // *  @param registerSn 挂号流水号，查询确定的一条就诊记录时需要传，否则传null
     * @param startTime 开始时间 （查询一段时间内就诊记录开始时间，查询就诊记录列表时需要传，否则传null）
     * @param endTime   结束时间 （查询一段时间内就诊记录结束时间，查询就诊记录列表时需要传，否则传null）
     * @return
     * @throws Exception
     */
    public List<WlyyOutpatientVO> BS30025(String PAT_NO, String conNo, String startTime, String endTime, boolean demoFlag,String ksdm) throws Exception {

        String fid = "BS30025";
        logger.info("EntranceService " + fid + " PAT_NO :" + PAT_NO + " conNo:" + conNo + " startTime:" + startTime + " endTime:" + endTime);

        String resp = "";
        String orgCode = "350211A5004";
        String orgName = "厦门大学附属厦门眼科中心";

        //居民id转化
        PatientMappingDO patientMappingDO = patientMappingDao.findByMappingCodeAndSource(PAT_NO,"1");
        if(patientMappingDO == null){
            return null;
        }

//KSSJ,h.BRID,h.BRXM,h.SJHM,h.JZKH,h.SFZH,h.BRXZ,h.YSDM,h.KDYS" +
//                ",h.KSDM,h.KSMC,h.ZDMC,h.JZXH
        JSONArray jsonArray = new JSONArray();
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("BRID","1168517");
            jsonObject.put("BRXM","于小童");
            jsonObject.put("SJHM","");
            jsonObject.put("SFZH","");
            jsonObject.put("BRXZ","自费");
            jsonObject.put("YSDM","1630");
            jsonObject.put("KDYS","罗向东");
            jsonObject.put("KSDM","1101");
            jsonObject.put("KSMC","眼底病专科(五缘院区)");
            jsonObject.put("KSSJ","2020/04/28 15:55:29");
            jsonObject.put("ZDMC","高度近视");
            jsonObject.put("JZXH","2395501");

            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("BRID","1168517");
            jsonObject2.put("BRXM","于小童");
            jsonObject2.put("SJHM","");
            jsonObject2.put("SFZH","");
            jsonObject2.put("BRXZ","自费");
            jsonObject2.put("YSDM","1630");
            jsonObject2.put("KDYS","张纯");
            jsonObject2.put("KSDM","1101");
            jsonObject2.put("KSMC","高度近视专科(五缘院区)");
            jsonObject2.put("KSSJ","2020/05/19 15:51:23");
            jsonObject2.put("ZDMC","高度近视");
            jsonObject2.put("JZXH","2395506");

            jsonArray.add(jsonObject);
            jsonArray.add(jsonObject2);
        }else {
            jsonArray = findV_ZKSG_HZCX_HIS(patientMappingDO.getMappingCode(),conNo,startTime,endTime,ksdm);
        }
        //查找眼科数据
        if (jsonArray.size() == 0) {
            return null;
        }

        List<WlyyOutpatientVO> wlyyOutpatientVOS = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObjectMgsInfo = jsonArray.getJSONObject(i);
            if (null != jsonObjectMgsInfo) {
                WlyyOutpatientVO wlyyOutpatientVO = new WlyyOutpatientVO();
                wlyyOutpatientVO.setHospital(orgCode);
                wlyyOutpatientVO.setHospitalName(orgName);
                wlyyOutpatientVO.setWinNo("6");
                wlyyOutpatientVO.setAdmNo(null == jsonObjectMgsInfo.get("JZXH") ? "" : jsonObjectMgsInfo.get("JZXH") + "");
                //wlyyOutpatientVO.setRegisterNo(null == jsonObjectMgsInfo.get("REGISTER_SN") ? "" : jsonObjectMgsInfo.get("REGISTER_SN") + "");
                wlyyOutpatientVO.setDept(null == jsonObjectMgsInfo.get("KSDM") ? "" : jsonObjectMgsInfo.get("KSDM") + "");
                wlyyOutpatientVO.setDeptName(null == jsonObjectMgsInfo.get("KSMC") ? "" : jsonObjectMgsInfo.get("KSMC") + "");
                wlyyOutpatientVO.setPatient(patientMappingDO.getPatient());
                wlyyOutpatientVO.setPatientName(patientMappingDO.getPatientName());
                wlyyOutpatientVO.setConNo(null == jsonObjectMgsInfo.get("JZXH") ? "" : jsonObjectMgsInfo.get("JZXH") + "");
                String doctor = null == jsonObjectMgsInfo.get("YSDM") ? "" : jsonObjectMgsInfo.get("YSDM") + "";

                //转化医生
                String mappingCode = doctor.trim();
                String doctorCode = "";
                if (StringUtils.isNotBlank(mappingCode)) {
                    List<DoctorMappingDO> mappingDOs = doctorMappingDao.findByOrgCodeAndMappingCode(orgCode, mappingCode);
                    if (mappingDOs != null && mappingDOs.size() > 0) {
                        doctorCode = mappingDOs.get(0).getDoctor();
                    }
                }
                wlyyOutpatientVO.setDoctor(doctorCode);
                wlyyOutpatientVO.setDoctorName(null == jsonObjectMgsInfo.get("KDYS") ? "" : jsonObjectMgsInfo.get("KDYS") + "");

//                wlyyOutpatientVO.setMjz(null == jsonObjectMgsInfo.get("MJZ") ? "" : jsonObjectMgsInfo.get("MJZ") + "");

                String icdName = null == jsonObjectMgsInfo.get("ZDMC") ? "" : jsonObjectMgsInfo.get("ZDMC") + "";
//                wlyyOutpatientVO.setIcd10(icdcodes);
                wlyyOutpatientVO.setIcd10Name(icdName);

                String admDate = null == jsonObjectMgsInfo.get("KSSJ") ? "" : jsonObjectMgsInfo.get("KSSJ") + "";
                String conDate = null == jsonObjectMgsInfo.get("KSSJ") ? "" : jsonObjectMgsInfo.get("KSSJ") + "";
                wlyyOutpatientVO.setAdmDate(DateUtil.strToDate(admDate, DateUtil.YYYY_MM_DD_HH_MM_SS_));
                wlyyOutpatientVO.setConDate(DateUtil.strToDate(conDate, DateUtil.YYYY_MM_DD_HH_MM_SS_));
                List<WlyyInspectionVO> inspectionVOList = new ArrayList<>();
                JSONArray array = findV_ZKSG_JCCX(PAT_NO,wlyyOutpatientVO.getAdmNo(),demoFlag);
                for (int j=0;j<array.size();j++){
                    JSONObject object = array.getJSONObject(j);
                    String ksdm1 = object.getString("ksdm");//科室代码
                    String fymc = object.getString("fymc");//费用名称
                    String fydj = object.getString("fydj");//单价
                    String fysl = object.getString("fysl");//数量
                    String fyhj = object.getString("fyhj");//金额
                    String jzxh = object.getString("jzxh");//就诊序号
                    String zxks = object.getString("zxks");//执行科室
                    String yqdm = object.getString("yqdm");//执行科室
                    WlyyInspectionVO wlyyInspectionVO = new WlyyInspectionVO();
                    wlyyInspectionVO.setName(fymc);
                    wlyyInspectionVO.setDeptName(zxks);
                    wlyyInspectionVO.setDept(ksdm1);
                    wlyyInspectionVO.setOrgCode(yqdm);
                    if ("1001".equalsIgnoreCase(yqdm)){
                        wlyyInspectionVO.setOrgName("思北院区");
                    }else {
                        wlyyInspectionVO.setOrgName("五缘院区");
                    }
                    wlyyInspectionVO.setQuantity(Integer.parseInt(fysl));
                    inspectionVOList.add(wlyyInspectionVO);
                }
                wlyyOutpatientVO.setInspectionVOS(inspectionVOList);
                wlyyOutpatientVOS.add(wlyyOutpatientVO);
            }
        }
        return wlyyOutpatientVOS;
    }

    /**
     * 查找眼科his 已审核未付款的处方
     * @throws Exception
     */
    public JSONArray getUnsettledPrescription() throws Exception{
        String sql = "SELECT h.BRID,h.CFSB,h.SJLY from v_ms_dd01 h WHERE h.SPZT = 1 and h.FKZT = 0 order by h.KFRQ desc ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        params.put("page","1");
        params.put("size","60");
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);

        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * 查找眼科his 审方失败
     * @throws Exception
     */
    public JSONArray getNoUnsettledPrescription() throws Exception{
        String sql = "SELECT h.BRID,h.CFSB,h.SJLY from v_ms_dd01 h WHERE h.SPZT = 2 and h.FKZT = 0 order by h.KFRQ desc ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        params.put("page","1");
        params.put("size","60");
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);

        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * 查找眼科his 未审核未付款
     * @throws Exception
     */
    public JSONArray getUnCheckPrescription(String startTime,String endTime) throws Exception{
        String sql = "SELECT h.BRID,h.CFSB,h.SJLY from v_ms_dd01 h WHERE h.SPZT = 0 and h.FKZT = 0 ";
        if(!StringUtil.isBlank(startTime)){
            sql += " and h.KFRQ >= to_date('"+startTime+"', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if(!StringUtil.isBlank(endTime)){
            sql += " and h.KFRQ <= to_date('"+endTime+"', 'YYYY-MM-DD HH24:MI:SS')";
        }
        sql+=" order by h.KFRQ desc ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        params.put("page","1");
        params.put("size","60");
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);

        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * HIS就诊患者历史查询
     * @throws Exception
     */
    public JSONArray findV_ZKSG_HZCX_HIS(String brid,String conNo,String startTime,String endTime,String ksdm) throws Exception{

        String sql = "SELECT to_char(h.KSSJ ,'yyyy/MM/dd hh24:mi:ss' ) as KSSJ,h.BRID,h.BRXM,h.SJHM,h.JZKH,h.SFZH,h.BRXZ,h.YSDM,h.KDYS" +
                ",h.KSDM,h.KSMC,h.ZDMC,h.JZXH from V_ZKSG_HZCX_HIS h WHERE h.BRID = "+brid+" ";
        String depts ="";
        String deptUsuaName ="";
        if (StringUtils.isNoneBlank(ksdm)){
            DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDao.findByCode(ksdm);
            if (dictHospitalDeptDO!=null){
                deptUsuaName = dictHospitalDeptDO.getUsualName();
            List<DictHospitalDeptDO> deptList =dictHospitalDeptDao.findByUsuallyName(deptUsuaName);
            if (deptList!=null&&deptList.size()>0){
                for (int i =0 ;i<deptList.size();i++){
                    if (i==deptList.size()-1){
                        depts +=deptList.get(i).getCode();
                    }else {
                        depts+=deptList.get(i).getCode()+",";
                    }
                }
            }else {
                depts = dictHospitalDeptDO.getCode();
            }
        }

        }
        if(!StringUtil.isBlank(conNo)){
            sql += " and h.JZXH = " + conNo;
        }
        if(!StringUtil.isBlank(startTime)){
            sql += " and h.KSSJ >= to_date('"+startTime+"', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if(!StringUtil.isBlank(endTime)){
            sql += " and h.KSSJ <= to_date('"+endTime+"', 'YYYY-MM-DD HH24:MI:SS')";
        }/*if(!StringUtil.isBlank(depts)){
            sql += " and h.KSDM in ("+ depts+")";
        }*/

        sql += " order by h.KSSJ desc";

        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("sqlOutpatientList"+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }


    /**
     * HIS就诊患者历史查询
     * @throws Exception
     */
    public JSONArray findV_ZKSG_JCCX(String brid,String conNo,boolean demoFlag) throws Exception{
        String sql = "SELECT\n" +
                "\tz.BRID AS \"brid\",\n" +
                "\tz.BRXM AS \"brxm\",\n" +
                "\tto_char (\n" +
                "\t\tz.KDRQ,\n" +
                "\t\t'yyyy/MM/dd hh24:mi:ss'\n" +
                "\t) AS \"kdrq\",\n" +
                "\tto_char (\n" +
                "\t\tz.ZXRQ,\n" +
                "\t\t'yyyy/MM/dd hh24:mi:ss'\n" +
                "\t) AS \"zxrq\",\n" +
                "\tz.YSDM AS \"ysdm\",\n" +
                "\tz.KSDM AS \"ksdm\",\n" +
                "\tz.FYMC AS \"fymc\",\n" +
                "\tz.FYDJ AS \"fydj\",\n" +
                "\tz.FYSL AS \"fysl\",\n" +
                "\tz.FYHJ AS \"fyhj\",\n" +
                "\tz.YBLB AS \"yblb\",\n" +
                "\tz.JZXH AS \"jzxh\",\n" +
                "\tz.YJXH AS \"yjxh\",\n" +
                "\tto_char(h.YQDM) AS \"yqdm\",\n" +
                "\tz.ZXKS AS \"zxks\"\n" +
                "FROM\n" +
                "\tV_ZKSG_JCCX z left join V_HLW_KSXX h on z.ksdm = h.code\n" +
                "WHERE\n" +
                "\tz.JZXH = '"+conNo+"'\n" +
                "AND z.brid = '"+brid+"'";
        JSONArray jsonArray = new JSONArray();
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("brid","769da42e4dda41b29e73ddf2450b42c2");
            jsonObject.put("brxm","李艳秋");
            jsonObject.put("kdrq","2020-06-15");
            jsonObject.put("zxrq","2020-06-25");
            jsonObject.put("ysdm","A0502541");
            jsonObject.put("fymc","珍视明眼药水");
            jsonObject.put("fydj","9.99");
            jsonObject.put("fysl","2");
            jsonObject.put("fyhj","19.98");
            jsonObject.put("yblb","甲类");
            jsonObject.put("jzhx","X44515865");
            jsonObject.put("yjxh","F0551285");
            jsonObject.put("zxks","高度近视专科(五缘院区)");
            jsonArray.add(jsonObject);
        }else {
            Map<String,Object> params = new HashedMap();
            params.put("sql",sql);
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if(status!=null&&status == 200){
                return rs.getJSONArray("detailModelList");
            }
        }
        return jsonArray;
    }


    /**
     * HIS处方记录
     * @throws Exception
     */
    public List<WlyyPrescriptionVO> findV_MSDD01And02(String admNo,boolean demoFlag) throws Exception{
        List<WlyyPrescriptionVO> wlyyPrescriptionVOList = new ArrayList<>();

        //处方数据
        String msd01 = "SELECT\n" +
                "\td.CFSB AS \"cfsb\",\n" +
                "\td.CFHM AS \"cfhm\",\n" +
                "\td.FKZT as \"fkzt\",\n" +
                "\td.CFLX as \"cflx\",\n" +
                "\td.KFRQ as \"kfrq\",\n" +
                "\td.SCDDH as \"scddh\",\n" +
                "\td.BRID as \"brid\",\n" +
                "\td.BRXM as \"brxm\",\n" +
                "\td.KSDM as \"ksdm\",\n" +
                "\td.YSDM as \"ysdm\",\n" +
                "\td.JZXH as \"jzxh\",\n" +
                "\td.GUID as \"guid\",\n" +
                "\td.JZKH as \"jzkh\"\n" +
                "FROM\n" +
                "\tV_MS_CF01 d\n" +
                "WHERE\n" +
                "\td.JZXH = '"+admNo+"'";

        JSONObject rs = new JSONObject();
        String content="";
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cfsb","X155245");
            jsonObject.put("cfhm","2524863258522");
            jsonObject.put("fkzt","0");
            jsonObject.put("cflx",1100);
            jsonObject.put("kfrq","2020-06-23 15:25:58");
            jsonObject.put("scddh","SH2856545254");
            jsonObject.put("brid","25318532");
            jsonObject.put("brxm","杨楠");
            jsonObject.put("ksdm","350524A0221");
            jsonObject.put("ysdm","152586232");
            jsonObject.put("jzxh","MZ258515");
            jsonObject.put("guid","255df252s222");
            jsonObject.put("jzkh","JZ255317855");
            JSONArray array = new JSONArray();
            array.add(jsonObject);
            rs.put("detailModelList",array);
            rs.put("status","200");
            content=rs.toJSONString();
        }else {
            Map<String,Object> params = new HashedMap();
            params.put("sql",msd01);
            HttpResponse response = HttpUtils.doGet(url,params);
             content = response.getContent();
            logger.info("response:"+content);
            rs = JSON.parseObject(content);
        }

        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            JSONArray array =rs.getJSONArray("detailModelList");
            logger.info("precription:"+rs.getJSONArray("detailModelList"));
            for (int j=0;j<array.size();j++){
                WlyyPrescriptionVO wlyyPrescriptionVO = new WlyyPrescriptionVO();
                JSONObject object = array.getJSONObject(j);
                wlyyPrescriptionVO.setType(object.getInteger("cflx"));
                wlyyPrescriptionVO.setOrderNo(object.getString("scddh"));
                wlyyPrescriptionVO.setPayStatus(object.getInteger("fkzt"));
                wlyyPrescriptionVO.setPatientName(object.getString("brxm"));
                String brid = object.getString("brid");
                if (StringUtils.isNoneBlank(brid)){
                    PatientMappingDO mappingDO = patientMappingDao.findByMappingCode(brid);
                    if (mappingDO!=null){
                        wlyyPrescriptionVO.setPatientCode(mappingDO.getPatient());
                    }
                }
                wlyyPrescriptionVO.setSsc(object.getString("jzkh"));
                wlyyPrescriptionVO.setOrderId(object.getString("guid"));
                wlyyPrescriptionVO.setAdmNo(object.getString("jzxh"));
                wlyyPrescriptionVO.setRealOrder(object.getString("cfsb"));
                wlyyPrescriptionVO.setDept(object.getString("ksdm"));
                wlyyPrescriptionVO.setOriginRealOrder(object.getString("cfhm"));
                String msd02 = "SELECT\n" +
                        "\td.CFSB AS \"cfsb\",\n" +
                        "\td.YPXH as \"ypxh\",\n" +
                        "\td.YPCD as \"ypcd\",\n" +
                        "\td.YPSL as \"ypsl\",\n" +
                        "\td.YPDJ as \"ypdj\",\n" +
                        "\td.HJJE as \"hjje\",\n" +
                        "\td.YFDW as \"yfdw\",\n" +
                        "\td.MRCS as \"mrcs\",\n" +
                        "\td.YFBZ as \"yfbz\",\n" +
                        "\td.YPYF as \"ypyf\",\n" +
                        "\td.GYTJ as \"gytj\",\n" +
                        "\td.YCJL as \"ycjl\",\n" +
                        "\td.SBXH as \"sbxh\",\n" +
                        "\td.YYTS as \"yyts\",\n" +
                        "\td.YFGG as \"yfgg\"\n" +
                        "FROM\n" +
                        "\tV_MS_CF02 d  \n" +
                        "WHERE\n" +
                        "\td.cfsb = '"+wlyyPrescriptionVO.getRealOrder()+"'";

                JSONObject rs1 =new JSONObject();
                if (demoFlag){
                    JSONArray array1 = new JSONArray();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cfsb","X1552155");
                    jsonObject.put("ypxh","CF2552142");
                    jsonObject.put("ypcd","YP2552212");
                    jsonObject.put("ypsl","5");
                    jsonObject.put("ypdj","10");
                    jsonObject.put("hjje","9.99");
                    jsonObject.put("yfdw","盒");
                    jsonObject.put("mrcs","2");
                    jsonObject.put("yfbz","消化科");
                    jsonObject.put("ypyf","X1552155");//给药途径
                    jsonObject.put("ycjl","X1552155");
                    jsonObject.put("yyts","X1552155");
                    jsonObject.put("sbxh","X1552155");
                    jsonObject.put("yfgg","X1552155");
                    array1.add(jsonObject);
                    rs1.put("status","200");
                    rs1.put("detailModelList",array);
                }else {
                    Map<String,Object> params1 = new HashedMap();
                    params1.put("sql",msd02);
                    HttpResponse response1 = HttpUtils.doGet(url,params1);
                    String content1 = response1.getContent();
                    logger.info("response:"+content);
                    rs1 = JSON.parseObject(content1);
                }


                Integer status1 = rs1.getInteger("status");
                List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
                if(status1!=null&&status1 == 200){
                    JSONArray array1 =  rs1.getJSONArray("detailModelList");
                    logger.info("info"+rs1.getJSONArray("detailModelList"));
                    for (int i =0;i<array1.size();i++){
                        JSONObject object1 = array1.getJSONObject(i);
                        WlyyPrescriptionInfoVO prescriptionInfoVO = new WlyyPrescriptionInfoVO();
                        String sql = "SELECT ypxh as \"ypxh\",ypmc2 as \"ypmc2\" from V_hlwyy_MZ_YPXX WHERE ypxh='"+object1.getString("ypxh")+"' ";

                        JSONObject rs4 = new JSONObject();

                        if (demoFlag){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("ypxh","X456225");
                            jsonObject.put("ypmc2","板蓝根");
                            JSONArray array2 = new JSONArray();
                            rs4.put("detailModelList",array2);
                            rs4.put("status",200);
                        }else {
                            Map<String,Object> params4 = new HashedMap();
                            params4.put("sql",sql);
                            HttpResponse response4 = HttpUtils.doGet(url,params4);
                            String content4 = response4.getContent();
                            logger.info("response:"+content4);
                            rs4 = JSON.parseObject(content4);
                        }

                        Integer status4 = rs4.getInteger("status");
                        if(status4!=null&&status4 == 200){
                            JSONArray array4 =  rs4.getJSONArray("detailModelList");
                            logger.info("info"+rs4.getJSONArray("detailModelList"));
                            if (array4!=null&&array4.size()!=0){
                                JSONObject jsonObject = array4.getJSONObject(0);
                                prescriptionInfoVO.setDrugName(jsonObject.getString("ypmc2"));
                            }
                        }
                        prescriptionInfoVO.setDrugNo(object1.getString("ypxh"));
                        prescriptionInfoVO.setDrugPlace(object1.getString("ypcd"));
                        prescriptionInfoVO.setQuantity(object1.getString("ypsl"));
                        prescriptionInfoVO.setPackRetprice(object1.getDouble("ypdj"));
                        prescriptionInfoVO.setPackUnitName(object1.getString("yfdw"));
                        prescriptionInfoVO.setUnitName(object1.getString("yfdw"));
                        prescriptionInfoVO.setDosage(object1.getString("ycjl"));
                        prescriptionInfoVO.setSupplyCode(object1.getString("gytj"));
                        JSONArray ypyfList = findYpyf("",object1.getString("gytj"));
                        if (ypyfList!=null&&ypyfList.size()>0){
                            JSONObject map = ypyfList.getJSONObject(0);
                            logger.info("setSupplyName+++"+map.get("xmmc").toString());
                            prescriptionInfoVO.setSupplyName(map.get("xmmc").toString());
                        }
                        prescriptionInfoVO.setUsageCode(object1.getString("ypyf"));
                        JSONArray sypcList = findSypc(object1.getString("ypyf"));
                        if (sypcList!=null&&sypcList.size()>0){
                            JSONObject sypcmap = sypcList.getJSONObject(0);
                            logger.info("setUsageName+++"+sypcmap.get("pcmc1").toString());
                            prescriptionInfoVO.setUsageName(sypcmap.get("pcmc1").toString());
                        }
                        prescriptionInfoVO.setPackQuantity(object1.getInteger("yfbz"));
                        prescriptionInfoVO.setDays(object1.getString("yyts"));
                     /*   prescriptionInfoVO.setYpyf(object1.getInteger("ypyf"));*/
                        prescriptionInfoVO.setHisCode(object1.getInteger("sbxh"));
                        prescriptionInfoVO.setSpecification(object1.getString("yfgg"));
                        wlyyPrescriptionInfoVOS.add(prescriptionInfoVO);
                    }
                }
                wlyyPrescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
                List<WlyyPrescriptionDiagnosisVO> diagnosisVOS = new ArrayList<>();
                String mz = "SELECT ICD AS \"icd\",MSZD AS \"mszd\",JZXH AS \"jzxh\" FROM v_hlwys_mz_jbzd WHERE jzxh = '"+admNo+"'";
                JSONObject rs2 =new JSONObject();
                if (demoFlag){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("icd","250465322053223");
                    jsonObject.put("mszd","感冒");
                    jsonObject.put("jzxh","JZ25521875232");
                    JSONArray array1 = new JSONArray();
                    array1.add(jsonObject);
                    rs2.put("status",200);
                    rs2.put("detailModelList",array1);
                }else {
                    Map<String,Object> params2 = new HashedMap();
                    params2.put("sql",mz);
                    HttpResponse response2 = HttpUtils.doGet(url,params2);
                    String content2 = response2.getContent();
                    logger.info("response:"+content2);
                    rs2 = JSON.parseObject(content2);
                }
                Integer status2 = rs2.getInteger("status");
                if(status2!=null&&status2 == 200){
                    JSONArray array2 = rs2.getJSONArray("detailModelList");
                    for (int i=0;i<array2.size();i++){
                        JSONObject object2 = array2.getJSONObject(i);
                        WlyyPrescriptionDiagnosisVO diagnosisVO = new WlyyPrescriptionDiagnosisVO();
                        diagnosisVO.setCode(object2.getString("icd"));
                        diagnosisVO.setName(object2.getString("mszd"));
                        diagnosisVOS.add(diagnosisVO);
                    }
                }
                wlyyPrescriptionVO.setDiagnosisVOs(diagnosisVOS);
                wlyyPrescriptionVOList.add(wlyyPrescriptionVO);
            }
        }
        return wlyyPrescriptionVOList;
    }

    public String updateYkyyDoctor(String idCard)throws Exception{
        String sql ="select y.code AS \"code\",y.name AS \"name\",y.expertise AS \"expertise\",y.introduce AS \"introduce\",y.mobile AS \"mobile\",y.idCard AS \"idcard\",y.jobtitlecode AS \"jobTitleCode\",y.jobTitleName AS \"jobTitleName\",y.dept AS \"dept\",y.deptName AS \"deptName\" from v_Hlw_Ysxx y where y.idcard is not null";
        if (StringUtils.isNoneBlank(idCard)){
            sql +=" and y.idcard ='"+idCard+"' ";
        }
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            JSONArray array = rs.getJSONArray("detailModelList");
            logger.info("doctor size:"+array.size());
            if(array!=null&&array.size()>0) {
                for (int i = 0; i < array.size(); i++) {
                    JSONObject doctorJson = array.getJSONObject(i);
                    String idcard = doctorJson.getString("idcard");

                    //过滤身份证脏数据
                    if(idcard.length()>=15){

                        List<BaseDoctorDO> doctorDOs = baseDoctorDao.findByIdcard(idcard);

                        if(doctorDOs!=null&&doctorDOs.size()>0){

                            BaseDoctorDO doctor = doctorDOs.get(0);

                            String salt = randomString(5);
                            String pw = idcard.substring(idcard.length() - 6);
                            doctor.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                            doctor.setSalt(salt);

                            doctor.setJobTitleCode(doctorJson.getString("jobtitlecode"));
                            doctor.setJobTitleName(doctorJson.getString("jobTitleName"));
//                            doctor.setExpertise(doctorJson.getString("expertise"));
//                            doctor.setIntroduce(doctorJson.getString("introduce"));
//                            doctor.setMobile(doctorJson.getString("mobile"));

                            BaseDoctorDO temp = baseDoctorDao.save(doctor);

                            List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode(orgCode,doctorJson.getString("dept"),doctor.getId());
                            if(hospitalDOs!=null&&hospitalDOs.size()>0){
                                //机构信息部门信息
                                BaseDoctorHospitalDO hospitalDO = hospitalDOs.get(0);
                                hospitalDO.setDeptCode(doctorJson.getString("dept"));
                                hospitalDO.setDeptName(doctorJson.getString("deptName"));
                                hospitalDO.setDel("1");
                                baseDoctorHospitalDao.save(hospitalDO);
                            }


                        }else{
                            //新增医生
                            BaseDoctorDO doctor = new BaseDoctorDO();
                            doctor.setName(doctorJson.getString("name"));
                            doctor.setIdcard(idcard);

                            doctor.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(idcard)));
                            doctor.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));

                            doctor.setProvinceCode("350000");
                            doctor.setProvinceName("福建省");
                            doctor.setTownCode("350203");
                            doctor.setTownName("思明区");
                            doctor.setCityCode("350200");
                            doctor.setCityName("厦门市");
//                            doctor.setExpertise(doctorJson.getString("expertise"));
//                            doctor.setIntroduce(doctorJson.getString("introduce"));
//                            doctor.setMobile(doctorJson.getString("mobile"));
                            //认证信息设置
                            String salt = randomString(5);
                            String pw = idcard.substring(idcard.length() - 6);
                            doctor.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                            doctor.setSalt(salt);
                            doctor.setDel("1");
                            doctor.setEnabled(1);
                            doctor.setLocked(0);
                            doctor.setCreateTime(new Date());

                            doctor.setJobTitleCode(doctorJson.getString("jobtitlecode"));
                            doctor.setJobTitleName(doctorJson.getString("jobTitleName"));

                            BaseDoctorDO temp = baseDoctorDao.save(doctor);

                            //机构信息部门信息
                            BaseDoctorHospitalDO hospitalDO = new BaseDoctorHospitalDO();
                            hospitalDO.setDoctorCode(temp.getId());
                            hospitalDO.setOrgCode(orgCode);
                            hospitalDO.setOrgName(orgName);
                            hospitalDO.setDeptCode(doctorJson.getString("dept"));
                            hospitalDO.setDeptName(doctorJson.getString("deptName"));
                            hospitalDO.setDel("1");
                            baseDoctorHospitalDao.save(hospitalDO);

                            //保存角色
                            BaseDoctorRoleDO role = new BaseDoctorRoleDO();
                            role.setDoctorCode(temp.getId());
                            role.setRoleCode("specialist");
                            baseDoctorRoleDao.save(role);

                            //保存mapping
                            DoctorMappingDO mappingDO = new DoctorMappingDO();
                            mappingDO.setIdcard(idcard);
                            mappingDO.setDoctor(temp.getId());
                            mappingDO.setDoctorName(temp.getName());

                            mappingDO.setOrgCode(orgCode);
                            mappingDO.setOrgName(orgName);

                            mappingDO.setMappingCode(doctorJson.getString("code"));
                            mappingDO.setMappingName(temp.getName());
                            mappingDO.setCreateTime(new Date());

                            doctorMappingDao.save(mappingDO);
                        }
                    }
                }
            }
        }
        return "success";
    }


    public String updateYkTDoctor(String fastdfs_file_url)throws Exception{
        List<BaseDoctorDO> baseDoctorDOS = baseDoctorDao.findByDel();
        for (BaseDoctorDO baseDoctorDO:baseDoctorDOS){
            String response="";
            String url = "http://www.yanketong.com:133/api/doc_jkzl/doctor_list_had_bind_account?hospital_code=sb&page=1&id_card="+baseDoctorDO.getIdcard();
            response = httpClientUtil.get(url,"GBK");
            logger.info("response:"+response);
            JSONObject rs = JSON.parseObject(response);
            Integer status = rs.getInteger("code");
            if(status!=null&&status == 200){
                JSONObject object = rs.getJSONObject("data");
                JSONArray array = object.getJSONArray("list");
                if (array!=null&&array.size()!=0){
                    JSONObject jsonObject = array.getJSONObject(0);
                    DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(baseDoctorDO.getId());
                    String mappingCode = jsonObject.getString("DOCTORCODE");
                    String photo = jsonObject.getString("doctor_image");
                    if (StringUtils.isNoneBlank(photo)){
                        String name = photo.substring(photo.lastIndexOf("/")+1,photo.length());
                        logger.info("name"+name);
                        InputStream inputStream = fileUploadService.getInputStream(photo);
                        UploadVO uploadVO = new UploadVO();
                        uploadVO = fileUploadService.uploadStream(inputStream,name,fastdfs_file_url);
                        baseDoctorDO.setPhoto(uploadVO.getFullUri());
                    }
                    if (doctorMappingDO==null){
                        doctorMappingDO = new DoctorMappingDO();
                        doctorMappingDO.setMappingCode(mappingCode);
                        doctorMappingDO.setCreateTime(new Date());
                        doctorMappingDO.setDoctor(baseDoctorDO.getId());
                        doctorMappingDO.setDoctorName(baseDoctorDO.getName());
                        doctorMappingDO.setOrgCode("350211A5004");
                        doctorMappingDO.setMappingName(baseDoctorDO.getName());
                        doctorMappingDO.setOrgName("厦门大学附属厦门眼科中心");
                    }else {
                        doctorMappingDO.setMappingCode(mappingCode);
                    }
                    doctorMappingDao.save(doctorMappingDO);
                }else {
                    baseDoctorDO.setDel("0");
                }
                baseDoctorDao.save(baseDoctorDO);
            }
        }
        return "success";
    }




    public String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();

        for(int i = 0; i < length; ++i) {
            int pos = random.nextInt(str.length());
            buffer.append(str.charAt(pos));
        }

        return buffer.toString();
    }

    public String getCFXX(String brids,String ysdm,String startDate)throws Exception{
        BaseDoctorDO doctor = findByMapingCode(ysdm);
        if(doctor==null){
            return "doctor mapping not exist !";
        }
        BaseDoctorHospitalDO hospitalDO = getDept(doctor.getId());
        if(hospitalDO==null){
            return "hospital not exist!";
        }

        String sql ="SELECT " +
                " c.BRID," +
                " c.CFHM," +
                " c.TSCF," +
                " c.BRXM," +
                " c.YSDM," +
                " c.KSDM," +
                " c.YPMC," +
                " c.YPDJ," +
                " c.YPSL," +
                " c.HJJE," +
                " c.JZXH," +
                " c.FPHM," +
                " c.FYBZ," +
                " c.YPCD," +
                " c.YPXH," +
                " c.YPYF," +
                " d.ICD," +
                " d.JBMC," +
                " x.YPDM," +
                " x.YFGG," +
                " x.YFDW," +
                " x.YFBZ," +
                " x.YPSX," +
                " x.YPJL," +
                " x.JLDW," +
                " x.PYDM," +
                " x.FYFS," +
                " x.GYFF," +
                " x.GYFFMC," +
                " x.YFZF," +
                " x.LSJG," +
                " x.KCSL," +
                " x.ZFPB," +
                " x.JBYWBZ," +
                " x.YDYP," +
                " x.YPMC2," +
                " p.JZKH " +
                "FROM " +
                " V_ZKSG_CFCX c, " +
                " v_hlw_mzbrzd d, " +
                " V_hlwyy_MZ_YPXX x," +
                " V_ZKSG_BRCX p " +
                "WHERE " +
                " c.BRID = d.BRID " +
                " AND c.jzxh = d.jzxh " +
                " AND c.ysdm = '"+ysdm+"' " +
                " AND x.ypxh = c.ypxh  " +
                " AND x.ypcd = c.ypcd " +
                " AND p.BRID = c.BRID " +
                " AND c.BRID in  ("+brids+") order by c.BRID DESC";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        Map<String,String> map = new HashedMap();
        if(status!=null&&status == 200){
            JSONArray array = rs.getJSONArray("detailModelList");
            logger.info("detailModelList size:"+array.size());
            if(array!=null&&array.size()>0) {
                for(int i= 0;i<array.size();i++){
                    JSONObject cfxx = array.getJSONObject(i);
                    String brid = cfxx.getString("BRID");
                    BasePatientDO patientDO = findPatientByMapingCode(brid);
                    if(patientDO!=null){
                        if(map.get(brid)==null){
                            map.put(brid,brid);
                            logger.info("1.创建门诊记录");
                            //1.创建门诊记录
                            WlyyOutpatientDO outpatientDO = saveOutPatient(cfxx,hospitalDO,patientDO,doctor,startDate);

                            logger.info("2.生成处方记录");
                            //2.生成处方记录
                            savePrescription(outpatientDO,cfxx,startDate);

                            logger.info("3.医生评价");
                            //3.医生评价
                            saveDoctorScore(outpatientDO);

                        }
                    }else{
                        logger.info("brid:"+brid+" mapping not exist");
                    }
                }
            }
        }
        return "ok";
    }

    //生成门诊信息
    public WlyyOutpatientDO saveOutPatient(JSONObject cfxx,BaseDoctorHospitalDO hospitalDO,BasePatientDO patientDO,BaseDoctorDO doctor,String startDate){

        WlyyOutpatientDO outpatientDO = new WlyyOutpatientDO();
        outpatientDO.setRegisterNo(cfxx.getString("JZXH"));
        outpatientDO.setOutpatientType("1");
        outpatientDO.setType("1");
        outpatientDO.setHospital(orgCode);
        outpatientDO.setHospitalName(orgName);
        outpatientDO.setDept(hospitalDO.getDeptCode());
        outpatientDO.setDeptName(hospitalDO.getDeptName());

        outpatientDO.setPatient(patientDO.getId());
        outpatientDO.setPatientName(patientDO.getName());
        outpatientDO.setDoctor(doctor.getId());
        outpatientDO.setDoctorName(doctor.getName());

        outpatientDO.setIdcard(patientDO.getIdcard());
        outpatientDO.setMjz("mz");
        outpatientDO.setIcd10(cfxx.getString("ICD"));
        outpatientDO.setIcd10Name(cfxx.getString("JBMC"));
        outpatientDO.setAdvice("注意休息，防止过度疲劳");

        outpatientDO.setStatus("2");

        outpatientDO.setDescription("身体不舒服，焦虑");
        outpatientDO.setCreateTime(DateUtil.strToDate(startDate+" 08:30:00","yyyy-MM-dd HH:mm:ss"));
        outpatientDO.setDiseaseImg("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583567535353&di=6529f7ff05e79c26f37e0176adcb3241&imgtype=0&src=http%3A%2F%2Fimages.669pic.com%2Felement_pic%2F74%2F70%2F44%2F48%2F8997cd56af062ce6e1ca3da37506f3c9.jpg");

        outpatientDO.setConNo(cfxx.getString("JZXH"));
        outpatientDO.setRegisterDate(DateUtil.strToDate(startDate+" 08:30:00","yyyy-MM-dd HH:mm:ss"));
        outpatientDO.setEvaluateStatus("1");
        outpatientDO.setEndTime(DateUtil.strToDate(startDate+" 09:30:00","yyyy-MM-dd HH:mm:ss"));

        outpatientDO.setAdmNo("001");

        return outpatientDao.save(outpatientDO);
    }

    public void savePrescription(WlyyOutpatientDO outpatientDO,JSONObject cfxx,String startDate){
        WlyyPrescriptionDO prescriptionDO = new WlyyPrescriptionDO();

        prescriptionDO.setOutpatientId(outpatientDO.getId());
        prescriptionDO.setRealOrder(cfxx.getString("CFHM"));
        prescriptionDO.setSerialNo(cfxx.getString("JZXH"));
        prescriptionDO.setType(1);
        prescriptionDO.setPatientCode(outpatientDO.getPatient());
        prescriptionDO.setPatientName(outpatientDO.getPatientName());
        prescriptionDO.setIdcard(outpatientDO.getIdcard());
        prescriptionDO.setSsc(outpatientDO.getCardNo());
        prescriptionDO.setDoctor(outpatientDO.getDoctor());
        prescriptionDO.setDoctorName(outpatientDO.getDoctorName());
        prescriptionDO.setStatus(100);

        prescriptionDO.setCreateTime(DateUtil.strToDate(startDate+" 09:00:00","yyyy-MM-dd HH:mm:ss"));
        prescriptionDO.setDept(outpatientDO.getDept());
        prescriptionDO.setDeptName(outpatientDO.getDeptName());
        prescriptionDO.setHospital(outpatientDO.getHospital());
        prescriptionDO.setHospitalName(outpatientDO.getHospitalName());

        prescriptionDO.setRemark("001");

        prescriptionDO.setDiseaseImg("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583567535353&di=6529f7ff05e79c26f37e0176adcb3241&imgtype=0&src=http%3A%2F%2Fimages.669pic.com%2Felement_pic%2F74%2F70%2F44%2F48%2F8997cd56af062ce6e1ca3da37506f3c9.jpg");
        prescriptionDO.setDrugFee(cfxx.getDouble("HJJE"));
        prescriptionDO.setInspectFee(0D);
        prescriptionDO.setRegFee(0D);

        WlyyPrescriptionDO temp = prescriptionDao.save(prescriptionDO);

        WlyyPrescriptionInfoDO info = new WlyyPrescriptionInfoDO();

        info.setPrescriptionId(temp.getId());

        info.setDrugNo(cfxx.getString("PYDM"));
        info.setDrugName(cfxx.getString("YPMC"));
        info.setDosage(cfxx.getString("YPJL"));
        info.setQuantity(cfxx.getString("YPSL"));
        //计量单位
        info.setUnitName(cfxx.getString("JLDW"));
        //包装单位
        info.setPackUnitName(cfxx.getString("YFDW"));
        //用法
        info.setSupplyCode(cfxx.getString("GYFF"));
        info.setSupplyName(cfxx.getString("GYFFMC"));
        //规格
        info.setSpecification(cfxx.getString("YFGG"));
        info.setDel(1);
        info.setUsageCode(cfxx.getString("YPYF"));
        info.setUsageName(cfxx.getString("YPYF"));
        //药品单价
        info.setPackRetprice(cfxx.getDouble("YPDJ"));

        info.setComm("001");

        prescriptionInfoDao.save(info);
    }

    public void saveDoctorScore(WlyyOutpatientDO outpatientDO){
        BaseEvaluateScoreDO scoreDO = new BaseEvaluateScoreDO();
        scoreDO.setHospital(orgCode);
        scoreDO.setHospital(orgName);

        scoreDO.setDoctor(outpatientDO.getDoctor());
        scoreDO.setDoctorName(outpatientDO.getDoctorName());
        scoreDO.setPatient(outpatientDO.getPatient());
        scoreDO.setPatientName(outpatientDO.getPatientName());

        scoreDO.setEvaluateType(1);
        scoreDO.setScore(100D);
        scoreDO.setType(1);

        scoreDO.setRelationCode("001");

        BaseEvaluateScoreDO temp = baseEvaluateScoreDao.save(scoreDO);

        BaseEvaluateDO evaluateDO = new BaseEvaluateDO();
        evaluateDO.setRelationCode(temp.getId());
        evaluateDO.setScore(1D);
        evaluateDO.setScoreType("4");
        evaluateDO.setContent("五星好评！");

        baseEvaluateDao.save(evaluateDO);
    }

    /**
     * 获取医生信息
     * @param mappingCode
     * @return
     */
    public BaseDoctorDO findByMapingCode(String mappingCode){

        String sql = "SELECT " +
                " map.doctor AS \"doctor\" " +
                " FROM " +
                " base_doctor_mapping map " +
                " WHERE " +
                " map.org_code ='350211A5004' " +
                " AND map.mapping_code ='"+mappingCode+"' ";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        if(list!=null&&list.size()>0){
            BaseDoctorDO doctorDO = baseDoctorDao.findById(list.get(0).get("doctor").toString());
            return doctorDO;
        }
        return null;
    }

    //获取部门
    public BaseDoctorHospitalDO getDept(String doctor){
        List<BaseDoctorHospitalDO> list =  baseDoctorHospitalDao.findByDoctorCode(doctor);
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }

    //获取居民信息
    public BasePatientDO findPatientByMapingCode(String mappingCode){
        PatientMappingDO patientMappingDO = patientMappingDao.findByMappingCodeAndSource(mappingCode,"1");
        if(patientMappingDO==null){
            return null;
        }
        BasePatientDO patientDO = basePatientDao.findById(patientMappingDO.getPatient());
        return patientDO;
    }


    /**
     * 查询药品信息
     * @param ypdm
     * @param ypmc
     * @param kusl
     * @return
     */
    public JSONArray findYkYpxx(String ypdm,String ypmc,String kusl,String pydm ,String hisCode) throws Exception {
        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\"," +
                "yp.gyffmc as \"gyffmc\"," +
                "yp.pzwh as \"pzwh\","+
                "yp.yfsb as \"yfsb\""+" FROM " +
                "V_hlwyy_MZ_YPXX yp where 1=1 and yp.yfsb in(9,10)  ";
        if (StringUtils.isNoneBlank(ypdm)){
            sql+=" and lower(yp.ypdm) like '%"+ypdm.toLowerCase()+"%' ";
        }
        if (StringUtils.isNoneBlank(ypmc)){
            sql+=" and lower(yp.ypmc) like '%"+ypmc.toLowerCase()+"%' ";
        }
        if (StringUtils.isNoneBlank(kusl)){
            sql+=" and lower(yp.kusl) like '%"+kusl.toLowerCase()+"%' ";
        }

        if (StringUtils.isNoneBlank(pydm)){
            sql+=" and lower(yp.pydm) like '%"+pydm.toLowerCase()+"%' ";
        }
        if (StringUtils.isNoneBlank(hisCode)){
            sql+=" and lower(yp.yfsb) like '%"+hisCode.toLowerCase()+"%' ";
        }
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("ypxx："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
             array = rs.getJSONArray("detailModelList");
        }
       /* List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);*/
        return array;
    }


    /**
     * 查询检查项目
     *
     * @return
     */
    public JSONArray findYkJcxm(String pydm) throws Exception {
        String sql ="SELECT\n" +
                "\tmz.zlxmid AS \"zlxmid\",\n" +
                "\tmz.xmmc AS \"xmmc\",\n" +
                "\tmz.pydm AS \"pydm\",\n" +
                "\tmz.wbdm AS \"wbdm\",\n" +
                "\tmz.jxdm AS \"jxdm\",\n" +
                "\tmz.qtdm AS \"qtdm\",\n" +
                "\tmz.ydyzlb AS \"ydyzlb\",\n" +
                "\tmz.mlbh AS \"mlbh\",\n" +
                "\tmz.zxpc AS \"zxpc\",\n" +
                "\tmz.jfpc AS \"jfpc\",\n" +
                "\tmz.jsfs AS \"jsfs\",\n" +
                "\tmz.jszq AS \"jszq\",\n" +
                "\tmz.jsdw AS \"jsdw\",\n" +
                "\tmz.syxb AS \"syxb\",\n" +
                "\tmz.mxsy AS \"mxsy\",\n" +
                "\tmz.zysy AS \"zysy\",\n" +
                "\tmz.tjsy AS \"tjsy\",\n" +
                "\tmz.zxlb AS \"zxlb\",\n" +
                "\tmz.zxks AS \"zxks\",\n" +
                "\tmz.zxgzid AS \"zxgzid\",\n" +
                "\tmz.ywzx AS \"ywzx\",\n" +
                "\tmz.zxap AS \"zxap\",\n" +
                "\tmz.cpzx AS \"cpzx\",\n" +
                "\tmz.szzx AS \"szzx\",\n" +
                "\tmz.jjlx AS \"jjlx\",\n" +
                "\tmz.ycxzsl AS \"ycxzsl\",\n" +
                "\tmz.yblx AS \"yblx\",\n" +
                "\tmz.zxbz AS \"zxbz\",\n" +
                "\tmz.txid AS \"txid\",\n" +
                "\tmz.bgbh AS \"bgbh\",\n" +
                "\tmz.czsy AS \"czsy\",\n" +
                "\tmz.lzsy AS \"lzsy\",\n" +
                "\tmz.lccs AS \"lccs\",\n" +
                "\tmz.bwbz AS \"bwbz\",\n" +
                "\tmz.yblb AS \"yblb\"\n" +
                "FROM\n" +
                "\tV_ZKSG_JCXM_MZ mz where 1=1 ";
        if (StringUtils.isNoneBlank(pydm)){
            sql+=" and lower(pydm) like '%"+pydm.toLowerCase()+"%'";
        }
        /*List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);*/
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("ypxx："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }


    /**
     * 获取频次
     * @return
     */
    public JSONArray findSypc(String pcbm) throws Exception {
        String sql = "select s.mrcs as \"mrcs\",s.pcbm as \"pcbm\",s.pcmc as \"pcmc\",s.pcmc1 as \"pcmc1\" from v_hlw_sypc s where 1=1 ";
        if (StringUtils.isNoneBlank(pcbm)){
            sql+=" and lower(s.pcbm)='"+pcbm.toLowerCase()+"' ";
        }
        /*List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;*/
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("ypxx："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }

    /**
     * 获取用法
     * @return
     */
    public JSONArray findYpyf(String pydm,String ypyf) throws Exception {
        String sql = "select y.ypyf as \"ypyf\",y.pydm as \"pydm\",y.xmmc as \"xmmc\" from v_hlw_ypyf y where 1=1  and y.pydm is not null";
        if (StringUtils.isNoneBlank(pydm)){
            sql+=" and lower(y.pydm)='"+pydm.toLowerCase()+"' ";
        }
        if (StringUtils.isNoneBlank(ypyf)){
            sql+=" and lower(y.ypyf)="+ypyf.toLowerCase()+" ";
        }
        /*List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;*/
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("ypxx："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }


    /**
     * 获取his病人信息
     * @param ssc
     * @return
     * @throws Exception
     */
    public JSONArray findHisPatient(String ssc,boolean demoFlag) throws Exception {
        String sql = "SELECT\n" +
                "\tx.brid AS \"brid\",\n" +
                "\tx.mzhm AS \"mzhm\",\n" +
                "\tx.brxm AS \"brxm\",\n" +
                "\tx.sfzh AS \"sfzh\",\n" +
                "\tx.brxz AS \"brxz\",\n" +
                "\tx.brxb AS \"brxb\",\n" +
                "\tx.csny as \"csny\",\n" +
                "\tx.jzkh AS \"jzkh\",\n" +
                "\tx.jdsj AS \"jdsj\",\n" +
                "\tx.sjhm AS \"sjhm\",\n" +
                "\tx.fzxmc AS \"fzxmc\",\n" +
                "\tx.gzztmc AS \"gzztmc\",\n" +
                "\tx.lxdz AS \"lxdz\"\n" +
                "FROM\n" +
                "\tV_ZKSG_BRCX x\n" +
                "WHERE\n" +
                "\tx.jzkh = '"+ssc+"' ";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("brid","1168517");
            jsonObject.put("mzhm","0502452155");
            jsonObject.put("brxm","于小童");
            jsonObject.put("sfzh","450521199405092535");
            jsonObject.put("brxz","自费");
            jsonObject.put("brxb","男");
            jsonObject.put("csny","1994-05-09");
            jsonObject.put("jzkh","2396501");
            jsonObject.put("jdsj","2020-06-28 15:15:35");
            jsonObject.put("gzztmc","一般");
            jsonObject.put("lxdz","厦门市五缘湾");
            array.add(jsonObject);
        }else  {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }

        return array;
    }


    /**
     * 获取his病人信息--身份证/卡号
     * @param ssc
     * @return
     * @throws Exception
     */
    public JSONArray findHisPatientBySscAndIdcard(String ssc,String idcard,boolean demoFlag) throws Exception {
        String sql = "SELECT\n" +
                "\tx.brid AS \"brid\",\n" +
                "\tx.mzhm AS \"mzhm\",\n" +
                "\tx.brxm AS \"brxm\",\n" +
                "\tx.sfzh AS \"sfzh\",\n" +
                "\tx.brxz AS \"brxz\",\n" +
                "\tx.brxb AS \"brxb\",\n" +
                "\tx.csny as \"csny\",\n" +
                "\tx.jzkh AS \"jzkh\",\n" +
                "\tx.jdsj AS \"jdsj\",\n" +
                "\tx.sjhm AS \"sjhm\",\n" +
                "\tx.fzxmc AS \"fzxmc\",\n" +
                "\tx.gzztmc AS \"gzztmc\",\n" +
                "\tx.lxdz AS \"lxdz\"\n" +
                "FROM\n" +
                "\tV_ZKSG_BRCX x\n" +
                "WHERE\n" +
                "\t(x.jzkh = '"+ssc+"' or x.MZHM='"+ssc+"') and x.sfzh ='"+idcard+"'";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("brid","1168517");
            jsonObject.put("mzhm","0502452155");
            jsonObject.put("brxm","于小童");
            jsonObject.put("sfzh","450521199405092535");
            jsonObject.put("brxz","自费");
            jsonObject.put("brxb","男");
            jsonObject.put("csny","1994-05-09");
            jsonObject.put("jzkh","2396501");
            jsonObject.put("jdsj","2020-06-28 15:15:35");
            jsonObject.put("gzztmc","一般");
            jsonObject.put("lxdz","厦门市五缘湾");
            array.add(jsonObject);
        }else  {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }

        return array;
    }

    /**
     * 获取his病人信息
     * @param idcard
     * @return
     * @throws Exception
     */
    public JSONArray findHisPatientByIdCard(String idcard,boolean demoFlag) throws Exception {
        String sql = "SELECT\n" +
                "\tx.brid AS \"brid\",\n" +
                "\tx.mzhm AS \"mzhm\",\n" +
                "\tx.brxm AS \"brxm\",\n" +
                "\tx.sfzh AS \"sfzh\",\n" +
                "\tx.brxz AS \"brxz\",\n" +
                "\tx.brxb AS \"brxb\",\n" +
                "\tx.csny as \"csny\",\n" +
                "\tx.jzkh AS \"jzkh\",\n" +
                "\tx.jdsj AS \"jdsj\",\n" +
                "\tx.sjhm AS \"sjhm\",\n" +
                "\tx.fzxmc AS \"fzxmc\",\n" +
                "\tx.gzztmc AS \"gzztmc\",\n" +
                "\tx.lxdz AS \"lxdz\"\n" +
                "FROM\n" +
                "\tV_ZKSG_BRCX x\n" +
                "WHERE\n" +
                "\tx.sfzh = '"+idcard+"' ";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("brid","1168517");
            jsonObject.put("mzhm","0502452155");
            jsonObject.put("brxm","于小童");
            jsonObject.put("sfzh","450521199405092535");
            jsonObject.put("brxz","自费");
            jsonObject.put("brxb","男");
            jsonObject.put("csny","1994-05-09");
            jsonObject.put("jzkh","2396501");
            jsonObject.put("jdsj","2020-06-28 15:15:35");
            jsonObject.put("gzztmc","一般");
            jsonObject.put("lxdz","厦门市五缘湾");
            array.add(jsonObject);
        }else  {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }

        return array;
    }
    /**
     * 获取his病人信息
     * @param medicare
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONArray findHisPatientBymMedicare(String medicare,String mzhm,boolean demoFlag) throws Exception {
        String sql = "SELECT\n" +
                "\tx.brid AS \"brid\",\n" +
                "\tx.mzhm AS \"mzhm\",\n" +
                "\tx.brxm AS \"brxm\",\n" +
                "\tx.sfzh AS \"sfzh\",\n" +
                "\tx.brxz AS \"brxz\",\n" +
                "\tx.brxb AS \"brxb\",\n" +
                "\tx.csny as \"csny\",\n" +
                "\tx.jzkh AS \"jzkh\",\n" +
                "\tx.jdsj AS \"jdsj\",\n" +
                "\tx.sjhm AS \"sjhm\",\n" +
                "\tx.fzxmc AS \"fzxmc\",\n" +
                "\tx.gzztmc AS \"gzztmc\",\n" +
                "\tx.lxdz AS \"lxdz\"\n" +
                "FROM\n" +
                "\tV_ZKSG_BRCX x\n" +
                "WHERE 1=1" ;
        if (StringUtils.isNotBlank(medicare)&&StringUtils.isNotBlank(mzhm)){
            sql+=" and (x.jzkh = '"+medicare+"' or x.mzhm = '"+mzhm+"')";
        }else if (StringUtils.isNotBlank(medicare)&&!StringUtils.isNotBlank(mzhm)){
            sql+=" and x.jzkh = '"+medicare+"' ";
        }else if (!StringUtils.isNotBlank(medicare)&&StringUtils.isNotBlank(mzhm)){
            sql+=" and x.mzhm = '"+mzhm+"' ";
        }else {
            sql+=" and x.brid is null";
        }
        net.sf.json.JSONArray array = new net.sf.json.JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("brid","1168517");
            jsonObject.put("mzhm","0502452155");
            jsonObject.put("brxm","于小童");
            jsonObject.put("sfzh","450521199405092535");
            jsonObject.put("brxz","自费");
            jsonObject.put("brxb","男");
            jsonObject.put("csny","1994-05-09");
            jsonObject.put("jzkh","2396501");
            jsonObject.put("jdsj","2020-06-28 15:15:35");
            jsonObject.put("gzztmc","一般");
            jsonObject.put("lxdz","厦门市五缘湾");
            array.add(jsonObject);
        }else  {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            net.sf.json.JSONObject rs = net.sf.json.JSONObject.fromObject(content);
            Integer status = rs.getInt("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }

        return array;
    }


    /**
     * 获取his就诊卡号
     * @param idcard
     * @return
     * @throws Exception
     */
    public JSONArray findHisCard(String idcard,boolean demoFlag) throws Exception {
        String sql = "select o.pat_no as \"pat_no\",o.card_no as \"card_no\",o.card_stat as \"card_stat\",o.op_date as \"op_date\",o.card_type as \"card_type\",o.card_type_name as \"card_type_name\" from v_zksg_brcx x,V_HLW_CARDINFO o where  o.pat_no = x.mzhm and x.sfzh = '"+idcard+"'";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pat_no","P5616242-0");
            jsonObject.put("card_no","D40136791");
            jsonObject.put("card_stat","激活");
            jsonObject.put("op_date","2020-06-25 08:46:40");
            jsonObject.put("card_type","2");
            jsonObject.put("card_type_name","社保卡");
            array.add(jsonObject);
        }else {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }
        return array;
    }


    public JSONArray findIcd10(String pyCode,boolean demoFlag) throws Exception {
        String sql = "select i.code as \"code\",i.name as \"name\",i.disea_reason as \"disea_reason\",i.death_reason as \"death_reason\",i.py_code as \"py_code\",i.flag as \"flag\",i.add_code as \"add_code\",i.emr as \"emr\" from v_hlw_icd10 i";
        JSONArray array = new JSONArray();
        if (StringUtils.isNoneBlank(pyCode)){
            sql +="  where lower(i.py_code) like '%"+pyCode.toLowerCase()+"%'";
        }
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("ICD10："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("add_code","");
            jsonObject.put("code","E25.000x011");
            jsonObject.put("d_code","11-UWSRB");
            jsonObject.put("death_reason","");
            jsonObject.put("disease_reason","");
            jsonObject.put("emr","");
            jsonObject.put("name","11-羟化酶缺陷");
            jsonObject.put("py_code","11-QHMQX");
            array.add(jsonObject);
        }else {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }

        return array;
    }


    public static void main(String[] args) {
        List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
        System.out.println(wlyyPrescriptionInfoVOS.get(0).getHisCode());
    }

    public String findByRealOrder(String code,boolean demoFlag) throws Exception {
        List<WlyyPrescriptionDO>  wlyyPrescriptionDOs = prescriptionDao.findById(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(),1);
            List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
            for (WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO:wlyyPrescriptionInfoDOS){
                JSONObject object = (JSONObject) JSONObject.toJSON(wlyyPrescriptionInfoDO);
                logger.info("11111参数入参"+object.toJSONString());
                WlyyPrescriptionInfoVO prescriptionInfoVO = JSONObject.toJavaObject(object,WlyyPrescriptionInfoVO.class);
                wlyyPrescriptionInfoVOS.add(prescriptionInfoVO);
            }
            //诊断
            synPrescriptionDiagnosis(prescriptionVO,code,demoFlag);
            if (wlyyPrescriptionInfoVOS!=null&&wlyyPrescriptionInfoVOS.size()>0){
                prescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
            }else {
                System.out.println("=====setInfoVOs");
                prescriptionVO.setInfoVOs(null);
            }

            List<WlyyPrescriptionExpressageDO> expressageDOList =prescriptionExpressageDao.findByOutpatientId(wlyyPrescriptionDO.getOutpatientId());
            String drug = "";
            if (expressageDOList!=null&&expressageDOList.size()!=0){
                WlyyPrescriptionExpressageDO expressageDO = expressageDOList.get(0);
                if (1==expressageDO.getOneselfPickupFlg()){
                    if (expressageDO.getHospitalCode().equalsIgnoreCase("3")){
                        drug="9";
                    }else if (expressageDO.getHospitalCode().equalsIgnoreCase("6")){
                        drug="10";
                    }
                }else {
                    drug = "10";
                }
            }
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(code,1);
            synPrecriptionHis(prescriptionVO,code,drug);
            //同步检查检验
            if(null!=inspectionDOS&&inspectionDOS.size()>0){
                synInspect(inspectionDOS);
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
                //向患者发送检查提醒短信
                if (wlyyOutpatientDO!=null){
                    ykyySMSService.sendSmsByTempcode("inspection_remind",wlyyOutpatientDO,null,"");
                }


            }
        }

        return wlyyPrescriptionDOs.toString();

    }

    //同步检查检验
    public void  synInspect(List<WlyyInspectionDO> inspectionDOS) throws Exception {
        System.out.println("进入同步");
        List<YkEmrJcsqDO> ykEmrJcsqDOS = new ArrayList<>();
        String doctor = null;
        String patient = null;
        String admNo= null;
        String registNo=null;
        String deptNo = null;
        String prescriptionId=null;
        if (inspectionDOS!=null&&inspectionDOS.size()!=0){
            WlyyInspectionDO inspectionDO = inspectionDOS.get(0);
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(inspectionDO.getOutpatientId());
            WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(inspectionDO.getPrescriptionId());
            admNo = prescriptionDO.getAdmNo();
            registNo = prescriptionDO.getRealOrder();
            doctor=outpatientDO.getDoctor();
            patient=outpatientDO.getPatient();
            prescriptionId=prescriptionDO.getId();
        }
        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(doctor);
        String deptCode=null;
        if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
            deptCode = doctorHospitalDOS.get(0).getDeptCode();
        }
        for (WlyyInspectionDO wlyyInspectionDO:inspectionDOS){
            YkEmrJcsqDO ykEmrJcsqDO = new YkEmrJcsqDO();
            System.out.println("jcjy=="+wlyyInspectionDO.getOutpatientId());
            //ykEmrJcsqDO.setJzhm(registNo);
            if (StringUtils.isNotEmpty(admNo)){
                System.out.println("admno=="+admNo);
                ykEmrJcsqDO.setJzxh(Integer.parseInt(admNo));
            }
            ykEmrJcsqDO.setXmid(Integer.valueOf(wlyyInspectionDO.getCode()));
            JSONArray jsonArray = this.findZlxm(null,wlyyInspectionDO.getCode(),"","","");
            if (jsonArray!=null&&jsonArray.size()>0){
                JSONObject deptobject = jsonArray.getJSONObject(0);
                deptNo = deptobject.getString("dept");
            }
            //ykEmrJcsqDO.setZxks(deptNo==null?0:Integer.parseInt(deptNo));
            ykEmrJcsqDO.setZxks(wlyyInspectionDO.getDept()==null?0:Integer.parseInt(wlyyInspectionDO.getDept()));
            ykEmrJcsqDO.setJcxm(wlyyInspectionDO.getName());
            ykEmrJcsqDO.setXmdj(new BigDecimal(wlyyInspectionDO.getChargeAmount()));
            ykEmrJcsqDO.setSqsl(wlyyInspectionDO.getQuantity());
            ykEmrJcsqDO.setJclx(Integer.valueOf(wlyyInspectionDO.getCheckPart()));
            ykEmrJcsqDO.setXmdw(wlyyInspectionDO.getTotalUnit());
            ykEmrJcsqDO.setKdsj(new Date());
            ykEmrJcsqDO.setKdks(deptCode==null?0:Integer.parseInt(deptCode));
            ykEmrJcsqDOS.add(ykEmrJcsqDO);

        }
        //同步his
        logger.info("开始同步检查检验");
        Map<String,Object> message = this.outPatientOrder(ykEmrJcsqDOS,false,doctor,patient);
        System.out.println(message.get("code")+"-----"+message.get("msg"));
        if ("-1".equalsIgnoreCase(message.get("code").toString())){
           logger.info("同步检查检验失败，错误信息为："+message.get("msg").toString());
        }else {
            String msg = message.get("msg").toString();
            JSONObject object = JSONObject.parseObject(msg);
            JSONArray array = object.getJSONArray("detailModelList");
            for (int i=0;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String xmid = jsonObject.getString("xmid");
                String yjxh = jsonObject.getString("yjxh");
                List<WlyyInspectionDO> inspectionDOList = wlyyInspectionDao.findByPrescriptionIdAndCode(prescriptionId,xmid,1);
                for (WlyyInspectionDO inspectionDO:inspectionDOList){
                    inspectionDO.setHisCode(yjxh);
                    wlyyInspectionDao.save(inspectionDO);
                }
            }
        }

        System.out.println(message.get("code")+"-----"+message.get("msg"));
    }

    /**
     * 根据身份证查找his医生
     * @param idcard
     * @return
     * @throws Exception
     */
    public JSONArray findHisDoctor(String idcard) throws Exception{
        String sql ="select y.code AS \"code\",y.ygbh,y.name AS \"name\",y.expertise AS \"expertise\",y.introduce AS \"introduce\",y.mobile AS \"mobile\",y.idCard AS \"idcard\",y.jobtitlecode AS \"jobTitleCode\",y.jobTitleName AS \"jobTitleName\",y.dept AS \"dept\",y.deptName AS \"deptName\" from v_Hlw_Ysxx y where y.idcard ='"+idcard+"'";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }

    public JSONArray synYkICD10() throws Exception {
        String sql = "select i.code as \"code\",i.name as \"name\",i.disea_reason as \"disea_reason\",i.death_reason as \"death_reason\",i.py_code as \"py_code\",i.flag as \"flag\",i.add_code as \"add_code\",i.emr as \"emr\" from v_hlw_icd10 i";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("ICD10："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
            ykDictIcd10Dao.deleteAll();
            for (int i=0;i<array.size();i++){
                JSONObject object = array.getJSONObject(i);
                DictIcd10DO dictIcd10DO = new DictIcd10DO();
                dictIcd10DO.setCode(object.getString("code"));
                dictIcd10DO.setName(object.getString("name"));
                dictIcd10DO.setDescription(object.getString("py_code"));
                ykDictIcd10Dao.save(dictIcd10DO);
            }
        }
        return array;
    }

    /**
     * 根据his Icd10
     * @param code
     * @return
     * @throws Exception
     */
    public JSONArray findHisIcd10(String code) throws Exception{
        String sql ="select v.code,v.name,v.flag from V_HLW_ICD10 v WHERE v.code = '"+code.trim()+"'";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("sql："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }

    /**
     * 查找挂号明细
     * @param patient
     * @param doctor
     * @return
     * @throws Exception
     */
    public JSONArray fingHlwGhmx(String patient,String doctor) throws Exception{
        String sql = "select v.SBXH,to_char(v.ghsj,'yyyy-mm-dd hh24:mi:ss') as GHSJ from v_hlw_ghmx v where v.brid = '"+patient+"' and v.ysdm =" +
                " '"+doctor+"' and v.ghsj > to_date('"+DateUtil.dateToStrLong(DateUtil.getToday())+"','yyyy-MM-dd HH24:mi:ss')";
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("sql："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }


    public void saveKsjc(BaseNatAppointmentDO natAppointmentDO,Boolean demoFlag) throws Exception {

        BigDecimal bigDecimal = new BigDecimal("80");
        if (StringUtils.isNoneBlank(natAppointmentDO.getChargeAmount())){

            bigDecimal= new BigDecimal(natAppointmentDO.getChargeAmount());
        }
        List<WlyyHospitalSysDictDO> natConfigList = wlyyHospitalSysDictDao.findByDictName("natConfigList");
        String chargeCode = "12220";
        String icdCode = "Z00.001";
        String inspectionName="新冠病毒核酸检测";
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:natConfigList){
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"chargeCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                chargeCode = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"icdCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                icdCode = wlyyHospitalSysDictDO.getDictValue();
            }
        }
        if (StringUtils.isNoneBlank(natAppointmentDO.getInspectionName())){
            inspectionName = natAppointmentDO.getInspectionName();
        }
        //挂号
        Map<String,Object> map = findYkDoctor(natAppointmentDO.getHospitalFlag());
        BasePatientDO patientDO = basePatientDao.findById(natAppointmentDO.getPatientId());
        //PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(natAppointmentDO.getPatientId());
        PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",natAppointmentDO.getPatientId(),"1");
        Integer brid= 0;
        //病人性质
        Integer GHXH = 0;
        //挂号明细表HLW_GHMX
        HlwGhmxDO hlwGhmxDO = new HlwGhmxDO();
        JSONArray jsonArray = findHisPatientBySscAndIdcard(patientMedicareCardDO.getCode(),patientDO.getIdcard(),demoFlag);
        if(jsonArray!=null&&jsonArray.size()>0){
            //获取居民信息
            JSONObject json = jsonArray.getJSONObject(0);
            hlwGhmxDO.setBRXZ(json.getInteger("brxz"));
            brid = json.getInteger("brid");
        }
        hlwGhmxDO.setSBXH(0);
        hlwGhmxDO.setGHCS(1);
        hlwGhmxDO.setGHJE(0);
        hlwGhmxDO.setZLJE(0);
        hlwGhmxDO.setZJFY(0);
        hlwGhmxDO.setBLJE(0);
        hlwGhmxDO.setXJJE(0);
        hlwGhmxDO.setZPJE(0);
        hlwGhmxDO.setZHJE(0);
        hlwGhmxDO.setHBWC(0);
        hlwGhmxDO.setQTYS(0);
        hlwGhmxDO.setTHBZ(0);
        hlwGhmxDO.setCZPB(0);
        hlwGhmxDO.setMZLB(0);
        hlwGhmxDO.setYSPB(0);
        hlwGhmxDO.setSFFS(0);
        hlwGhmxDO.setJZZT(2);
        hlwGhmxDO.setJZXH(0);
        hlwGhmxDO.setKSDM(map.get("deptCode").toString());
        hlwGhmxDO.setBRID(brid);
        hlwGhmxDO.setGHSJ(new Date());//挂号时间
        hlwGhmxDO.setGHLB(1);//挂号类别
        hlwGhmxDO.setYSDM(map.get("doctorCode").toString());//医生代码
        hlwGhmxDO.setJZYS(map.get("doctorCode").toString());//接诊医生

        //获取医生信息
        hlwGhmxDO.setCZGH(map.get("doctorMappingCode").toString());


        // 同一个医生同一个病人，一天一条挂号记录。
        JSONArray ja = fingHlwGhmx(String.valueOf(brid),map.get("doctorCode").toString());
        if(ja!=null&&ja.size()>0){
            //更新
            JSONObject json = ja.getJSONObject(0);
            hlwGhmxDO.setSBXH(json.getInteger("SBXH"));
            hlwGhmxDO.setGHSJ(DateUtil.strToDate(json.getString("GHSJ")));
            GHXH = json.getInteger("SBXH");

            String jsonString = JSONObject.toJSONString(hlwGhmxDO);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","HlwGhmxDO");
            logger.info("HlwGhmxDO："+jsonString);
            HttpResponse response = HttpUtils.doGet(updateEntityUrl,params);
            if (response.getStatus()==200){
                logger.info("content"+response.getContent());
                logger.info("表hlwGhmxDo更新成功！");

            }else {
                logger.info("表hlwGhmxDo更新失败！"+response.getErrorMsg());
            }
        }else{
            //新增
            String jsonString = JSONObject.toJSONString(hlwGhmxDO);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","HlwGhmxDO");
            logger.info("HlwGhmxDO："+jsonString);
            HttpResponse response = HttpUtils.doGet(saveUrl,params);
            if (response.getStatus()==200){
                String content = response.getContent();
                logger.info("content"+content);
                JSONObject jsonObject = JSONObject.parseObject(content);
                JSONObject object = jsonObject.getJSONObject("obj");
                if (object!=null){
                    GHXH = object.getInteger("sbxh");
                    logger.info("GHXH=========="+GHXH);
                }
                logger.info("表hlwGhmxDo新增成功！");
            }
        }

        Integer icd10Flag = 0;
        //就诊历史表HLWYS_MZ_JZLS
        HlwYsMzJzLsDO hlwYsMzJzLsDO = new HlwYsMzJzLsDO();
        hlwYsMzJzLsDO.setJZXH(0);
        hlwYsMzJzLsDO.setGHXH(GHXH);
        hlwYsMzJzLsDO.setBRBH(brid);
        hlwYsMzJzLsDO.setKSDM(Integer.parseInt(map.get("deptCode").toString()));
        hlwYsMzJzLsDO.setYSDM(map.get("doctorCode").toString());
        hlwYsMzJzLsDO.setKSSJ(DateUtil.getNowDate());
        hlwYsMzJzLsDO.setJSSJ(DateUtil.getNight23());
        hlwYsMzJzLsDO.setJZZT(9);
        hlwYsMzJzLsDO.setJZLX(3);//就诊类型
        hlwYsMzJzLsDO.setZDMC("健康查体");
        hlwYsMzJzLsDO.setMQZD("健康查体");
        /*if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getAdmNo())){
            hlwYsMzJzLsDO.setJZXH(Integer.parseInt(wlyyPrescriptionVO.getAdmNo()));
        }*/
        //V_HLW_ICD10.FLAG
        JSONArray jsonArray2 = findHisIcd10(icdCode);
        if(jsonArray2!=null&&jsonArray2.size()>0){
            //获取居民信息
            JSONObject json = jsonArray2.getJSONObject(0);
            icd10Flag = json.getInteger("FLAG");

        }
        hlwYsMzJzLsDO.setZYZD(icd10Flag);
        String jsonString2 = JSONObject.toJSONString(hlwYsMzJzLsDO);
        Map<String,Object> params2 = new HashedMap();
        params2.put("json",jsonString2);
        params2.put("table","HlwYsMzJzLsDO");
        logger.info("HlwYsMzJzLsDO："+jsonString2);
        HttpResponse response2 = HttpUtils.doGet(saveUrl,params2);
        Integer jzxh = null;
        if (response2.getStatus()==200) {
            String content = response2.getContent();
            logger.info("content" + content);
            //获取就诊序号，更新处方表数据
            JSONObject jsonObject = JSONObject.parseObject(content);
            JSONObject object = jsonObject.getJSONObject("obj");
            if (object != null) {
                jzxh = object.getInteger("jzxh");
                logger.info("JZXH==========" + jzxh);
            }
            logger.info("表hlwYsMzJzLsDO同步成功！");

            //疾病诊断表HLWYS_MZ_JBZD
            HlwYsMzJbzdDO hlwYsMzJbzdDO = new HlwYsMzJbzdDO();
            //hlwYsMzJbzdDO.setJLBH(0);
            hlwYsMzJbzdDO.setYSDM(map.get("doctorCode").toString());
            hlwYsMzJbzdDO.setICD(icdCode);
            hlwYsMzJbzdDO.setMSZD("健康查体");
            hlwYsMzJbzdDO.setJBBH(icd10Flag);
            hlwYsMzJbzdDO.setBRBH(brid);
            hlwYsMzJbzdDO.setZDLB(11);//诊断类别
            hlwYsMzJbzdDO.setZDSJ(DateUtil.getNowDate());//诊断时间
            hlwYsMzJbzdDO.setZFPB(0);//作废标志
            hlwYsMzJbzdDO.setQZBZ(0);//确诊标志
            hlwYsMzJbzdDO.setQZSJ(DateUtil.getNowDate());//确诊时间
            hlwYsMzJbzdDO.setJBMC("健康查体");//诊断名称
            hlwYsMzJbzdDO.setZDLX(1);//诊断类型
            hlwYsMzJbzdDO.setTJBZ(1);//提交标志
            hlwYsMzJbzdDO.setJZXH(jzxh);

            String jsonString1 = JSONObject.toJSONString(hlwYsMzJbzdDO);
            Map<String, Object> params1 = new HashedMap();
            params1.put("json", jsonString1);
            params1.put("table", "HlwYsMzJbzdDO");
            logger.info("HlwYsMzJbzdDO：" + jsonString1);
            HttpResponse response1 = HttpUtils.doGet(saveUrl, params1);
            if (response1.getStatus() == 200) {
                String content1 = response1.getContent();
                logger.info("content" + content1);

                logger.info("表hlwYsMzJbzdDO同步成功！");
            }
        }
        //同步核酸检验
        List<YkEmrJcsqDO> ykEmrJcsqDOS = new ArrayList<>();
        YkEmrJcsqDO ykEmrJcsqDO = new YkEmrJcsqDO();
        ykEmrJcsqDO.setJzxh(jzxh);
        ykEmrJcsqDO.setXmid(Integer.valueOf(chargeCode));
        String deptNo = null;
        /*JSONArray jsonArray1 = this.findZlxm(null, "12220");
        if (jsonArray1 != null && jsonArray1.size() > 0) {
            JSONObject deptobject = jsonArray1.getJSONObject(0);
            deptNo = deptobject.getString("dept");
        }*/
        if ("3".equalsIgnoreCase(natAppointmentDO.getHospitalFlag())){
            deptNo = "96";
        }else {
            deptNo="1111";
        }
        ykEmrJcsqDO.setZxks(deptNo == null ? 0 : Integer.parseInt(deptNo));
        ykEmrJcsqDO.setJcxm(inspectionName);
        ykEmrJcsqDO.setXmdj(bigDecimal);
        ykEmrJcsqDO.setSqsl(1);
        ykEmrJcsqDO.setJclx(1);
        ykEmrJcsqDO.setXmdw("人次");
        ykEmrJcsqDO.setJbbh(icd10Flag);
        ykEmrJcsqDO.setKdsj(new Date());
        Integer brxb = 0;
        String brxm = "";
        Date csny =null;
        Integer brnl =0;
        String doctorHis="";
        Integer kdks = 0;
        /*Integer brid=0;*/
        String mzhm="0";
        JSONArray jsonArray3 = findHisPatientBySscAndIdcard(patientMedicareCardDO.getCode(),patientDO.getIdcard(),demoFlag);
        Map<String,Object> resultMap = new HashMap();
        if(jsonArray3!=null&&jsonArray3.size()>0){
            //获取居民信息
            JSONObject json = jsonArray3.getJSONObject(0);
            brxb = json.getInteger("brxb");
            brxm = json.getString("brxm");
            csny = json.getDate("csny");
            brnl = this.getBrnl(csny);
            brid=json.getInteger("brid");
            mzhm = json.getString("mzhm");

        }
        //操作医生信息
        doctorHis=map.get("doctorCode").toString();
        kdks = Integer.parseInt(map.get("deptCode").toString());
        ykEmrJcsqDO.setBrid(brid);
        ykEmrJcsqDO.setJjbz(0);
        ykEmrJcsqDO.setJczt(1);
        ykEmrJcsqDO.setZfbz(0);
        ykEmrJcsqDO.setQxbz(0);
        ykEmrJcsqDO.setBrxb(brxb);
        ykEmrJcsqDO.setBrxm(natAppointmentDO.getName());
        ykEmrJcsqDO.setBrnl(brnl);
        ykEmrJcsqDO.setKdys(doctorHis);
        ykEmrJcsqDO.setBrks(kdks);
        ykEmrJcsqDO.setTjys(doctorHis);
        ykEmrJcsqDO.setJzhm(mzhm);
        ykEmrJcsqDOS.add(ykEmrJcsqDO);
        String jsonString = JSONObject.toJSONString(ykEmrJcsqDOS);
        Map<String,Object> params = new HashedMap();
        params.put("json",jsonString);
        params.put("table","ykEmrJcsqDO");
        logger.info("ykEmrJcsqDO："+jsonString);
        HttpResponse response = HttpUtils.doGet(orderUrl,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONArray array= new JSONArray();
        if (status==200){
            array = rs.getJSONArray("detailModelList");
            JSONObject object = array.getJSONObject(0);
            String yjxh = object.getString("yjxh");
            natAppointmentDO.setRealOrder(yjxh);
            natAppointmentDO.setIsSuccess("1");
            natAppointmentDO.setDoctorId(map.get("doctorCode").toString());
            natAppointmentDO.setDoctorName(map.get("doctorName").toString());
            baseNatAppointmentDao.save(natAppointmentDO);
        }else {
        }
    }

    public Map<String,Object> findYkDoctor(String hospitalFlag){
        String sql = "select t.id as \"id\"," +
                "t.doctor_mapping_code as \"doctorMappingCode\"," +
                "t.doctor_code as \"doctorCode\"," +
                "t.dept_code as \"deptCode\"," +
                "t.start_time as \"startTime\"," +
                "t.end_time as \"endTime\"," +
                "t.doctor_name as \"doctorName\"," +
                "t.dept_name  as \"deptName\" from base_doctor_time_mapping t where 1=1 ";
        if (StringUtils.isNoneBlank(hospitalFlag)){
            sql+=" and t.hospital_flag = '"+hospitalFlag+"'";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        if (list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }


    /**
     * 诊断
     * @param wlyyPrescriptionVO
     */
    public void synPrescriptionDiagnosis(WlyyPrescriptionVO wlyyPrescriptionVO,String code,boolean demoFlag) throws Exception{
        String doctor = wlyyPrescriptionVO.getDoctor();
        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
        String patient = wlyyPrescriptionVO.getPatientCode();
        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patient);
        BasePatientDO patientDO = basePatientDao.findById(patient);
        PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patient,"1");
        if (patientMedicareCardDO==null){
            patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_02",patient,"1");
        }
        Integer GHXH = 0;
        //挂号明细表HLW_GHMX
        HlwGhmxDO hlwGhmxDO = new HlwGhmxDO();
        hlwGhmxDO.setSBXH(0);
        hlwGhmxDO.setGHCS(1);
        hlwGhmxDO.setGHJE(0);
        hlwGhmxDO.setZLJE(0);
        hlwGhmxDO.setZJFY(0);
        hlwGhmxDO.setBLJE(0);
        hlwGhmxDO.setXJJE(0);
        hlwGhmxDO.setZPJE(0);
        hlwGhmxDO.setZHJE(0);
        hlwGhmxDO.setHBWC(0);
        hlwGhmxDO.setQTYS(0);
        hlwGhmxDO.setTHBZ(0);
        hlwGhmxDO.setCZPB(0);
        hlwGhmxDO.setMZLB(0);
        hlwGhmxDO.setYSPB(0);
        hlwGhmxDO.setSFFS(0);
        hlwGhmxDO.setJZZT(2);
        hlwGhmxDO.setJZXH(0);
        hlwGhmxDO.setKSDM(wlyyPrescriptionVO.getDept());
        hlwGhmxDO.setBRID(Integer.parseInt(patientMappingDO.getMappingCode()));
        hlwGhmxDO.setGHSJ(new Date());//挂号时间
        hlwGhmxDO.setGHLB(1);//挂号类别
        hlwGhmxDO.setYSDM(doctorMappingDO.getMappingCode());//医生代码
        hlwGhmxDO.setJZYS(doctorMappingDO.getMappingCode());//接诊医生
        //病人性质
        JSONArray jsonArray = findHisPatientBySscAndIdcard(patientMedicareCardDO.getCode(),patientDO.getIdcard(),demoFlag);
        if(jsonArray!=null&&jsonArray.size()>0){
            //获取居民信息
            JSONObject json = jsonArray.getJSONObject(0);
            hlwGhmxDO.setBRXZ(json.getInteger("brxz"));
        }
        //操作工号
        JSONArray jsonArray1 = findHisDoctor(doctorMappingDO.getIdcard());
        if(jsonArray1!=null&&jsonArray1.size()>0){
            //获取医生信息
            JSONObject json = jsonArray1.getJSONObject(0);
            hlwGhmxDO.setCZGH(json.getString("YGBH"));
        }

        // 同一个医生同一个病人，一天一条挂号记录。
        JSONArray ja = fingHlwGhmx(patientMappingDO.getMappingCode(),doctorMappingDO.getMappingCode());
        if(ja!=null&&ja.size()>0){
            //更新
            JSONObject json = ja.getJSONObject(0);
            hlwGhmxDO.setSBXH(json.getInteger("SBXH"));
            hlwGhmxDO.setGHSJ(DateUtil.strToDate(json.getString("GHSJ")));
            GHXH = json.getInteger("SBXH");

            String jsonString = JSONObject.toJSONString(hlwGhmxDO);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","HlwGhmxDO");
            logger.info("HlwGhmxDO："+jsonString);
            HttpResponse response = HttpUtils.doGet(updateEntityUrl,params);
            if (response.getStatus()==200){
                logger.info("content"+response.getContent());
                logger.info("表hlwGhmxDo更新成功！");

            }else {
                logger.info("表hlwGhmxDo更新失败！"+response.getErrorMsg());
            }
        }else{
            //新增
            String jsonString = JSONObject.toJSONString(hlwGhmxDO);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","HlwGhmxDO");
            logger.info("HlwGhmxDO："+jsonString);
            HttpResponse response = HttpUtils.doGet(saveUrl,params);
            if (response.getStatus()==200){
                String content = response.getContent();
                logger.info("content"+content);
                JSONObject jsonObject = JSONObject.parseObject(content);
                JSONObject object = jsonObject.getJSONObject("obj");
                if (object!=null){
                    GHXH = object.getInteger("sbxh");
                    logger.info("GHXH=========="+GHXH);
                }
                logger.info("表hlwGhmxDo新增成功！");
            }
        }

        Integer icd10Flag = 0;
        //诊断删除v_hlwys_mz_jzls
        if (!StringUtils.isNoneBlank(wlyyPrescriptionVO.getAdmNo())){
           /* String deleteSql = "delete from v_hlwys_mz_jzls where jzxh = '"+wlyyPrescriptionVO.getAdmNo()+"'";
            Map<String,Object> params = new HashedMap();
            params.put("sql",deleteSql);
            HttpResponse response = HttpUtils.doGet(updateUrl,params);
            if (response.getStatus()==200){
                logger.info("表v_hlwys_mz_jzls删除成功！");
            }*/
            List<WlyyPrescriptionDiagnosisDO> diagnosisDOs = prescriptionDiagnosisDao.findByPrescriptionId(code,1);
            if(diagnosisDOs!=null&&diagnosisDOs.size()>0){
                WlyyPrescriptionDiagnosisDO diagnosisDO = diagnosisDOs.get(0);

                //就诊历史表HLWYS_MZ_JZLS
                HlwYsMzJzLsDO hlwYsMzJzLsDO = new HlwYsMzJzLsDO();
                hlwYsMzJzLsDO.setJZXH(0);
                hlwYsMzJzLsDO.setGHXH(GHXH);
                hlwYsMzJzLsDO.setBRBH(Integer.parseInt(patientMappingDO.getMappingCode()));
                hlwYsMzJzLsDO.setKSDM(Integer.parseInt(wlyyPrescriptionVO.getDept()));
                hlwYsMzJzLsDO.setYSDM(doctorMappingDO.getMappingCode());
                hlwYsMzJzLsDO.setKSSJ(DateUtil.strToDate(DateUtil.dateToStr(wlyyPrescriptionVO.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));
                hlwYsMzJzLsDO.setJSSJ(DateUtil.getNight23());
                hlwYsMzJzLsDO.setJZZT(9);
                hlwYsMzJzLsDO.setJZLX(3);//就诊类型
                hlwYsMzJzLsDO.setZDMC(diagnosisDO.getName());
                hlwYsMzJzLsDO.setMQZD(diagnosisDO.getName());
                if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getAdmNo())){
                    hlwYsMzJzLsDO.setJZXH(Integer.parseInt(wlyyPrescriptionVO.getAdmNo()));
                }
                //V_HLW_ICD10.FLAG
                JSONArray jsonArray2 = findHisIcd10(diagnosisDO.getCode());
                if(jsonArray2!=null&&jsonArray2.size()>0){
                    //获取居民信息
                    JSONObject json = jsonArray2.getJSONObject(0);
                    icd10Flag = json.getInteger("FLAG");

                }
                hlwYsMzJzLsDO.setZYZD(icd10Flag);

                String jsonString2 = JSONObject.toJSONString(hlwYsMzJzLsDO);
                Map<String,Object> params2 = new HashedMap();
                params2.put("json",jsonString2);
                params2.put("table","HlwYsMzJzLsDO");
                logger.info("HlwYsMzJzLsDO："+jsonString2);
                HttpResponse response2 = HttpUtils.doGet(saveUrl,params2);
                if (response2.getStatus()==200){
                    String content = response2.getContent();
                    logger.info("content"+content);
                    //获取就诊序号，更新处方表数据
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONObject object = jsonObject.getJSONObject("obj");
                    if (object!=null){
                        Integer jzxh = object.getInteger("jzxh");
                        wlyyPrescriptionVO.setAdmNo(jzxh+"");
                        logger.info("JZXH=========="+jzxh);
                        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(code);
                        if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
                            WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
                            wlyyPrescriptionDO.setAdmNo(jzxh+"");
                            prescriptionDao.save(wlyyPrescriptionDO);
                        }
                    }
                    logger.info("表hlwYsMzJzLsDO同步成功！");
                }

                //删除疾病诊断表HLWYS_MZ_JBZD
                /*if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getAdmNo())){
                    String deleteSql = "update v_hlwys_mz_jbzd set  zfpb=1,  where jzxh = '"+wlyyPrescriptionVO.getAdmNo()+"'";
                    Map<String,Object> params = new HashedMap();
                    params.put("sql",deleteSql);
                    HttpResponse response = HttpUtils.doGet(updateUrl,params);
                    if (response.getStatus()==200){
                        logger.info("表v_hlwys_mz_jbzd删除成功！");
                    }
                }*/
                //疾病诊断表HLWYS_MZ_JBZD
                HlwYsMzJbzdDO hlwYsMzJbzdDO = new HlwYsMzJbzdDO();
                //hlwYsMzJbzdDO.setJLBH(0);
                hlwYsMzJbzdDO.setYSDM(doctorMappingDO.getMappingCode());
                hlwYsMzJbzdDO.setICD(diagnosisDO.getCode());
                hlwYsMzJbzdDO.setMSZD(diagnosisDO.getName());
                hlwYsMzJbzdDO.setJBBH(icd10Flag);
                hlwYsMzJbzdDO.setBRBH(Integer.valueOf(patientMappingDO.getMappingCode()));
                hlwYsMzJbzdDO.setZDLB(11);//诊断类别
                hlwYsMzJbzdDO.setZDSJ(DateUtil.strToDate(DateUtil.dateToStr(wlyyPrescriptionVO.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));//诊断时间
                hlwYsMzJbzdDO.setZFPB(0);//作废标志
                hlwYsMzJbzdDO.setQZBZ(0);//确诊标志
                hlwYsMzJbzdDO.setQZSJ(DateUtil.strToDate(DateUtil.dateToStr(wlyyPrescriptionVO.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));//确诊时间
                hlwYsMzJbzdDO.setJBMC(diagnosisDO.getName());//诊断名称
                hlwYsMzJbzdDO.setZDLX(1);//诊断类型
                hlwYsMzJbzdDO.setTJBZ(1);//提交标志
                if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getAdmNo())){
                    hlwYsMzJbzdDO.setJZXH(Integer.parseInt(wlyyPrescriptionVO.getAdmNo()));
                }

                String jsonString1 = JSONObject.toJSONString(hlwYsMzJbzdDO);
                Map<String,Object> params1 = new HashedMap();
                params1.put("json",jsonString1);
                params1.put("table","HlwYsMzJbzdDO");
                logger.info("HlwYsMzJbzdDO："+jsonString1);
                HttpResponse response1 = HttpUtils.doGet(saveUrl,params1);
                if (response1.getStatus()==200){
                    String content = response1.getContent();
                    logger.info("content"+content);

                    logger.info("表hlwYsMzJbzdDO同步成功！");
                }
            }
        }

    }

    public WlyyPrescriptionVO synPrecriptionHis(WlyyPrescriptionVO wlyyPrescriptionVO,String code,String drugCode) throws Exception {
        HlwCf01DO hlwCf01DO = new HlwCf01DO();
        logger.info("开始===================");
        if (wlyyPrescriptionVO!=null&&wlyyPrescriptionVO.getInfoVOs()!=null){
            try {
                hlwCf01DO.setSPZT(0);
                hlwCf01DO.setFKZT(wlyyPrescriptionVO.getPayStatus());
                if (StringUtils.isNoneBlank(drugCode)){
                    Integer yfsb = Integer.parseInt(drugCode);
                    hlwCf01DO.setYFSB(yfsb);
                }

                hlwCf01DO.setCFLX(wlyyPrescriptionVO.getType());
                hlwCf01DO.setKFRQ(DateUtil.strToDate(DateUtil.dateToStr(wlyyPrescriptionVO.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));
                hlwCf01DO.setZFPB(0);
                hlwCf01DO.setFYBZ(0);
                hlwCf01DO.setPYBZ(0);
                hlwCf01DO.setDJYBZ(0);
                hlwCf01DO.setCFTS(1);
                hlwCf01DO.setYXPB(1);
                hlwCf01DO.setDYBZ(0);
                hlwCf01DO.setTSCF(0);
                hlwCf01DO.setTYBZ(0);
                hlwCf01DO.setTSLX(6);
                hlwCf01DO.setCFBZ(0);
                hlwCf01DO.setJZXH(0);
                hlwCf01DO.setYXPB(0);
                hlwCf01DO.setLSCFBZ(0);
                hlwCf01DO.setZJFLAG(0);
                hlwCf01DO.setLSCFBZ(0);
                hlwCf01DO.setZJFLAG(0);
                hlwCf01DO.setFKZT(0);
                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());
                hlwCf01DO.setSJLY(1);
                if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getAdmNo())){
                    hlwCf01DO.setJZXH(Integer.parseInt(wlyyPrescriptionVO.getAdmNo()));
                }
               /* hibenateUtils.save(hlwCf01DO);*/
                if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getRealOrder())){
                    hlwCf01DO.setCFSB(Integer.parseInt(wlyyPrescriptionVO.getRealOrder()));
                }
                if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getOriginRealOrder())){
                    hlwCf01DO.setCFHM(wlyyPrescriptionVO.getOriginRealOrder());
                }

                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);
                /**
                 {"message":null,"status":200,"obj":{"cfhm":1898356,"cfsb":5390518}}

                 */
                String cfsb = null;
                String cfhm = null;
                if (!StringUtils.isNoneBlank(wlyyPrescriptionVO.getRealOrder())){
                    HttpResponse response = HttpUtils.doGet(saveUrl,params);
                    if (response.getStatus()==200){
                        logger.info("content"+response.getContent());
                        String content = response.getContent();
                        JSONObject jsonObject = JSONObject.parseObject(content);
                        JSONObject object = jsonObject.getJSONObject("obj");
                        if (object!=null){
                            cfsb = object.getString("cfsb");
                            cfhm = object.getString("cfhm");
                            logger.info("kaishi=========="+cfsb);
                            List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(code);
                            if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
                                WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
                                wlyyPrescriptionDO.setRealOrder(cfsb);
                                wlyyPrescriptionDO.setOrderId(hlwCf01DO.getGUID());
                                wlyyPrescriptionDO.setOriginRealOrder(cfhm);
                                prescriptionDao.save(wlyyPrescriptionDO);
                            }
                        }
                        logger.info("表HLW_CF01同步成功！");

                    }else {
                        logger.info("表HLW_CF01同步失败！"+response.getErrorMsg());
                    }
                }else {
                    cfsb = wlyyPrescriptionVO.getRealOrder();

                    String sql = "update v_ms_dd01 t set t.ZFPB=1,t.ZFSJ=to_date('"+DateUtil.getStringDate()+"','yyyy-mm-dd hh24:mi:ss')  where  t.CFSB ='"+cfsb+"' ";
                    Map<String,Object> params1 = new HashedMap();
                    params1.put("sql",sql);
                    HttpResponse response = HttpUtils.doGet(updateUrl,params1);
                    if (response.getStatus()==200){
                        logger.info("表v_ms_dd01作废成功！");
                        HttpResponse response1 = HttpUtils.doGet(saveUrl,params);
                        if (response1.getStatus()==200){
                            logger.info("content"+response1.getContent());
                            String content = response1.getContent();
                            JSONObject jsonObject = JSONObject.parseObject(content);
                            JSONObject object = jsonObject.getJSONObject("obj");
                            if (object!=null){
                                cfsb = object.getString("cfsb");
                                cfhm = object.getString("cfhm");
                                logger.info("kaishi=========="+cfsb);
                                List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(code);
                                if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
                                    WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
                                    wlyyPrescriptionDO.setRealOrder(cfsb);
                                    wlyyPrescriptionDO.setOrderId(hlwCf01DO.getGUID());
                                    wlyyPrescriptionDO.setOriginRealOrder(cfhm);
                                    prescriptionDao.save(wlyyPrescriptionDO);
                                }
                            }
                            logger.info("表HLW_CF01同步成功！");

                        }else {
                            logger.info("表HLW_CF01同步失败！"+response.getErrorMsg());
                        }
                    }

                   /* hlwCf01DO.setZFPB(1);
                    hlwCf01DO.setZFSJ(new Date());
                    HttpResponse response = HttpUtils.doGet(updateEntityUrl,params);
                    if (response.getStatus()==200){
                        logger.info("content"+response.getContent());
                        logger.info("表HLW_CF01更新成功！");

                    }else {
                        logger.info("表HLW_CF01更新失败！"+response.getErrorMsg());
                    }*/
                }

                logger.info("处方："+cfsb);
                if (StringUtils.isEmpty(cfsb)){
                    throw new Exception("添加失败");
                }
               /* if (StringUtils.isNoneBlank(wlyyPrescriptionVO.getRealOrder())){
                    String deleteSql = "delete from v_ms_dd02 where cfsb = '"+wlyyPrescriptionVO.getRealOrder()+"'";
                    Map<String,Object> params1 = new HashedMap();
                    params1.put("sql",deleteSql);
                    HttpResponse response = HttpUtils.doGet(updateUrl,params1);
                    if (response.getStatus()==200){
                        logger.info("表v_ms_dd02删除成功！");
                    }
                }*/
                List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS =wlyyPrescriptionVO.getInfoVOs();
                for (WlyyPrescriptionInfoVO wlyyPrescriptionInfoVO:wlyyPrescriptionInfoVOS){
                    try {
                        logger.info("chufang1============");
                    HlwCf02DO hlwCf02DO = new HlwCf02DO();
                    hlwCf02DO.setCFSB(Integer.parseInt(cfsb));
                    hlwCf02DO.setYPXH(Integer.parseInt(wlyyPrescriptionInfoVO.getDrugNo()));
                    logger.info("drugNo"+hlwCf02DO.getYPXH());
                    if (wlyyPrescriptionInfoVO.getDrugPlace()!=null){
                        hlwCf02DO.setYPCD(Integer.parseInt(wlyyPrescriptionInfoVO.getDrugPlace()));
                    }
                    hlwCf02DO.setXMLX(1);
                    hlwCf02DO.setCFTS(1);
                    hlwCf02DO.setYPSL(Double.parseDouble(wlyyPrescriptionInfoVO.getQuantity()));
                    hlwCf02DO.setYPDJ(wlyyPrescriptionInfoVO.getPackRetprice());
                    hlwCf02DO.setHJJE(Integer.parseInt(wlyyPrescriptionInfoVO.getQuantity())*wlyyPrescriptionInfoVO.getPackRetprice());//划价价额
                    hlwCf02DO.setYPZS(1);//药品组数  待确定
                    hlwCf02DO.setYCSL("0");
                    hlwCf02DO.setFYGB(17);//费用归并
                    hlwCf02DO.setZFBL(1.0);//自负比例
                    hlwCf02DO.setYFDW(wlyyPrescriptionInfoVO.getPackUnitName());
                    hlwCf02DO.setMRCS(StringUtils.isNoneBlank(wlyyPrescriptionInfoVO.getGroupNo())?Integer.parseInt(wlyyPrescriptionInfoVO.getGroupNo()):0);//每日次数
                    hlwCf02DO.setYFBZ(wlyyPrescriptionInfoVO.getPackQuantity());
                    hlwCf02DO.setYPYF(wlyyPrescriptionInfoVO.getUsageCode());
                    hlwCf02DO.setGYTJ(wlyyPrescriptionInfoVO.getYpyf());
                    hlwCf02DO.setPSPB(0);
                    hlwCf02DO.setYYTS(1);
                    hlwCf02DO.setYCJL(wlyyPrescriptionInfoVO.getDosage()!=null?Double.parseDouble(wlyyPrescriptionInfoVO.getDosage()):0);
                    hlwCf02DO.setZBBZ(0);
                    hlwCf02DO.setYDFYBZ(0);
                    hlwCf02DO.setTYSQSL(0);
                    hlwCf02DO.setZJFLAG(0);
                    hlwCf02DO.setSPZT(0);
                    if (wlyyPrescriptionInfoVO.getHisCode()!=null){
                        hlwCf02DO.setSBXH(wlyyPrescriptionInfoVO.getHisCode());
                    }
                    /*hlwCf02DO.setYPZH(Integer.parseInt(wlyyPrescriptionInfoVO.getFrequency()));*/
                    hlwCf02DO.setYFGG(wlyyPrescriptionInfoVO.getSpecification());
                  /*  hibenateUtils.save(hlwCf02DO);*/
                    String jsonString1 = JSONObject.toJSONString(hlwCf02DO);
                        logger.info("chufang2============");
                    Map<String,Object> params1 = new HashedMap();
                    params1.put("json",jsonString1);
                    params1.put("table","HLW_CF02");
                    logger.info("HLW_CF02："+jsonString1);
                    if (wlyyPrescriptionInfoVO.getHisCode()==null){
                        HttpResponse response1 = HttpUtils.doGet(saveUrl,params1);
                        Integer sbxh = null;
                        if (response1.getStatus()==200){
                            logger.info("content"+response1.getContent());
                            String content = response1.getContent();
                            JSONObject jsonObject = JSONObject.parseObject(content);
                            JSONObject object = jsonObject.getJSONObject("obj");
                            if (object!=null){
                                sbxh = object.getInteger("sbxh");
                                logger.info("kaishi=========="+cfsb);
                                WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO = prescriptionInfoDao.findOne(wlyyPrescriptionInfoVO.getId());
                                if (wlyyPrescriptionInfoDO!=null){
                                    wlyyPrescriptionInfoDO.setHisCode(sbxh);
                                    prescriptionInfoDao.save(wlyyPrescriptionInfoDO);
                                }
                            }
                            logger.info("表HLW_CF02同步成功！");
                        }else {
                            logger.info("表HLW_CF02同步失败！"+response1.getErrorMsg());
                        }
                    }else {
                        HttpResponse response1 = HttpUtils.doGet(updateEntityUrl,params1);
                        if (response1.getStatus()==200){
                            logger.info("content"+response1.getContent());
                            logger.info("表HLW_CF02更新成功！");
                        }else {
                            logger.info("表HLW_CF02更新失败！"+response1.getErrorMsg());
                        }
                    }

                    }catch (Exception e){
                        e.printStackTrace();
                        e.getMessage();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }



    public String updateHisStatus(String sql) throws Exception {
        Map<String,Object> params1 = new HashedMap();
        params1.put("sql",sql);
        logger.info("his支付"+sql);
        HttpResponse response1 = HttpUtils.doGet(updateUrl,params1);
        logger.info(response1.getContent());
        if (response1.getStatus()==200){
            logger.info("更新his支付状态！");
        }else {
            logger.info("更新his支付状态！"+response1.getErrorMsg());
        }
        return response1.getContent();
    }

    /**
     * 眼科通App消息推送接口
     * @param doctor
     * @param patient
     * @param orderType
     * @return
     */
    public String sendMesToYkt(String doctor, String patient, String orderType) throws Exception {

        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
        String yktDoctor ="";
        if (doctorMappingDO!=null&&StringUtils.isNoneBlank(doctorMappingDO.getMappingCode())){
            String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
            JSONObject jsonObject = JSONObject.parseObject(doctorResponse);
            if (jsonObject.getInteger("code")==200){
                JSONArray array1 = jsonObject.getJSONArray("data");
                if (array1!=null&&array1.size()!=0){
                    yktDoctor=array1.getJSONObject(0).getString("DOCTORUSERID");
                }
            }
        }else {
            throw new Exception("医生映射表不存在！");
        }

        BasePatientDO basePatientDO = basePatientDao.findById(patient);

        if(basePatientDO!=null){
            patient = basePatientDO.getYktId();
        }

        Map<String,Object> params = new HashedMap();
        logger.info("眼科通App消息推送接口:doctorId:"+yktDoctor);
        logger.info("眼科通App消息推送接口:patientId:"+patient);
        logger.info("眼科通App消息推送接口:orderType:"+orderType);
        logger.info("眼科通App消息推送接口:url:http://www.yanketong.com:90/api/share/PushNotificationToDoctor?patientId="+patient+"&doctorId="+yktDoctor+"&orderType="+orderType);
        HttpResponse response = HttpUtils.doPost("http://www.yanketong.com:90/api/share/PushNotificationToDoctor?patientId="+patient+"&doctorId="+yktDoctor+"&orderType="+orderType,params);

        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("code");
        if(status!=null&&status != 10000){
            return rs.getString("message");//推送失败原因
        }else{
            return "推送成功";
        }
    }
    //查询组套项目
    public JSONArray findYzztByGslb(String gslb) throws Exception {
        String sql = "select t.ztmc as\"ztmc\",t.ztid as\"ztid\"," +
                "t.gslb as\"gslb\",t.gsdm as\"gsdm\"," +
                "t.pydm as\"pydm\",t.Mzsy as\"Mzsy\"" +
                "from portal_his.emr_yzzt@xec_link t where 1=1";
        if(StringUtils.isNotEmpty(gslb)){
            sql+=" and t.gslb = "+Integer.valueOf(gslb);
            }
        System.out.println(sql);
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("findYzztByGslb："+sql);
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONArray array= new JSONArray();
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
       return array;

    }
    //根据组套项目id查询组套明细
    public JSONArray findZtmxByid(String ztId) throws Exception{
        String sql = "select t.ztid as \"ztid\",t.xmdm as \"code\"," +
                "t.xmmc as \"name\",t.mrsl as \"quantity\",t.zxks as \"dept\"" +
                "from portal_his.emr_ztmx@xec_link t where 1=1";
        if (StringUtils.isNotEmpty(ztId)){
            sql += " and t.ztid = '"+ztId+"'";
        }
        System.out.println(sql);
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("findZtmxByid："+sql);
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONArray array= new JSONArray();
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;

    }
    //查询诊疗项目视图
    public JSONArray findZlxm(String itemName,String itemCode,String deptCode,String yqdm,String pyCode) throws Exception{
        String sql = "select t.item_code as \"code\",t.item_name as \"name\"," +
                "t.price as \"chargeAmount\",t.total_unit as \"totalUnit\"," +
                "t.zxks as \"dept\" ,t.yqdm as \"yqdm\" ,m.name as \"exec_unit_name\" from VEMR_ORDER_ITEM t " +
                " left join V_HLW_KSXX m on m.code = t.zxks " +
                " where 1=1";
        /*if (StringUtils.isNotEmpty(itemName)){
            sql+=" and t.ITEM_NAME like '%"+itemName+"%'";
        }*/
        if (StringUtils.isNotEmpty(yqdm)){
            sql+=" and t.yqdm = '"+yqdm+"'";
        }
        if (StringUtils.isNoneBlank(itemName)){
            sql+=" and lower(t.kb_code) like '%"+itemName.toLowerCase()+"%'";
        }
        if (StringUtils.isNotEmpty(itemCode)){
            String[] split = itemCode.split(",|，");
            String ids = org.apache.commons.lang.StringUtils.join(split, ",");
            sql+=" and t.item_code in ("+ids+")";
        }
        if (StringUtils.isNotEmpty(deptCode)){
            sql+=" and t.zxks ="+deptCode+"";
        }
        System.out.println(sql);
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("findZlxm："+sql);
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONArray array= new JSONArray();
        if (status==200){
            array = rs.getJSONArray("detailModelList");
            for (int i=0;i<array.size();i++){
                JSONObject jsonObject =array.getJSONObject(i);
                if (jsonObject.get("yqdm")!=null){
                    if ("1001".equalsIgnoreCase(jsonObject.get("yqdm").toString())){
                        jsonObject.put("yqmc","思北院区");
                    }
                    if ("1002".equalsIgnoreCase(jsonObject.get("yqdm").toString())){
                        jsonObject.put("yqmc","五缘院区");
                    }
                }
            }
        }
        return array;
    }
    //查询诊疗项目明细视图
    public JSONArray findZlxmMx(String zlxmId) throws Exception{
        String sql = "select t.zlxmid as \"code\",t.fyxh as \"fyxh\",t.fysl \"quantity\"" +
                " from VEMR_ORDER_ITEM_MX t where 1=1";
        if (StringUtils.isNotEmpty(zlxmId)){
            sql+=" and t.zlxmid = '"+zlxmId+"'";
        }
        System.out.println(sql);
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("findZlxmMx："+sql);
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONArray array= new JSONArray();
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }
    //his.gy_ylsf明细查询
    public JSONArray findGyYlsf(String fyxh) throws Exception{
        String sql = "select t.xmlx as \"xmlx\",t.fydj as \"fydj\",t.fygb as \"fygb\"" +
                "from portal_his.GY_YLSF@ykzxtest t where 1=1";
        if (StringUtils.isNotEmpty(fyxh)){
            sql+=" and t.fyxh = '"+fyxh+"'";
        }
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("findZlxmMx："+sql);
        HttpResponse response = HttpUtils.doGet(jdbcUrl,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        JSONArray array= new JSONArray();
        if (status==200){
            array = rs.getJSONArray("detailModelList");
        }
        return array;
    }
    //门诊开单操作
    public Map<String,Object> outPatientOrder(List<YkEmrJcsqDO> surveys,Boolean demoFlag,String doctor,String patient) throws Exception{
        BasePatientDO patientDO = basePatientDao.findById(patient);
        DoctorMappingDO doctorMappingDO = new DoctorMappingDO();
        if (StringUtils.isNoneBlank(doctor)){
            doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
        }
        PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patient,"1");
        System.out.println();
        Integer brxb = 0;
        String brxm = "";
        Date csny =null;
        Integer brnl =0;
        String doctorHis="";
        Integer kdks = 0;
        Integer brid=0;
        String mzhm="0";
        JSONArray jsonArray = findHisPatientBySscAndIdcard(patientMedicareCardDO.getCode(),patientDO.getIdcard(),demoFlag);
        Map<String,Object> resultMap = new HashMap();
        if(jsonArray!=null&&jsonArray.size()>0){
            //获取居民信息
            JSONObject json = jsonArray.getJSONObject(0);
            brxb = json.getInteger("brxb");
            brxm = json.getString("brxm");
            csny = json.getDate("csny");
            brnl = this.getBrnl(csny);
            brid=json.getInteger("brid");
            mzhm = json.getString("mzhm");

        }
        //操作医生信息
        JSONArray jsonArray1 = findHisDoctor(doctorMappingDO.getIdcard());
        if(jsonArray1!=null&&jsonArray1.size()>0){
            JSONObject json = jsonArray1.getJSONObject(0);
            doctorHis=json.getString("code");
            kdks = Integer.parseInt(json.getString("dept"));
        }
        if (surveys!=null){
            for (YkEmrJcsqDO ykEmrJcsqDO:surveys){
                    ykEmrJcsqDO.setBrid(brid);
                    ykEmrJcsqDO.setJjbz(0);
                    ykEmrJcsqDO.setJczt(1);
                    ykEmrJcsqDO.setZfbz(0);
                    ykEmrJcsqDO.setQxbz(0);
                    ykEmrJcsqDO.setBrxb(brxb);
                    ykEmrJcsqDO.setBrxm(brxm);
                    ykEmrJcsqDO.setBrnl(brnl);
                    ykEmrJcsqDO.setKdys(doctorHis);
                    ykEmrJcsqDO.setBrks(kdks);
                    ykEmrJcsqDO.setJzhm(mzhm);
                    ykEmrJcsqDO.setTjys(doctorHis);

            }
            String jsonString = JSONObject.toJSONString(surveys);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","ykEmrJcsqDO");
            logger.info("ykEmrJcsqDO："+jsonString);
            HttpResponse response = HttpUtils.doGet(orderUrl,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            JSONArray array= new JSONArray();
            if (status==200){
                array = rs.getJSONArray("detailModelList");
                resultMap.put("code","200");
                resultMap.put("msg",content);
                return resultMap;
            }else {
                resultMap.put("code","-1");
                resultMap.put("msg",content);
                return resultMap;
            }
        }else {
            resultMap.put("code","-1");
            resultMap.put("msg","开单信息为空");
            return resultMap;
        }
    }
   //查询检查单
   public JSONArray findOrder()throws Exception{
        String sql = "select t.sqdh,t.brid," +
                "t.jzlx,t.brxm,t.brks," +
                "t.brnl,t.kdsj,t.zxks,t.jcxm,t.xmdj," +
             "t.xmdw,t.xmid,t.sqsl from emr_jcsq@ykzxtest t where 1=1";
       Map<String,Object> params = new HashedMap();
       params.put("sql",sql);
       params.put("table","ykEmrJcsqDO");
       logger.info("ykEmrJcsqDO："+sql);
       HttpResponse response = HttpUtils.doGet(jdbcUrl,params);
       String content = response.getContent();
       logger.info("response:"+content);
       JSONObject rs = JSON.parseObject(content);
       Integer status = rs.getInteger("status");
       JSONArray array= new JSONArray();
       if (status==200){
           array = rs.getJSONArray("detailModelList");
       }
       return array;
   }
   //根据病人出生年月计算病人年龄
   public Integer getBrnl(Date date){
       Calendar cal = Calendar.getInstance();
       if (cal.before(date)) {
           throw new IllegalArgumentException(
                   "The birthDay is before Now.It's unbelievable!");
       }
       int yearNow = cal.get(Calendar.YEAR);
       int monthNow = cal.get(Calendar.MONTH) + 1;
       int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
       cal.setTime(date);
       int yearBirth = cal.get(Calendar.YEAR);
       int monthBirth = cal.get(Calendar.MONTH) + 1;
       int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
       int age = yearNow - yearBirth;
       if (monthNow <= monthBirth) {
           if (monthNow == monthBirth) {
// monthNow==monthBirth
               if (dayOfMonthNow < dayOfMonthBirth) {
                   age--;
               }
           } else {
// monthNow>monthBirth
               age--;
           }
       }
       return age;
   }


    public String outPatientOrderYk(String jsonDate,Boolean demoFlag,String doctor,String patient) throws Exception{
        BasePatientDO patientDO = basePatientDao.findById(patient);
        List<YkEmrJcsqDO> surveys = EntityUtils.jsonToList(jsonDate,YkEmrJcsqDO.class);
        DoctorMappingDO doctorMappingDO = new DoctorMappingDO();
        if (StringUtils.isNotEmpty(doctor)){
            doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
        }
        PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patient,"1");
        Integer brxb = 0;
        String brxm = "";
        Date csny =null;
        Integer brnl =0;
        String doctorHis="";
        Integer kdks = 0;
        Integer brid=0;
        JSONArray jsonArray = findHisPatientBySscAndIdcard(patientMedicareCardDO.getCode(),patientDO.getIdcard(),demoFlag);
        if(jsonArray!=null&&jsonArray.size()>0){
            //获取居民信息
            JSONObject json = jsonArray.getJSONObject(0);
            brxb = json.getInteger("brxb");
            brxm = json.getString("brxm");
            csny = json.getDate("csny");
            brnl = this.getBrnl(csny);
            brid=json.getInteger("brid");
        }
        //操作医生信息
        JSONArray jsonArray1 = findHisDoctor(doctorMappingDO.getIdcard());
        if(jsonArray1!=null&&jsonArray1.size()>0){
            JSONObject json = jsonArray1.getJSONObject(0);
            doctorHis=json.getString("code");
        }
        if (surveys!=null){
            for (YkEmrJcsqDO ykEmrJcsqDO:surveys){
                ykEmrJcsqDO.setBrid(brid);
                ykEmrJcsqDO.setJjbz(0);
                ykEmrJcsqDO.setJczt(1);
                ykEmrJcsqDO.setZfbz(0);
                ykEmrJcsqDO.setQxbz(0);
                ykEmrJcsqDO.setBrxb(brxb);
                ykEmrJcsqDO.setBrxm(brxm);
                ykEmrJcsqDO.setBrnl(brnl);
                ykEmrJcsqDO.setKdys(doctorHis);
                ykEmrJcsqDO.setBrks(114);
                ykEmrJcsqDO.setTjys(doctorHis);
            }
            String jsonString = JSONObject.toJSONString(surveys);
            Map<String,Object> params = new HashedMap();
            params.put("json",jsonString);
            params.put("table","ykEmrJcsqDO");
            logger.info("ykEmrJcsqDO："+jsonString);
            HttpResponse response = HttpUtils.doGet(orderUrl,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            JSONArray array= new JSONArray();
            if (status==200){
                array = rs.getJSONArray("detailModelList");
                if(array.size()>0){
                    return "success";
                }else {
                    return "failed";
                }
            }
            return "faild";
        }else {
            return "failed";
        }
    }
    //获取上一次的电子病例
    public List<WlyyPrescriptionEmrDO>  getPrevious(String patientId){
        List<WlyyPrescriptionDO> list =  prescriptionDao.findByPatientCode(patientId);
        String emrId = "";
        List<WlyyPrescriptionEmrDO> result = new ArrayList<>();
        if (list.size()>0){
            for (WlyyPrescriptionDO wlyyPrescriptionDO:list){
                WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO= prescriptionEmrDao.findOne(wlyyPrescriptionDO.getId());
                result.add(wlyyPrescriptionEmrDO);
            }
        }
        return result;
    }
    /**
     * 根据卡号获取病人hisCode
     * @param cardNo
     * @return
     * @throws Exception
     */
    public JSONArray findPatientCodeByCardNo(String cardNo,boolean demoFlag,String patientId) throws Exception {
        PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByCodeAndPatientCode(cardNo,patientId);
        String sql = "select x.brid as \"brid\" ,o.pat_no as \"pat_no\",o.card_no as \"card_no\",o.card_stat as \"card_stat\",o.op_date as \"op_date\",o.card_type as \"card_type\",o.card_type_name as \"card_type_name\"  from v_zksg_brcx x,V_HLW_CARDINFO o where  o.pat_no = x.mzhm  ";
        if (patientMedicareCardDO!=null){
            String type = patientMedicareCardDO.getType();
            if (type.equalsIgnoreCase("A_01")){
                sql +=" and UPPER(o.card_no) = UPPER('"+cardNo+"') ";
            }else {
                if (type.equalsIgnoreCase("A_02")){
                    sql +=" and x.mzhm='"+cardNo+"' ";
                }else {
                    sql +=" and UPPER(o.card_no) = UPPER('"+cardNo+"') ";
                }
            }

        }
        JSONArray array = new JSONArray();
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("idcard："+sql);
        if (demoFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pat_no","P5616242-0");
            jsonObject.put("card_no","D40136791");
            jsonObject.put("card_stat","激活");
            jsonObject.put("op_date","2020-06-25 08:46:40");
            jsonObject.put("card_type","2");
            jsonObject.put("card_type_name","社保卡");
            array.add(jsonObject);
        }else {
            HttpResponse response = HttpUtils.doGet(url,params);
            String content = response.getContent();
            logger.info("response:"+content);
            JSONObject rs = JSON.parseObject(content);
            Integer status = rs.getInteger("status");
            if (status==200){
                array = rs.getJSONArray("detailModelList");
            }
        }
        return array;
    }



    public JSONObject selectByAddress(String cardNo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        String address = null;
        String zydm = null;
        String jtdh = null;
        JSONArray array = new JSONArray();
        String sql = "SELECT brid as \"brid\",hkdz as \"hkdz\",zydm as \"zydm\",jtdh as \"jtdh\" from portal_his.V_ZKSG_BRCX@xec_link where jzkh = '"+cardNo+"'";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if (status==200){
            array = rs.getJSONArray("detailModelList");
            if (array!=null&&array.size()!=0){
                JSONObject object = array.getJSONObject(0);
                address=object.getString("hkdz");
                zydm = object.getString("zydm");
                jtdh = object.getString("jtdh");
                jsonObject.put("address",address);
                jsonObject.put("zydm",zydm);
                jsonObject.put("jtdh",jtdh);
            }


        }
        return  jsonObject;
    }


    /**
     * 通过卡号更新患者信息
     */
    public void updatePatientJd(String patient,String address,String phone,Float zy, boolean demoFlag) throws Exception {
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patient,"1");
        JSONArray jsonArray = findHisPatientBySscAndIdcard(patientMedicareCardDO.getCode(),basePatientDO.getIdcard(),demoFlag);
        if(jsonArray!=null&&jsonArray.size()>0){
            //获取居民信息
            JSONObject json = jsonArray.getJSONObject(0);
            String brid = json.getString("brid");
            Float id = Float.parseFloat(brid);
            Map<String,Object> params = new HashedMap();
            params.put("brid",id);
            params.put("sfzh",basePatientDO.getIdcard());
            params.put("lxdh",phone);
            params.put("lxdz",address);
            params.put("zy",zy);
            HttpResponse response = HttpUtils.doGet(updateJdxx,params);
            logger.info("更新患者信息"+response);
        }

    }



    public String saveJdxx(String brxm,String csny,Float brxb,String czgh,String sfzh,String sjhm,String ybkh,String lxdz,Float zy){
        logger.info("===========sjhm==================="+sjhm);
        return  hibenateUtils.saveJdxx(brxm,DateUtil.strToDateShort(csny),brxb,czgh,sfzh,sjhm,ybkh,lxdz,zy);
    }


    public String updateJdxx(Float brid,String sfzh,String lxdz,Float zy,String lxdh){
        return  hibenateUtils.updateJdxx(brid,sfzh,lxdz,zy,lxdh);
    }

    public String updateJzkh(Float brid,String jzkh){
        return  hibenateUtils.updateJzkh(brid,jzkh);
    }
    public String updateSfzh(Float brid,String sfzh){
        return  hibenateUtils.updateSfzh(brid,sfzh);
    }

    public String findInfoBysql(String sql) throws Exception {
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("sql："+sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        return content;
    }

    //获取调用hospital-entrance createSQLQuery 返回结果
    public JSONArray getSqlResult(String sql) throws Exception {
        Map<String, Object> params = new HashedMap();
        params.put("sql", sql);
        HttpResponse response = HttpUtils.doGet(url, params);
        String content = response.getContent();
        logger.info("sql:" + sql);
        logger.info("response:" + content);
        JSONObject rsult = JSON.parseObject(content);
        Integer status = rsult.getInteger("status");
        if (status == 200) {
            JSONArray array = rsult.getJSONArray("detailModelList");
            return array;
        }
        return null;
    }

    //判断居民是否建过档，没有就建档
    public JSONObject patientJDKH(String idcard, String name, String phoneNum, String medicare,String clinicId) throws Exception {
        JSONObject res = new JSONObject();
        res.put("status", 200);
        Float brid = null;
        //根据身份证查询是否建档
        String sfzhSql = "SELECT jzkh \"jzkh\" ,brid \"brid\" from portal_his.V_ZKSG_BRCX@xec_link where sfzh = '" + idcard + "' order by JDSJ ";
        //根据社保卡查询是否建档
        String jzkhSql = "SELECT brid \"brid\"，sfzh \"sfzh\" from portal_his.V_ZKSG_BRCX@xec_link where UPPER(jzkh) = UPPER('" + medicare + "')  order by JDSJ ";
        JSONArray sfzhArray = getSqlResult(sfzhSql);
        int size = sfzhArray.size();
        /*if (size == 1) {
            JSONObject json = sfzhArray.getJSONObject(0);
            Object jzkh = json.get("jzkh");//社保卡
            //获取居民信息
            brid = json.getFloat("brid");//病人id
            if (jzkh != null && !jzkh.toString().equals(medicare)) {//判断是否跟当前医保卡号一致
//                res.put("status", -1);
//                res.put("message", "您输入的卡号和该就诊人在医院预留的卡号不一致，请重新输入。");
//                return res;
            } else if (jzkh == null) {//若为空则更新社保卡
                Map<String, Object> updateParams = new HashedMap();
                updateParams.put("brid", brid);
                updateParams.put("jzkh", medicare);
                logger.info("更新params:" + updateParams);
                HttpResponse updateResponse = HttpUtils.doGet(updateJzkh, updateParams);
                String updateContent = updateResponse.getContent();
                logger.info("更新患者信息updateResponse:" + updateContent);
                JSONObject rsult = JSON.parseObject(updateContent);
                Integer s = rsult.getInteger("status");
                String message = rsult.getString("message");
                if (s != 200 || !message.equals("成功")) {
                    res.put("status", -1);
                    res.put("message", message);
                    return res;
                }
            }
        } else*/ if (size > 1) {//如果存在多条数据，查看是否有跟当前社保卡号一致的，如果有则跳过，如果社保卡都为空则取其中一条更新，否则就提示与预留卡号不一致
            String sql = "SELECT brid \"brid\" from portal_his.V_ZKSG_BRCX@xec_link where sfzh = '" + idcard + "' and  UPPER(jzkh) = UPPER('" + medicare + "') ";
            JSONArray array = getSqlResult(sql);
            logger.info("查询身份证和社保卡：" + array.toString());

            String sql1 = "SELECT brid \"brid\" from portal_his.V_ZKSG_BRCX@xec_link where sfzh = '" + idcard + "' and  mzhm = '" + clinicId + "' ";
            JSONArray array1 = getSqlResult(sql1);
            logger.info("查询身份证和门诊号：" + array1.toString());
            /*if (array==null||array.size()==0){
                res.put("status", -1);
                res.put("message", "您输入的卡号和该就诊人在医院预留的卡号不一致，请重新输入。");
                return res;
            }*/
            if (array.size() == 1) {
                brid = array.getJSONObject(0).getFloat("brid");
                res.put("brid",brid);
                return res;
            }else if (array1.size() == 1) {
                brid = array1.getJSONObject(0).getFloat("brid");
                res.put("brid",brid);
                return res;
            }else if(size >= 6){//查不到数据就判断建档次数，超过6次不让新增
                res.put("status", -1);
                res.put("message", "建档超过6次，请到线下变更。");
                return res;
            }
            }/*else { //否则就去最早一条更新
                String nullSql = "SELECT brid \"brid\" from portal_his.V_ZKSG_BRCX@xec_link where sfzh = '" + idcard + "' and  jzkh is null ";
                Integer count = getSqlResult(nullSql).size();
                if (count == size) {//如果都为空就默认取一条，然后更新社保卡号
                    brid = sfzhArray.getJSONObject(0).getFloat("brid");
                    Map<String, Object> updateParams = new HashedMap();
                    updateParams.put("brid", brid);
                    updateParams.put("jzkh", medicare);
                    logger.info("更新params:" + updateParams);
                    HttpResponse updateResponse = HttpUtils.doGet(updateJzkh, updateParams);
                    String updateContent = updateResponse.getContent();
                    logger.info("更新患者信息updateResponse:" + updateContent);
                    JSONObject rsult = JSON.parseObject(updateContent);
                    Integer s = rsult.getInteger("status");
                    String message = rsult.getString("message");
                    if (s != 200 || !message.equals("成功")) {
                        res.put("status", -1);
                        res.put("message", message);
                        return res;
                    }
                }else {
                    res.put("status", -1);
                    res.put("message", "您输入的卡号和该就诊人在医院预留的卡号不一致，请重新输入。");
                    return res;
                }
            }
        } else { //身份证号没查到信息，就用社保卡号查询
            JSONArray jzkhArray = getSqlResult(jzkhSql);
            if (jzkhArray!=null&&jzkhArray.size()>0){
                brid = jzkhArray.getJSONObject(0).getFloat("brid");
            }
        }*/
        //查询是否有这个病人id 如果有直接返回 如果没有则新建
        if (brid == null)
        {
            Map<String, Object> params1 = new HashedMap();
            params1.put("brxm", name);
            params1.put("csny", IdCardUtil.getBirthdayForIdcardStr(idcard));
            params1.put("brxb", IdCardUtil.getSexForIdcard_new(idcard));
            params1.put("czgh", "1996");
            params1.put("sfzh", idcard);
            params1.put("sjhm", phoneNum);
            params1.put("ybkh", medicare);
            params1.put("lxdz", 0);
            params1.put("zy", 0);
            HttpResponse response1 = HttpUtils.doGet(saveJdxxUrl, params1);
            String content1 = response1.getContent();
            logger.info("建档params:" + params1);
            logger.info("建档response:" + content1);
            JSONObject rs1 = JSON.parseObject(content1);
            if (rs1.getInteger("status") != 200) {
                res.put("status", -1);
                res.put("message", "建档失败，失败原因：" + rs1.getString("message"));
                return res;
            }
        }
        return res;
    }

}
