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.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.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.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.entity.hospital.prescription.*;
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.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.restmodel.hospital.prescription.*;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.security.MD5;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.yihu.jw.util.common.PwdUtil.randomString;

/**
 * Created by wangzhinan on 2020/12/24.
 */
@Service
@Transactional
public class TnyyEntranceService {

    private static Logger logger = LoggerFactory.getLogger(TnyyEntranceService.class);
    private final static String url="http://10.9.1.247:10023//tnyy/queryBySql";
    private final static String saveUrl="http://10.9.1.247:10023//tnyy/save";
    private final static String updateUrl="http://10.9.1.247:10023//tnyy/updateBySql";
    private final static String updateEntityUrl="http://10.9.1.247:10023/tnyy/update";
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DictHospitalDeptDao hospitalDeptDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private YkDictIcd10Dao ykDictIcd10Dao;
    private final static String orgCode ="350211A1002";
    @Autowired
    private PatientMappingDao patientMappingDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private PrescriptionDao prescriptionDao;




    //同步科室
    public String updateTnyyDept() throws Exception {
        String sql = "select KSDM,KSMC,PYDM,PLSX,JGBM from GY_KSDM  ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("updateTnyyDept："+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());
            for (int i=0;i<array.size();i++){
                JSONObject deptObj = array.getJSONObject(i);
                String ksdm = deptObj.getString("KSDM");
                String jgbm = deptObj.getString("JGBM");
                String ksmc = deptObj.getString("KSMC");
                List<DictHospitalDeptDO> list = hospitalDeptDao.findByOrgCodeAndCode(orgCode,ksdm);
                if (list!=null&&list.size()!=0){
                    DictHospitalDeptDO dictHospitalDeptDO = list.get(0);
                    dictHospitalDeptDO.setCode(ksdm);
                    dictHospitalDeptDO.setName(ksmc);
                    dictHospitalDeptDO.setOrgCode(jgbm);
                    hospitalDeptDao.save(dictHospitalDeptDO);
                }else {
                    //新增科室
                    DictHospitalDeptDO dictHospitalDeptDO = new DictHospitalDeptDO();
                    dictHospitalDeptDO.setCode(ksdm);
                    dictHospitalDeptDO.setName(ksmc);
                    dictHospitalDeptDO.setOrgCode(jgbm);
                    dictHospitalDeptDO.setCreateTime(new Date());
                    dictHospitalDeptDO.setConsultDeptFlag("1");
                    hospitalDeptDao.save(dictHospitalDeptDO);
                }
            }
        }
        return "success";
    }

    //更新泰安医生信息
    public String updateTnyyDoctor(String idCard)throws Exception{
        String sql ="select sfzh,LXDH,YGDM,KSDM,YGXM,YGXB,CSNY,YSJJ from GY_YGDM where ZFPB=0 and sfzh is not null and len(ygbh) =3 and ksyq >0 and ksdm <> '2118' ";
        if (StringUtils.isNoneBlank(idCard)){
            sql +=" and sfzh ='"+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("sfzh");

                    //过滤身份证脏数据
                    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"));
                            doctor.setMobile(doctorJson.getString("LXDH"));

                            BaseDoctorDO temp = baseDoctorDao.save(doctor);

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


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

                            doctor.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(idcard)));
                            doctor.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));
                            doctor.setMobile(doctorJson.getString("LXDH"));

                            doctor.setProvinceCode("370000");
                            doctor.setProvinceName("山东省");
                            doctor.setTownCode("370902");
                            doctor.setTownName("泰山区");
                            doctor.setCityCode("370900");
                            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("泰安市中医医院");
                            hospitalDO.setDeptCode(doctorJson.getString("KSDM"));
                            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("泰安市中医医院");

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

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

    public JSONArray selectPatientMappingCode(String idcard) throws Exception {
        String sql = "SELECT a.BRID,a.BRXM from MS_BRDA a WHERE a.SFZH = '"+idcard+"' ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("selectPatientMappingCode："+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");
        JSONArray array = new JSONArray();
        if(status!=null&&status == 200){
            array = rs.getJSONArray("detailModelList");
            logger.info("patient size:"+array.size());
        }
        return array;
    }




    /**
     * 查询药品信息
     * @param ypdm
     * @param ypmc
     * @param group_no
     * @return
     */
    public JSONArray findTnYpxx(String ypdm,String ypmc,String group_no,String pydm ,String hisCode) throws Exception {
        /*String sql ="SELECT yp.YPXH,yp.XTSB,yp.YPMC,yp.YPGG,yp.YFGG,yp.BFGG,yp.YPSX,yp.TSYP,yp.YPDW,yp.ZXDW,yp.ZXBZ,yp.YFBZ,yp.YFDW,yp.BFBZ," +
                "yp.BFDW,yp.ZFPB,yp.YLXZ,yp.FYFS,yp.PYDM,yp.YPBH,yp.MESS,yp.GYFF,yp.TYPE,yp.YPDM,yp.YPJL,yp.JLDW,yp.YKZF,yp.YFZF,yp.ZXCD,yp.YCYL," +
                "kc.YPCD,kc.LSJG,kc.KCSL,kc.BZLJ,yp.UNITCODE,yp.UNTCODENAME  FROM  YK_TYPK yp,YK_KCMX kc where 1=1 and kc.YPXH=yp.YPXH ";*/
        String sql = "SELECT yp.serial,yp.group_no,yp.drugname,yp.dosage,yp.mini_unit,yp.pack_size,yp.specification,yp.retprice,yp.pack_retprice,yp.stock_amount,yp.visible_flag,yp.drug_flag,yp.py_code,yp.pack_unit,yp.manu_name,yp.weigh_unit,yp.vol_unit,yp.mini_unit_name,yp.pack_unit_name,yp.weigh_unit_name,yp.vol_unit_name," +
                "yp.manu_code,yp.ypjl,yp.jldw,yp.fyfs,yp.jbyw  FROM HLW_YP yp where 1=1  ";
        if (StringUtils.isNoneBlank(ypdm)){
            sql+=" and lower(yp.serial) like '%"+ypdm.toLowerCase()+"%' ";
        }
        if (StringUtils.isNoneBlank(ypmc)){
            sql+=" and lower(yp.drugname) like '%"+ypmc.toLowerCase()+"%' ";
        }
        if (StringUtils.isNoneBlank(pydm)){
            sql+=" and lower(yp.py_code) like '%"+pydm.toLowerCase()+"%' ";
        }
        if (StringUtils.isNoneBlank(group_no)&&group_no.equalsIgnoreCase("82")){
            sql+=" and yp.group_no='草药库'";
        }else {
            sql+=" and yp.group_no in('成药库','西药库')";
        }
        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 findSypc(String pcbm) throws Exception {
        String sql = "select s.PCBM,s.PCMC,s.MRCS,s.MZCS,s.YFBM,s.JGRS  from GY_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("sypc："+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) throws Exception {
        String sql = "select y.YPYF,y.PYDM,y.XMMC,y.XMLB,y.FYXH from ZY_YPYF y where 1=1  and y.PYDM is not null";
        if (StringUtils.isNoneBlank(pydm)){
            sql+=" and lower(y.PYDM)='"+pydm.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("ypyf："+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;
    }

    /**
     * 获取icd10
     * @return
     * @throws Exception
     */
    public JSONArray synYkICD10() throws Exception {
        String sql = "select i.JBXH,i.JBMC,i.PYDM, from GY_JBBM 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("JBXH"));
                dictIcd10DO.setName(object.getString("JBMC"));
                dictIcd10DO.setDescription(object.getString("PYDM"));
                ykDictIcd10Dao.save(dictIcd10DO);
            }
        }
        return array;
    }


    /**
     * 获取诊断
     * @param pyCode
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray findIcd10(String pyCode,boolean demoFlag) throws Exception {
        String sql = "select i.JBXH as code ,i.JBMC as name,i.PYDM as pydm from GY_JBBM i ";
        JSONArray array = new JSONArray();
        if (StringUtils.isNoneBlank(pyCode)){
            sql +="  where lower(i.PYDM) like '%"+pyCode.toLowerCase()+"%'";
        }
        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");
        }
        return array;
    }

    /**
     * HIS就诊患者历史查询
     * @throws Exception
     */
    public JSONArray findV_ZKSG_HZCX_HIS(String brid,String conNo,String startTime,String endTime,String ksdm) throws Exception{
        String sql = "SELECT h.JZXH,h.GHXH,h.BRBH,h.KSDM,h.YSDM,zd.JBMC as ZYZD,h.KSSJ,h.JSSJ,h.JZZT,h.FZRQ,h.GHFZ,ks.KSMC,yg.YGXM  from YS_MZ_JZLS h,GY_KSDM ks,GY_YGDM yg " +
                " ,GY_JBBM zd  WHERE yg.YGDM=h.YSDM and ks.KSDM=h.KSDM and h.ZYZD = zd.JBXH and  h.BRBH = "+brid+" ";
        if(!StringUtil.isBlank(conNo)){
            sql += " and h.JZXH = " + conNo;
        }
        if(!StringUtil.isBlank(startTime)){
            sql += " and  h.KSSJ  >= '"+startTime+"' ";
        }
        if(!StringUtil.isBlank(endTime)){
            sql += " and h.KSSJ  <= '"+endTime+"' ";
        }if(!StringUtil.isBlank(ksdm)){
            sql += " and h.KSDM = " + ksdm;
        }

        sql += " order by h.KSSJ 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");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }


    /**
     * 患者门诊就诊记录
     * 使用时间查询的话，很可能会超时。时间没有索引，所以超时时间需要加长
     *
     * @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 = "350211A1002";
        String orgName = "泰安市中医医院";

        //居民id转化
        PatientMappingDO patientMappingDO = patientMappingDao.findByMappingCodeAndSource(PAT_NO,"1");


//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();
        jsonArray = findV_ZKSG_HZCX_HIS(PAT_NO,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") + "");
                if (patientMappingDO!=null){
                    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("YGXM") ? "" : jsonObjectMgsInfo.get("YGXM") + "");

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

                String icdName = null == jsonObjectMgsInfo.get("ZYZD") ? "" : jsonObjectMgsInfo.get("ZYZD") + "";
//                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.stampToDate(admDate));
                wlyyOutpatientVO.setConDate(DateUtil.stampToDate(admDate));
                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");//执行科室
                    WlyyInspectionVO wlyyInspectionVO = new WlyyInspectionVO();
                    wlyyInspectionVO.setName(fymc);
                    wlyyInspectionVO.setDeptName(zxks);
                    wlyyInspectionVO.setDept(ksdm1);
                    wlyyInspectionVO.setQuantity(Integer.parseInt(fysl));
                    inspectionVOList.add(wlyyInspectionVO);
                }
                wlyyOutpatientVO.setInspectionVOS(inspectionVOList);*/
                wlyyOutpatientVOS.add(wlyyOutpatientVO);
            }
        }
        return wlyyOutpatientVOS;
    }


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

        //处方数据
        String msd01 = "SELECT d.CFLX,d.BRID,d.BRXM,d.FPHM,d.MZXH,d.JZKH,d.JZXH,d.CFSB,d.CFHM,d.KSDM  FROM MS_CF01_YD d WHERE d.JZXH = '"+admNo+"'";
        JSONObject rs = new JSONObject();
        String content="";
        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 d.YPXH,d.YPCD,d.YPSL,d.YPDJ,d.YFDW,d.YFDW,d.MRCS,d.YFBZ,d.YPYF,d.YYTS,d.SBXH,d.YFGG  FROM MS_CF02_YD d WHERE d.CFSB = '"+wlyyPrescriptionVO.getRealOrder()+"'";

                JSONObject rs1 =new JSONObject();
                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 ,YPMC  from YK_TYPK WHERE YPXH='"+object1.getString("YPXH")+"' ";
                        JSONObject rs4 = new JSONObject();
                        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("YPMC"));
                            }
                        }
                        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("MRCS"));
                        prescriptionInfoVO.setPackQuantity(object1.getInteger("YFBZ"));
                        prescriptionInfoVO.setUsageCode(object1.getString("YPYF"));
                        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();
                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;
    }

    /**
     * 获取检查检验字典
     * @throws Exception
     */
    public JSONArray findVpacsBw(String pyKey) throws Exception{
        String sql = " SELECT bw.DMMC,bw.jcbw,bw.fyxh,bw.FYMC,bw.FYDW,bw.fysl,bw.FYDJ,bw.jclx,bw.JCMC,bw.SRDM FROM HLW_PACS_BW bw WHERE 1=1   ";
        if (StringUtils.isNoneBlank(pyKey)){
            sql+= " and  lower(bw.SRDM) like '%"+pyKey+"%' ";
        }
        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");
        JSONArray array = new JSONArray();
        if(status!=null&&status == 200){
            JSONArray jsonArray = rs.getJSONArray("detailModelList");
            for (int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                JSONObject object = new JSONObject();
                object.put("name",jsonObject.getString("DMMC"));
                object.put("charge_unit",jsonObject.getString("FYDW"));
                object.put("charge_amount",jsonObject.getString("FYDJ"));
                object.put("py_code",jsonObject.getString("SRDM"));
                object.put("code",jsonObject.getString("jcbw"));
                object.put("exec_unit",jsonObject.getString("fyxh"));
                object.put("fysl",jsonObject.getString("fysl"));
                object.put("FYMC",jsonObject.getString("FYMC"));
                object.put("jclx",jsonObject.getString("jclx"));
                object.put("JCMC",jsonObject.getString("JCMC"));
                array.add(object);
            }
        }
        return array;
    }


    /**
     * 查询某个门诊患者记录
     * @param doctor
     * @return
     * @throws Exception
     */
    public JSONArray selectMzRecord(String doctor,String patientName) throws Exception {
        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
        String condition = "";
        if (doctorMappingDO!=null){
            condition = " and mz.YSDM ='"+doctorMappingDO.getMappingCode()+"' ";
        }

        String sql = "SELECT br.BRID,br.BRXM,br.BRXB,CONVERT(varchar(100), br.CSNY, 120) as birthDay,br.MZHM,br.SFZH from MS_BRDA br WHERE br.BRID IN(SELECT mz.BRBH FROM YS_MZ_JZLS mz where 1=1 "+condition+" GROUP BY mz.BRBH ) and br.SFZH is not null and br.BRXM !='作废' ";
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and br.BRXM like '%"+patientName+"%'";
        }
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("selectMzRecord："+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");
        JSONArray array = new JSONArray();
        JSONArray array1 = new JSONArray();
        if(status!=null&&status == 200){
            array = rs.getJSONArray("detailModelList");
            for (int i = 0;i<array.size();i++){
                JSONObject jsonObject = JSONObject.parseObject(array.get(i).toString());
                if (jsonObject.get("SFZH")!=null){
                    String szfh = jsonObject.getString("SFZH");
                    jsonObject.put("sex",IdCardUtil.getSexForIdcard(szfh));
                    jsonObject.put("age",IdCardUtil.getAgeForIdcard(szfh));
                }
                array1.add(jsonObject);

            }

            logger.info("selectMzRecord size:"+array.size());
        }
        return array1;
    }

    /**
     * 查询某个医生住院患者记录
     * @param doctor
     * @return
     * @throws Exception
     */
    public JSONArray selectZyRecord(String doctor,String patientName) throws Exception {
        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(doctor);
        String condition = "";
        if (doctorMappingDO!=null){
            condition = " and (brry.zyys= '"+doctorMappingDO.getMappingCode()+"' or brry.zzys= '"+doctorMappingDO.getMappingCode()+"' or brry.szys= '"+doctorMappingDO.getMappingCode()+"') ";
        }else {
            return null;
        }
        String sql = "SELECT br.BRID,br.BRXM,br.BRXB,CONVERT(varchar(100), br.CSNY, 120) as birthDay ,br.MZHM,br.SFZH from MS_BRDA br WHERE br.BRID IN(SELECT cast(brry.BAHM as numeric(18,0)) FROM ZY_BRRY brry where 1=1 and isnumeric(brry.BAHM) = 1 "+condition+" GROUP BY brry.BAHM) and br.BRXM !='作废' and br.SFZH is not null ";
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and br.BRXM like '%"+patientName+"%' ";
        }
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        logger.info("selectZyRecord："+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");
        JSONArray array = new JSONArray();
        JSONArray array1 = new JSONArray();
        if(status!=null&&status == 200){
            array = rs.getJSONArray("detailModelList");
            for (int i = 0;i<array.size();i++){
                JSONObject jsonObject = JSONObject.parseObject(array.get(i).toString());
                if (jsonObject.get("SFZH")!=null){
                    String szfh = jsonObject.getString("SFZH");
                    jsonObject.put("sex",IdCardUtil.getSexForIdcard(szfh));
                    jsonObject.put("age",IdCardUtil.getAgeForIdcard(szfh));
                }
                array1.add(jsonObject);
            }
            logger.info("selectZyRecord size:"+array.size());
        }
        return array1;
    }


    /**
     * 健康档案中门诊记录
     * @throws Exception
     */
    public JSONArray findJKTA_V_ZKSG_HZCX_HIS(String brid) throws Exception{
        String sql = "SELECT h.JZXH,h.GHXH,h.BRBH,h.KSDM,h.YSDM,h.ZYZD,h.KSSJ,h.JSSJ,h.JZZT,h.FZRQ,h.GHFZ,ks.KSMC,yg.YGXM  from YS_MZ_JZLS h,GY_KSDM ks,GY_YGDM yg WHERE yg.YGDM=h.YSDM and ks.KSDM=h.KSDM and  h.BRBH = "+brid+" ";
        sql += " order by h.KSSJ desc";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("findJKTA_V_ZKSG_HZCX_HIS:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * 上门服务项目
     * @return
     * @throws Exception
     */
    public JSONArray findGY_YLSF() throws Exception{
        String sql = "SELECT * from GY_YLSF h";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("findGY_YLSF:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }

    /**
     * 获取健康档案住院记录
     * @param brid
     * @return
     * @throws Exception
     */
    public JSONArray findJKTA_ZY_RECORD(String brid) throws Exception{
        String sql = "SELECT\n" +
                "\tbrry.ZYH,\n" +
                "\tbrry.ZYHM,\n" +
                "\tbrry.ZYDM,\n" +
                "\tbrry.ZYYS,\n" +
                "\tbrry.ZZYS,\n" +
                "\tbrry.SZYS,\n" +
                "\tbrry.zyysxm ,\n" +
                "\tbrry.zzysxm ,\n" +
                "\tbrry.szysxm ,\n" +
                "\tbrry.KSRQ,\n" +
                "\tbrry.JSRQ,\n" +
                "\tbrry.JGDM,\n" +
                "\tbrry.KSMC,\n" +
                "\tbrry.BAHM,\n" +
                "\tbrry.BRXM\n" +
                "FROM\n" +
                "\tV_ZY_BRRY brry\n" +
                "where\n" +
                "  brry.BAHM ='"+brid+"' ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("findJKTA_ZY_RECORD:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            return rs.getJSONArray("detailModelList");
        }
        return new JSONArray();
    }




    public JSONObject getAccessToken() throws Exception {
        String url = "http://tazhongyi.519e.com.cn/Api/ApiReport/GetAccessToken";
        HttpResponse httpResponse = HttpUtils.doPost(url,null);
        String content = httpResponse.getContent();
        logger.info("getAccessToken:"+content);
        JSONObject rs = JSON.parseObject(content);
        return rs;
    }





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


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

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

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

            prescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);

         /*   List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(code,1);*/
            synPrecriptionTnHis(prescriptionVO,code);
            /*//同步检查检验
            if(null!=inspectionDOS&&inspectionDOS.size()>0){
                synInspect(inspectionDOS);
            }*/
        }

        return wlyyPrescriptionDOs.toString();

    }


    public WlyyPrescriptionVO synPrecriptionTnHis(WlyyPrescriptionVO wlyyPrescriptionVO,String code) throws Exception {
        HlwTnCf01DO hlwCf01DO = new HlwTnCf01DO();
        logger.info("开始===================");
        if (wlyyPrescriptionVO!=null){
            try {

                hlwCf01DO.setYFSB(20);
                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.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.setPjbz(0);
                hlwCf01DO.setFypj(0);
                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());
                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.setOriginRealOrder(cfhm);
                                prescriptionDao.save(wlyyPrescriptionDO);
                            }
                        }
                        logger.info("表HLW_CF01同步成功！");

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

                    String sql = "update MS_CF01_YD t set t.ZFPB=1  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.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============");
                        HlwTnCf02DO hlwCf02DO = new HlwTnCf02DO();
                        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(1);//费用归并
                        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.setSL(Integer.parseInt(wlyyPrescriptionInfoVO.getQuantity()));
                        hlwCf02DO.setPSPB(0);
                        hlwCf02DO.setYYTS(1);
                        hlwCf02DO.setJhjg(0);
                        hlwCf02DO.setJhje(0);
                        hlwCf02DO.setJhjg1(0);
                        hlwCf02DO.setDzdr(0);
                        hlwCf02DO.setYCJL(wlyyPrescriptionInfoVO.getDosage()!=null?Double.parseDouble(wlyyPrescriptionInfoVO.getDosage()):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;
    }

}
