package com.yihu.jw.healthCare.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.healthCare.*;
import com.yihu.jw.entity.hospital.httplog.YlzHttpLogDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionExpressageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.healthCare.utils.AES;
import com.yihu.jw.healthCare.utils.SafeUtil;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.healthCare.*;
import com.yihu.jw.hospital.httplog.dao.YlzHttpLogDao;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.LatitudeUtils;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 医保对接
 * Created by wangzhinan 20211002
 */
@Service
@Transactional
public class HealthCareService {
    private Logger logger = LoggerFactory.getLogger(HealthCareService.class);
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private PrescriptionExpressageDao prescriptionExpressageDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private YlzHttpLogDao ylzHttpLogDao;
    @Autowired
    private PatientMappingDao patientMappingDao;
    @Autowired
    private YlzMedicalPrescriptionUploadDao ylzMedicalPrescriptionUploadDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private YlzMedicailRelationDao ylzMedicailRelationDao;
    @Autowired
    private YlzMedicailBillDao ylzMedicailBillDao;
    @Autowired
    private YlzMedicailIcdDao ylzMedicailIcdDao;
    @Autowired
    private YlzMedicailMxDao ylzMedicailMxDao;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;

    private String ylzConfigUrl;
    private String ylzConfigAppid;
    private String ylzConfigAppSecret;
    private String ylzConfigEncryptKey;
    private String ylzConfigSignKey;
    private String ylzConfigOrgCode;

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


    public void initConfig() throws Exception{
        logger.info("初始话参数！");
        List<WlyyHospitalSysDictDO> hospitalSysDictDOS = hospitalSysDictDao.findByDictName("ylzConfig");
        if (hospitalSysDictDOS==null||hospitalSysDictDOS.size()==0){
            throw new Exception("尚未添加配置参数");
        }else {
            for (WlyyHospitalSysDictDO hospitalSysDictDO:hospitalSysDictDOS){
                if (hospitalSysDictDO.getId().equalsIgnoreCase("ylzConfigUrl")){
                    ylzConfigUrl = hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getId().equalsIgnoreCase("ylzConfigAppid")){
                    ylzConfigAppid = hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getId().equalsIgnoreCase("ylzConfigAppSecret")){
                    ylzConfigAppSecret = hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getId().equalsIgnoreCase("ylzConfigEncryptKey")){
                    ylzConfigEncryptKey = hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getId().equalsIgnoreCase("ylzConfigSignKey")){
                    ylzConfigSignKey = hospitalSysDictDO.getDictValue();
                }
                if (hospitalSysDictDO.getId().equalsIgnoreCase("ylzConfigOrgCode")){
                    ylzConfigOrgCode = hospitalSysDictDO.getDictValue();
                }
            }
        }
    }

    /**
     * 医保统一调用接口
     * @param data
     * @param funid
     * @param name
     * @return
     * @throws Exception
     */
    public String requestYlz(JSONObject data,String funid,String name) throws Exception {
        YlzHttpLogDO ylzHttpLogDO = new YlzHttpLogDO();
        initConfig();
        JSONObject object = new JSONObject();
        object.put("sign_type","md5");
        object.put("appid",ylzConfigAppid);
        String accessToken = getYlzToken();
        if (accessToken==null){
            throw new Exception("token无效");
        }
        object.put("access_token",accessToken);
        object.put("funid",funid);
        data.put("appid",ylzConfigAppid);
        data.put("org_code",ylzConfigOrgCode);
        object.put("data",data);
        String signResult = SafeUtil.sign(object.toJSONString(),ylzConfigSignKey);
        String obj = SafeUtil.encrypt(signResult,ylzConfigEncryptKey);
        JSONObject jsonObject = JSONObject.parseObject(obj);
        logger.info("请求前funid=="+funid+"data="+data.toJSONString());
        String response = httpClientUtil.postBody(ylzConfigUrl,jsonObject);
        ylzHttpLogDO.setResponseEncrpty(response);
        if (response!=null&&response!=""){
            JSONObject result = JSONObject.parseObject(response);
            if (result.getString("flag").equalsIgnoreCase("1")){
                String dataResult = result.getString("encrypt_data");
                result.remove("encrypt_data");
                if (dataResult!=null&&dataResult!=""){
                    String decryptResult = AES.aesDecrypt(dataResult,ylzConfigEncryptKey);
                    JSONObject dataObject = JSONObject.parseObject(decryptResult);
                    result.put("encrypt_data",dataObject);
                    response = result.toJSONString();
                }
            }
        }
        ylzHttpLogDO.setCode(funid);
        ylzHttpLogDO.setName(name);
        ylzHttpLogDO.setRequest(data.toJSONString());
        ylzHttpLogDO.setRequestEncrpty(obj);
        ylzHttpLogDO.setResponse(response);
        ylzHttpLogDO.setCreateTime(new Date());
        ylzHttpLogDao.save(ylzHttpLogDO);
        return response;
    }

    /**
     * 获取token
     * @return
     * @throws Exception
     */
    /**
     * 2.3.1	医师身份验证(处方权，多点执业等)
     */
    public String doctorAuthentication(String doctorId){
        try {
            BaseDoctorDO doctorDO = doctorDao.findOne(doctorId);
            if (doctorDO == null){
                throw new Exception("医生不存在");
            }
            List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(doctorId);
            if(doctorHospitalDOS.size()<=0){
                throw new Exception("未找到医生科室编码");
            }
            BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
            JSONObject data = new JSONObject();
            data.put("his_dept_code",doctorHospitalDO.getDeptCode());//his内部科室编码
            data.put("his_dept_name",doctorHospitalDO.getDeptName());//his内部科室名称
//        data.put("dept_code","");//医保科室编码	String	N
//        data.put("dept_name","");//医保科室名称	String	N
            data.put("medical_mode","10");//医疗就诊方式	10	门(急)诊
            data.put("name",doctorDO.getName());//医师姓名
            data.put("idcard",doctorDO.getIdcard());//医师证件号
            data.put("cert_type","01");//医师证件类型

            String result = requestYlz(data,"N20.17.02.01","医师身份验证");
            if(result == null){
                throw new Exception("医保请求失败");
            }
            logger.info("医师身份验证:"+result);
            JSONObject object = JSONObject.parseObject(result);
            if (object.getString("flag").equalsIgnoreCase("1")){
                JSONObject encryptData = object.getJSONObject("encrypt_data");
                return encryptData.getString("is_prescribe");
            }else {
                return "0";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    /**
     * 2.3.2	医师人脸签到表单地址
     * @param doctorId
     * @throws Exception
     */
    public String doctorFaceCheckInAddress(String doctorId)throws Exception{
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findOne("ylzConfigFaceReturnUrl");
        if(hospitalSysDictDO == null){
            throw new Exception("未配置回调地址");
        }
        BaseDoctorDO doctorDO = doctorDao.findOne(doctorId);
        if (doctorDO == null){
            throw new Exception("医生不存在");
        }
        JSONObject data = new JSONObject();
        data.put("name",doctorDO.getName());//医师姓名
        data.put("idcard",doctorDO.getIdcard());//医师证件号
        data.put("cert_type","01");//医师证件类型
        data.put("redirect_url",hospitalSysDictDO.getDictValue());//回调地址
        String result = requestYlz(data,"N20.17.02.02","医师人脸签到表单地址");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("医师人脸签到表单地址:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     * 2.3.3	获取医师人脸签到数据
     */
    public String doctorFaceCheckInData(String doctorId)throws Exception{
        BaseDoctorDO doctorDO = doctorDao.findOne(doctorId);
        if (doctorDO == null){
            throw new Exception("医生不存在");
        }
        JSONObject data = new JSONObject();
        data.put("name",doctorDO.getName());//医师姓名
        data.put("idcard",doctorDO.getIdcard());//医师证件号
        data.put("cert_type","01");//医师证件类型
        String result = requestYlz(data,"N20.17.02.05","获取医师人脸签到数据");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("获取医师人脸签到数据:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     * 2.4.1 事前提醒
     */
    public String advanceWarning(String prescriptionId){
        try {
            WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
            if (wlyyPrescriptionDO == null){
                throw new Exception("续方信息不存在");
            }
            WlyyOutpatientDO outpatientDO = outpatientDao.findOne(wlyyPrescriptionDO.getOutpatientId());
            if (outpatientDO == null){
                throw new Exception("门诊信息不存在");
            }
            WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("ylzConfigOrgCode");
            if(hospitalSysDictDO == null){
                throw new Exception("未配置网点编号");
            }

            String icCardNo = outpatientDO.getCardNo();
            String his_serial = outpatientDO.getRegisterNo();
            String org_code = hospitalSysDictDO.getDictCode();

            JSONObject data;
            //获取his处方信息
            String infoResponse = xzzxEntranceService.presUpload(icCardNo,his_serial,org_code);
            JSONObject infoObject = JSONObject.parseObject(infoResponse);
            if("0".equals(infoObject.getString("ret_code"))){
                data = infoObject;
            }else {
                throw new Exception("获取his处方信息失败："+infoObject.getString("ret_mess"));
            }

            data.remove("ret_code");
            data.remove("ret_mess");
            data.remove("log_no");

            data.put("ticket_no",outpatientDO.getXtgzh());//	单据流水号

            String result = requestYlz(data,"N20.17.03.03","事前提醒");
            if(result == null){
                throw new Exception("医保请求失败");
            }
            logger.info("事前提醒:"+result);
            JSONObject object = JSONObject.parseObject(result);
            if (object.getString("flag").equalsIgnoreCase("1")){
                JSONObject encryptData = object.getJSONObject("encrypt_data");
                return encryptData.toJSONString();
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 2.4.2	医师开方上传
     */
    public String doctorPrescriptionUpload(String prescriptionId) throws Exception{
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (wlyyPrescriptionDO == null){
            throw new Exception("续方信息不存在");
        }
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(wlyyPrescriptionDO.getOutpatientId());
        if (outpatientDO == null){
            throw new Exception("门诊信息不存在");
        }

        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("ylzConfigOrgCode");
        if(hospitalSysDictDO == null){
            throw new Exception("未配置网点编号");
        }

        String icCardNo = outpatientDO.getCardNo();
        String his_serial = outpatientDO.getRegisterNo();
        String org_code = hospitalSysDictDO.getDictCode();

        JSONObject data;
        //获取his处方信息
        String infoResponse = xzzxEntranceService.presUpload(icCardNo,his_serial,org_code);
        JSONObject infoObject = JSONObject.parseObject(infoResponse);
        if("0".equals(infoObject.getString("ret_code"))){
            data = infoObject;
        }else {
            throw new Exception("获取his处方信息失败："+infoObject.getString("ret_mess"));
        }

        data.remove("ret_code");
        data.remove("ret_mess");
        data.remove("log_no");

        data.put("order_id",prescriptionId);

        YlzMedicalPrescriptionUploadDO uploadDO = new YlzMedicalPrescriptionUploadDO();
        uploadDO.setOrgCode(org_code);
        uploadDO.setIcCardNo(icCardNo);
        uploadDO.setHisSerial(his_serial);
        uploadDO.setOutpatientId(wlyyPrescriptionDO.getOutpatientId());
        uploadDO.setPrescriptionId(prescriptionId);
        uploadDO.setRegionCode(data.getString("region_code"));
        uploadDO.setName(data.getString("name"));
        uploadDO.setIdcard(data.getString("idcard"));
        uploadDO.setCertType(data.getString("cert_type"));
        uploadDO.setDataSource("53");//53移动支付
        uploadDO.setInsuranceSerial(data.getString("insurance_serial"));
        String result = requestYlz(data,"N20.17.03.01","医师开方上传");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("医师开方上传:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            uploadDO.setTransactionNo(encryptData.getString("transaction_no"));
            ylzMedicalPrescriptionUploadDao.save(uploadDO);
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     * 2.4.3	医师开方上传取消（N20.17.03.06）
     */
    public String doctorPrescriptionUploadCancle(String prescriptionId,String cancelReason)throws Exception{

        YlzMedicalPrescriptionUploadDO uploadDO = ylzMedicalPrescriptionUploadDao.findByPrescriptionId(prescriptionId);
        if(uploadDO == null){
            throw new Exception("未找到开发上传记录");
        }

        JSONObject data = new JSONObject();
        data.put("transaction_no",uploadDO.getTransactionNo());//处方上传流水号  	String	Y
        data.put("insurance_serial",uploadDO.getInsuranceSerial());//医保流水号
        data.put("cancel_reason",cancelReason);//作废原因
        data.put("region_code",uploadDO.getRegionCode());//参保地区划代码
        data.put("idcard",uploadDO.getIdcard());//证件号码
        data.put("name",uploadDO.getName());//姓名
        data.put("cert_type",uploadDO.getCertType());//证件类型
        data.put("data_source",uploadDO.getDataSource());//数据来源	String	Y	参见编码附件

        String result = requestYlz(data,"N20.17.03.06","医师开方上传取消");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("医师开方上传取消:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     * 2.6.1	电子处方订单接收（N20.17.05.02）
     */
    public String electronicPrescriptionReceiving(String outpatientId)throws Exception{
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        if (outpatientDO == null){
            throw new Exception("门诊信息不存在");
        }
        JSONObject data = new JSONObject();
        data.put("order_code","");//订单号
        data.put("order_time",DateUtil.dateToStrLong(outpatientDO.getCreateTime()));//订单时间

        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutPatientIdList(outpatientId);
        if(wlyyPrescriptionDOS.size()==0){
            throw new Exception("处方信息不存在");
        }
        data.put("prescription_code",wlyyPrescriptionDOS.get(0).getRealOrder());//医院处方编号
        data.put("channel","1");//1、微信公众号，2、app，3、web
//        data.put("insurance_ticket_no","");//医保收费单据号	String	N	订单结算后的收费单据号
        data.put("order_state","");//订单状态    --1待发货、2配送中、3已签收、4已取消	String	Y
        List<WlyyPrescriptionExpressageDO> expressageDOList = prescriptionExpressageDao.findByOutpatientId(outpatientId);
        if(expressageDOList.size()==0){
            throw new Exception("收获信息不存在");
        }

        BasePatientDO patientDO = patientDao.findById(outpatientDO.getPatient());
        if(patientDO==null){
            throw new Exception("居民信息不存在");
        }
        WlyyPrescriptionExpressageDO expressageDO = expressageDOList.get(0);
        data.put("order_addr_detail",expressageDO.getAddress());//订单详细地址
        data.put("order_owner",expressageDO.getName());
        data.put("order_owner_idcard",patientDO.getIdcard());
        data.put("order_owner_phone",patientDO.getMobile());

        Map<String,String> map = LatitudeUtils.getGeocoderLatitude(expressageDO.getAddress());
        data.put("addr_lat",map.get("lat"));//收货地址纬度
        data.put("addr_lng",map.get("lng"));//收货地址经度
        if(expressageDO.getOneselfPickupFlg()==1){
            //自取
            data.put("delivery_way","2");//1.网订配送,2.网订自取
            data.put("qrcode_check_time","");//扫码校验时间
            data.put("receiving_time","");//药品签收时间
        }else {
            //非自取
            data.put("delivery_way","1");//配送方式 1.网订配送,2.网订自取
            data.put("delivery_number",expressageDO.getMailno());//配送单号
            data.put("delivery_org","");//配送单位
            data.put("delivery_take_time","");//配送接单时间
            data.put("delivery_name","");//配送人姓名
            data.put("delivery_id_card","");//配送人身份证
//            data.put("delivery_phone","");//配送人联系电话 N
            data.put("getmedical_time","");//骑手取药记录
            data.put("delivery_money","");//配送费

        }
//        apothecary_name	药师姓名	String	N
//        apothecary_id_card	药师身份证	String	N
//        apothecary_audit	药师审核时间	String	N

        data.put("money","");//商品金额
        data.put("settlement_time","");//结算时间
        data.put("data_source","");//数据来源
        data.put("delivery_time","");//发单时间

        data.put("elec_prescription_code",wlyyPrescriptionDOS.get(0).getId());//平台处方编号
        data.put("prescription_code",wlyyPrescriptionDOS.get(0).getRealOrder());//医院处方编号
//        data.put("insurance_serial",outpatientDO.getInsuranceSerial());//医保门诊流水号
        data.put("his_serial","");//门诊业务流水号


//        mxlist	药品明细	MXLIST	N
//        MXLIST
//        order_id	订单号	String	Y
//        settlement_no	医保结算单据号	String	Y
//        item_name	医保项目名称	String	Y
//        item_code	医保项目编码	String	Y
//        supervision_code	药品电子监管码	String	N	非必填

        String result = requestYlz(data,"N20.17.05.02","电子处方订单接收");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("电子处方订单接收:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     *2.6.2	电子处方订单取消（N20.17.05.03）
     */
    public String electronicPrescriptionCancle(String outpatientId)throws Exception{
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        if (outpatientDO == null){
            throw new Exception("门诊信息不存在");
        }
        JSONObject data = new JSONObject();
        data.put("order_code","");//订单号
        data.put("order_time",DateUtil.dateToStrLong(outpatientDO.getCreateTime()));//订单时间

        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutPatientIdList(outpatientId);
        if(wlyyPrescriptionDOS.size()==0){
            throw new Exception("处方信息不存在");
        }
        data.put("prescription_code",wlyyPrescriptionDOS.get(0).getRealOrder());//医院处方编号
        data.put("channel","1");//1、微信公众号，2、app，3、web
//        data.put("insurance_ticket_no","");//医保收费单据号	String	N	订单结算后的收费单据号
        data.put("order_state","");//订单状态    --1待发货、2配送中、3已签收、4已取消	String	Y
        data.put("cancel_time","");//订单取消时间  取消时必填
        data.put("cancel_reason","");//取消原因

        String result = requestYlz(data,"N20.17.05.03","电子处方订单取消");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("电子处方订单取消:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     * 2.6.3 获取处方流转平台药师审方结果（N20.17.05.04）
     */
    public String pharmacistReviewResults(String outpatientId)throws Exception{
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        if (outpatientDO == null){
            throw new Exception("门诊信息不存在");
        }
        JSONObject data = new JSONObject();
//        data.put("order_code","");//订单号
        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutPatientIdList(outpatientId);
        if(wlyyPrescriptionDOS.size()==0){
            throw new Exception("处方信息不存在");
        }
        data.put("prescription_code",wlyyPrescriptionDOS.get(0).getRealOrder());//医院处方编号

        String result = requestYlz(data,"N20.17.05.04","获取处方流转平台药师审方结果");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("获取处方流转平台药师审方结果:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }

    /**
     * 2.2.1	门诊提醒（N21.08.09.01）
     */
    public String outpatientReminder(String outpatientId,String doctorCode)throws Exception{
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        if (outpatientDO == null){
            throw new Exception("门诊信息不存在");
        }
        JSONObject data = new JSONObject();
//        data.put("order_code","");//订单号
        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutPatientIdList(outpatientId);
        if(wlyyPrescriptionDOS.size()==0){
            throw new Exception("处方信息不存在");
        }

        data.put("card_no",outpatientDO.getCardNo());//社保卡号
        List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(outpatientDO.getDoctor());
        if(doctorHospitalDOS.size()<=0){
            throw new Exception("未找到医生科室编码");
        }
        BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
        data.put("medical_dept_code",doctorHospitalDO.getDeptCode());//科室编码（使用医院科室编号）
        data.put("medical_dept_name",doctorHospitalDO.getDeptName());//科室名称
        data.put("doctor_code",doctorCode);//医师编号（使用医保医生编号）
        data.put("doctor_name",outpatientDO.getDoctorName());//医师姓名

        String result = requestYlz(data,"N21.08.09.01","门诊提醒");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("门诊提醒:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }


    /**
     * 2.2.2	门诊事中提醒（N21.08.09.02）
     */
    public String outpatientEventReminder(String outpatientId,String doctorCode)throws Exception{
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        if (outpatientDO == null){
            throw new Exception("门诊信息不存在");
        }
        JSONObject data = new JSONObject();
//        data.put("order_code","");//订单号

        data.put("card_no",outpatientDO.getCardNo());//社保卡号
        data.put("visit_no",outpatientDO.getRegisterNo());//门诊挂号号
        data.put("visit_type","1");//就诊类型	String	Y	（1住院、2门诊）
        data.put("medicine_type","");//医疗类别	String	Y
        List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(outpatientDO.getDoctor());
        if(doctorHospitalDOS.size()<=0){
            throw new Exception("未找到医生科室编码");
        }

        BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
        data.put("medical_dept_code",doctorHospitalDO.getDeptCode());//科室编码（使用医院科室编号）
        data.put("medical_dept_name",doctorHospitalDO.getDeptName());//科室名称
        data.put("doctor_code",doctorCode);//医师编号（使用医保医生编号）
        data.put("doctor_name",outpatientDO.getDoctorName());//医师姓名
        data.put("doctor_advice_no","");// 	处方流水号（医院内部唯一号）	String	Y

        //医嘱
        JSONArray advice_details = new JSONArray();
        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutPatientIdList(outpatientId);
        if(wlyyPrescriptionDOS.size()==0){
            throw new Exception("处方信息不存在");
        }

        for (WlyyPrescriptionDO wlyyPrescriptionDO:wlyyPrescriptionDOS){
            List<WlyyPrescriptionInfoDO> prescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
            for (WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO:prescriptionInfoDOS){
                JSONObject infoObj = new JSONObject();
                infoObj.put("project_code","");//项目编码	String	Y	(使用医保三目录项目编码)，正常情况必填，特殊情况，如生化全套等没有医保编码，可放空。
                infoObj.put("hospital_code","");//院内项目编码
                infoObj.put("project_name","");//项目名称
                infoObj.put("recipe_no",wlyyPrescriptionDO.getRealOrder());//处方号
                infoObj.put("invoice_project","");//发票项目编码	String	Y	（使用医保发票项目编码）

                infoObj.put("medical_specification",wlyyPrescriptionInfoDO.getSpecification());//规格型号
                infoObj.put("dose_form",wlyyPrescriptionInfoDO.getDosage());//剂型
                infoObj.put("charge_unit","");//单位
                infoObj.put("price",wlyyPrescriptionInfoDO.getPackRetprice());//单价
                infoObj.put("dose_unit",wlyyPrescriptionInfoDO.getPackRetprice());//单价
                infoObj.put("medical_number",wlyyPrescriptionInfoDO.getQuantity());//数量
                infoObj.put("amount",wlyyPrescriptionInfoDO.getPackRetprice()*Integer.parseInt(wlyyPrescriptionInfoDO.getQuantity()));//金额
                infoObj.put("single_dose_number","");//每次用量
                infoObj.put("single_dose_unit","");//每次用量
                infoObj.put("use_frequency",wlyyPrescriptionInfoDO.getUsageName());//使用频次
                infoObj.put("deliver_way","");//具体给药途径详见附录三的编码
                infoObj.put("use_day",wlyyPrescriptionInfoDO.getDays());//用药天数

/*                dose_form	剂型, 	String	Y	具体可使用剂型详见附录五的编码
                medical_specification	规格	String	Y
                price	单价	String	Y	必须使用数值型，如”12.5”
                medical_number	数量	String	Y	必须使用数值型，如”10”
                dose_unit	单价 String	Y
                amount	金额	String	Y	必须使用数值型，如”50.5”
                use_day	用药天数	String	Y	（项目为药品时非空），医嘱服用该药品天数，必须使用数值型，如”15”
                single_dose_number	单次用药量	String	Y	（项目为药品时非空），配合下一个字段的单位，如 50 mg，必须使用数值型，如”50”
                single_dose_unit	单次用药量剂量单位	String	Y	（项目为药品时非空），具体可使用剂量单位详见附录四的编码
                take_medical_number	取药总量（	String	Y	项目为药品时非空），配合下一个字段的单位，如 500 mg，必须使用数值型，如”500”
                take_medical_unit	取药总量剂量单位	String	Y	（项目为药品时非空），具体可使用剂量单位附录四的编码
                dose_day	药量天数	String	Y	（项目为药品时非空），依据医嘱服药要求，所配药品患者可以服用的天数，必须使用数值型，如”5”
                deliver_way	给药途径	String	Y	具体给药途径详见附录三的编码
                take_frequence	服用频次	String	Y
                具体可用服用频次详见附录二的编码*/

                advice_details.add(infoObj);
            }
        }

        data.put("advice_details",advice_details);

        //诊断
        JSONArray diagnoses = new JSONArray();
        String icd10 = outpatientDO.getIcd10();
        String icd10Name = outpatientDO.getIcd10Name();
        String icd[] = icd10.split(",");
        String icdName[] = icd10Name.split(",");
        for (int i=0;i<icd.length;i++){
            JSONObject icdObj = new JSONObject();
            icdObj.put("disease_code_icd10",icd[i]);//诊断或症状编码
            icdObj.put("disease_name_icd10",icdName[i]);//诊断或症状名称
            diagnoses.add(icdObj);
        }
        data.put("diagnoses",diagnoses);


        String result = requestYlz(data,"N21.08.09.02","门诊事中提醒");
        if(result == null){
            throw new Exception("医保请求失败");
        }
        logger.info("门诊事中提醒:"+result);
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            return encryptData.toJSONString();
        }
        return result;
    }


    public String getYlzToken() throws Exception {
        YlzHttpLogDO ylzHttpLogDO = new YlzHttpLogDO();
        String token = null;
        initConfig();
        String funid = "N00.00.00.01";
        JSONObject data = new JSONObject();
        data.put("appid",ylzConfigAppid);
        data.put("appsecret",ylzConfigAppSecret);
        data.put("grant_type","client_credentials");
        JSONObject object = new JSONObject();
        object.put("sign_type","md5");
        object.put("appid",ylzConfigAppid);
       /* String stringSignTemp ="appid="+ylzConfigAppid+"&appsecret="+ylzConfigAppSecret+"&data="+data+"&funid="+funid+"&sign_type=md5&key="+ylzConfigSignKey;
        String sign = MD5.md5(stringSignTemp).toUpperCase();*/
        object.put("data",data);
        object.put("funid",funid);
        String signResult = SafeUtil.sign(object.toJSONString(),ylzConfigSignKey);
        String obj = SafeUtil.encrypt(signResult,ylzConfigEncryptKey);
        JSONObject jsonObject = JSONObject.parseObject(obj);
        logger.info("请求前funid=="+funid+"data="+data);
        String response = httpClientUtil.postBody(ylzConfigUrl,jsonObject);
        ylzHttpLogDO.setResponseEncrpty(response);
        logger.info("请求后response=="+response);
        if (response!=null&&response!=""){
            JSONObject result = JSONObject.parseObject(response);
            if (result.getString("flag").equalsIgnoreCase("1")){
                String dataResult = result.getString("encrypt_data");
                result.remove("encrypt_data");
                if (dataResult!=null&&dataResult!=""){
                    String decryptResult = AES.aesDecrypt(dataResult,ylzConfigEncryptKey);
                    JSONObject dataObject = JSONObject.parseObject(decryptResult);
                    result.put("encrypt_data",dataObject);
                    response = result.toString();
                    token = dataObject.getString("access_token");
                }
            }
        }
        ylzHttpLogDO.setCode(funid);
        ylzHttpLogDO.setName("获取AccessToken");
        ylzHttpLogDO.setRequest(data.toJSONString());
        ylzHttpLogDO.setRequestEncrpty(obj);
        ylzHttpLogDO.setResponse(response);
        ylzHttpLogDO.setCreateTime(new Date());
        ylzHttpLogDao.save(ylzHttpLogDO);
        
        return token;
    }


    /**
     * 2.2.1渠道应用是否已授权（N20.17.01.01）
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public String authorized(String patient) throws Exception{
        String funid = "N20.17.01.01";
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO==null){
            throw new Exception("患者信息不存在");
        }
        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patient);
        if (patientMappingDO==null){
            throw new Exception("患者his信息不存在");
        }
        JSONObject data = new JSONObject();
        data.put("service_id","10000");
        data.put("name",patientDO.getName());
        data.put("idcard",patientDO.getIdcard());
        data.put("cert_type","01");//TODO
        data.put("phone",patientDO.getMobile());
        data.put("user_id",patientMappingDO.getMappingCode());
        String result = requestYlz(data,funid,"渠道应用是否已授权");
        return result;
    }


    /**
     * 2.2.1渠道应用是否已授权（N20.17.01.01）
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public String authorizedToEntrace(String patient) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"authorized?patient="+patient;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.2.2医保在线服务授权表单（H5表单/小程序）（N20.17.01.02）
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public String medicareOnline(String patient) throws Exception{
        String funid = "N20.17.01.02";
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("ylzConfigRedirectUrl");
        if (hospitalSysDictDO==null){
            throw new Exception("回调地址为空！");
        }
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO==null){
            throw new Exception("患者信息不存在");
        }
        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patient);
        if (patientMappingDO==null){
            throw new Exception("患者his信息不存在");
        }
        JSONObject data = new JSONObject();
        data.put("service_id","10000");
        data.put("name",patientDO.getName());
        data.put("idcard",patientDO.getIdcard());
        data.put("cert_type","01");//TODO
        data.put("phone",patientDO.getMobile());
        data.put("user_id",patientMappingDO.getMappingCode());
        data.put("redirect_url",hospitalSysDictDO.getDictValue());
        String result = requestYlz(data,funid,"医保在线服务授权表单");
        return result;
    }


    /**
     * 2.2.2医保在线服务授权表单（H5表单/小程序）（N20.17.01.02）
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public String medicareOnlineToEntrance(String patient) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"medicareOnline?patient="+patient;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.1医保挂号（N20.17.04.01）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String register(String registerNo) throws Exception{
        String funid = "N20.17.04.01";
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("上传医保挂号失败：结算信息为空！");
        }
        JSONObject data = new JSONObject();
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("cert_type",ylzMedicalRelationDO.getCertType());//证件类型
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("medical_type",ylzMedicalRelationDO.getMedicalType());//医疗类别
        data.put("his_serial",ylzMedicalRelationDO.getHisSerial());//his流水号
        data.put("his_dept_code",ylzMedicalRelationDO.getHisDeptCode());//his内部科室编码
        data.put("his_dept_name",ylzMedicalRelationDO.getHisDeptName());//his内部科室名称
        data.put("emergency_sign",ylzMedicalRelationDO.getEmergencySign());//急诊标志0 否，1 是
        data.put("trauma_sign",ylzMedicalRelationDO.getTraumaSign());//外伤标志0 否，1 是
        data.put("date", DateUtil.dateToStrLong(ylzMedicalRelationDO.getDate()));//实际门诊/入院日期 若为空，默认取系统时间
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        String result = requestYlz(data,funid,"医保挂号");
        if (result==null){
            throw new Exception("上传医保挂号失败！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            String insuranceSerial = encryptData.getString("insurance_serial");
            ylzMedicalRelationDO.setInsuranceSerial(insuranceSerial);
            ylzMedicailRelationDao.save(ylzMedicalRelationDO);
            logger.info("医保挂号流水号保存成功");
        }
        return result;
    }

    /**
     * 2.5.1医保挂号（N20.17.04.01）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String registerToEntrance(String registerNo) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"register?registerNo="+registerNo;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.2医保挂号冲销（N20.17.04.02）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String registerBack(String registerNo) throws Exception{
        String funid = "N20.17.04.02";
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("医保挂号冲销失败：结算信息为空！");
        }
        JSONObject data = new JSONObject();
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("cert_type",ylzMedicalRelationDO.getCertType());//证件类型
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("medical_type",ylzMedicalRelationDO.getMedicalType());//医疗类别
        data.put("his_serial",ylzMedicalRelationDO.getHisSerial());//his流水号
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        String result = requestYlz(data,funid,"医保挂号冲销");
        if (result==null){
            throw new Exception("上传医保挂号冲销失败！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            String invalidSerial = encryptData.getString("refund_serial");
            logger.info("医保挂号冲销流水号保存成功");
        }
        return result;
    }


    /**
     * 2.5.2医保挂号冲销（N20.17.04.02）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String registerBackToEntrance(String registerNo) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"registerBack?registerNo="+registerNo;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.3医保费用明细上传（N20.17.04.03）
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String feeDetailUpload(String registerNo) throws Exception{
        String funid = "N20.17.04.03";
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("医保费用明细上传：结算信息为空！");
        }
        JSONObject data = new JSONObject();
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("cert_type",ylzMedicalRelationDO.getCertType());//证件类型 TODO
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("his_serial",ylzMedicalRelationDO.getHisSerial());//his流水号
        data.put("item_count",ylzMedicalRelationDO.getItemCount());//明细项目数量
        data.put("total_amount",ylzMedicalRelationDO.getTotalAmount());//医疗费总金额
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        List<YlzMedicalIcdDO> ylzMedicalIcdDOList = ylzMedicailIcdDao.findByMedicalId(ylzMedicalRelationDO.getId());
        if (ylzMedicalIcdDOList==null){
            throw new Exception("医保费用明细上传：诊断结算信息为空！");
        }
        JSONArray icdArray = new JSONArray();
        for (YlzMedicalIcdDO ylzMI:ylzMedicalIcdDOList){
            JSONObject icdObj = new JSONObject();
            icdObj.put("disease_code_icd10",ylzMI.getDiseaseCodeIcd10());//诊断或症状编码
            icdObj.put("disease_name_icd10",ylzMI.getDiseaseNameIcd10());//诊断或症状名称
            icdObj.put("disease_type",ylzMI.getDiseaseType());//诊断或症状类型
            icdObj.put("disease_order",ylzMI.getDiseaseOrder());//诊断或症状序号
            icdArray.add(icdObj);
        }
        data.put("zdlist",icdArray);
        List<YlzMedicalMxDO> ylzMedicalMxDOS = ylzMedicailMxDao.findByMedicalId(ylzMedicalRelationDO.getId());
        if (ylzMedicalIcdDOList==null){
            throw new Exception("医保费用明细上传：诊断结算信息为空！");
        }
        JSONArray infoArray = new JSONArray();
        for (YlzMedicalMxDO ylzMedicalMxDO:ylzMedicalMxDOS){
                JSONObject infoObj = new JSONObject();
                infoObj.put("prescription_code",ylzMedicalMxDO.getPrescriptionCode());//医院处方编号
                infoObj.put("his_detail_sn",ylzMedicalMxDO.getHisDetailSn());//his处方明细流水号
                infoObj.put("item_name",ylzMedicalMxDO.getItemName());//医保项目名称
                infoObj.put("item_code",ylzMedicalMxDO.getItemCode());//医保项目编码
                infoObj.put("specification_type",ylzMedicalMxDO.getSpecificationType());//规格型号
                infoObj.put("dosage_form",ylzMedicalMxDO.getDosageForm());//剂型
                infoObj.put("charge_unit",ylzMedicalMxDO.getChargeUnit());//单位
                infoObj.put("price",ylzMedicalMxDO.getPrice());//单价
                infoObj.put("amount",ylzMedicalMxDO.getAmount());//数量
                infoObj.put("total_money",ylzMedicalMxDO.getTotalMoney());//金额
                infoObj.put("prescription_date", DateUtil.dateToStrLong(ylzMedicalMxDO.getPrescriptionDate()));//处方日期
                infoObj.put("his_dept_code",ylzMedicalMxDO.getHisDeptCode());//his内部科室编码
                infoObj.put("his_dept_name",ylzMedicalMxDO.getHisDeptName());//his内部科室名称
                infoObj.put("medical_per_name",ylzMedicalMxDO.getMedicalPerName());//医疗服务人员姓名
                infoObj.put("medical_per_id",ylzMedicalMxDO.getMedicalPerId());//医疗服务人员证件号码
                infoObj.put("limit_type",ylzMedicalMxDO.getLimitType());//限制范围类别
                infoObj.put("actg_date",DateUtil.dateToStr(ylzMedicalMxDO.getActgDate(),DateUtil.YYYYMMDD));//记帐日期
                infoObj.put("his_item_name",ylzMedicalMxDO.getHisItemName());//HIS院内项目名称
                infoObj.put("his_item_code",ylzMedicalMxDO.getHisItemCode());//HIS院内项目编码
                infoObj.put("clerk_days",DateUtil.dateToStrLong(ylzMedicalMxDO.getClerkDays()));//记帐日期
                infoObj.put("people_type",ylzMedicalMxDO.getPeopleType());//医保服务人员类别
                infoArray.add(infoObj);
        }
        data.put("mxlist",infoArray);
        String result = requestYlz(data,funid,"医保费用明细上传");
        if (result==null){
            throw new Exception("医保费用明细上传失败！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            String detailSerial = encryptData.getString("detail_serial");
            ylzMedicalRelationDO.setDetailSerial(detailSerial);
            ylzMedicailRelationDao.save(ylzMedicalRelationDO);
            logger.info("医保费用明细上传失败保存成功");
        }
        return result;
    }

    /**
     * 2.5.3医保费用明细上传（N20.17.04.03）
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String feeDetailUploadToEntrance(String registerNo) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"feeDetailUpload?registerNo="+registerNo;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.4医保费用明细上传冲销（N20.17.04.04）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String feeDetailRefund(String registerNo,String remark) throws Exception{
        String funid = "N20.17.04.04";
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("医保费用明细上传：结算信息为空！");
        }
        JSONObject data = new JSONObject();
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("medical_type",ylzMedicalRelationDO.getMedicalType());//医疗类别
        data.put("detail_serial",ylzMedicalRelationDO.getDetailSerial());//医保明细流水号
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("invalidation_reason",remark);//作废原因
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        String result = requestYlz(data,funid,"医保费用明细上传冲销");
        if (result==null){
            throw new Exception("医保费用明细上传冲销失败！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            logger.info("医保费用明细上传冲销保存成功");
        }
        return result;
    }



    /**
     * 2.5.4医保费用明细上传冲销（N20.17.04.04）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String feeDetailRefundToEntrance(String registerNo,String remark) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"feeDetailRefund?registerNo="+registerNo+"&remark="+remark;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.5医保预结算服务（N20.17.04.05）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public YlzMedicalRelationDO preSettlement(String registerNo) throws Exception{
        String funid = "N20.17.04.05";
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("医保费用明细上传：结算信息为空！");
        }
        JSONObject data = new JSONObject();
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("cert_type",ylzMedicalRelationDO.getCertType());//证件类型
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("medical_type",ylzMedicalRelationDO.getMedicalType());//医疗类别
        data.put("his_bill_serial",ylzMedicalRelationDO.getHisBillSerial());//his收费单据流水号
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("settlement_sign",0);//结算标识
        data.put("date",DateUtil.dateToStrLong(ylzMedicalRelationDO.getDate()));//实际就诊日期
        data.put("leave_method","09");//离院方式
        data.put("pre_count",ylzMedicalRelationDO.getPreCount());//处方项目数
        data.put("total_amount",ylzMedicalRelationDO.getTotalAmount());//医疗费总金额
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        data.put("his_serial",ylzMedicalRelationDO.getHisSerial());//his流水号
        data.put("doctor_level",ylzMedicalRelationDO.getDoctorLevel());//医师诊查费等级
        data.put("trt_fee_level",ylzMedicalRelationDO.getDoctorLevel());//医师诊查费等级
        data.put("dept_code",ylzMedicalRelationDO.getDeptCode());//科室编码
        data.put("charge_qty",1);//本次收费次数

        String result = requestYlz(data,funid,"医保预结算服务");
        if (result==null){
            throw new Exception("医保预结算服务失败！");
        }

        return ylzMedicalRelationDO;
    }

    /**
     * 2.5.5医保预结算服务（N20.17.04.05）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public YlzMedicalRelationDO preSettlementToEntrance(String registerNo) throws Exception{
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("医保费用明细上传：结算信息为空！");
        }
        List<YlzMedicalIcdDO> icdDOList = ylzMedicailIcdDao.findByMedicalId(ylzMedicalRelationDO.getId());;
        if (icdDOList!=null){
            ylzMedicalRelationDO.setYlzMedicalIcdDOList(icdDOList);
        }
        List<YlzMedicalMxDO> mxDOList = ylzMedicailMxDao.findByMedicalId(ylzMedicalRelationDO.getId());;
        if (mxDOList!=null){
            ylzMedicalRelationDO.setYlzMedicalMxDOList(mxDOList);
        }
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"preSettlement?registerNo="+registerNo;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            if (jsonObject1.getString("flag").equalsIgnoreCase("1")){
                JSONObject encryptData = jsonObject1.getJSONObject("encrypt_data");
                String billSerial = encryptData.getString("bill_serial");
                ylzMedicalRelationDO.setInsuranceSerial(encryptData.getString("insurance_serial"));
                ylzMedicalRelationDO.setBillSerial(encryptData.getString("bill_serial"));
                ylzMedicalRelationDO.setHisBillSerial(encryptData.getString("his_bill_serial"));
                ylzMedicalRelationDO.setSexMc(encryptData.getString("sex_mc"));
                ylzMedicalRelationDO.setPersonCash(encryptData.getString("person_cash"));
                ylzMedicalRelationDO.setPersonAccount(encryptData.getString("person_account"));
                ylzMedicalRelationDO.setFundPrice(encryptData.getString("fund_price"));
                ylzMedicalRelationDO.setJkzhPay(encryptData.getString("jkzh_pay"));
                ylzMedicalRelationDO.setOwnPay(encryptData.getString("own_pay"));
                ylzMedicalRelationDO.setAccountBalance(encryptData.getString("account_balance"));
                ylzMedicalRelationDO.setHospitalizationQty(encryptData.getString("hospitalization_qty"));
                ylzMedicalRelationDO.setPayDate(DateUtil.strToDateLong(encryptData.getString("pay_date")));
                ylzMedicalRelationDO.setInvoiceJj(encryptData.getString("invoice_jj"));
                ylzMedicalRelationDO.setInvoiceXj(encryptData.getString("invoice_xj"));
                ylzMedicalRelationDO.setInvoiceZh(encryptData.getString("invoice_zh"));
                ylzMedicalRelationDO.setCreateTime(new Date());
                ylzMedicalRelationDO = ylzMedicailRelationDao.save(ylzMedicalRelationDO);
                JSONArray jsonArray = encryptData.getJSONArray("fplist");
                for (int i=0;i<jsonArray.size();i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    YlzMedicalBillDO ylzMb = new YlzMedicalBillDO();
                    ylzMb.setMedicalId(ylzMedicalRelationDO.getId());
                    ylzMb.setInvoicePay(jsonObject.getString("invoice_pay"));
                    ylzMb.setInvoiceType(jsonObject.getString("invoice_type"));
                    ylzMb.setInvoiceTypeName(jsonObject.getString("invoice_type_name"));
                    ylzMb.setProjectPay(jsonObject.getString("project_pay"));
                    ylzMb.setOwnPay(jsonObject.getString("own_pay"));
                    ylzMb.setSpecialPay(jsonObject.getString("special_pay"));
                    ylzMb.setUninsurancePay(jsonObject.getString("uninsurance_pay"));
                    ylzMb.setCreateTime(new Date());
                    ylzMedicailBillDao.save(ylzMb);
                }
                logger.info("医保预结算服务保存成功");
            }
        }else {
            return null;
        }
        return ylzMedicalRelationDO;
    }
    /**
     * 2.5.6医保结算冲销服务（N20.17.04.06）
     *
     * 返回值
     *
     * @param registerNo
     * @return
     * @throws Exception
     */
    public String preSettlementRefundToEntrance(String registerNo) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"feeDetailRefund?registerNo="+registerNo;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.6医保结算冲销服务（N20.17.04.06）
     *
     * 返回值
     *
     * @param registerNo
     * @return
     * @throws Exception
     */
    public String preSettlementRefund(String registerNo) throws Exception{
        String funid = "N20.17.04.06";
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("医保结算冲销上传：结算信息为空！");
        }
        JSONObject data = new JSONObject();
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("cert_type",ylzMedicalRelationDO.getCertType());//证件类型
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("bill_serial",ylzMedicalRelationDO.getBillSerial());//医保收费流水号
        data.put("his_bill_serial",ylzMedicalRelationDO.getHisSerial());//his收费单据流水号
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        data.put("refund_serial",ylzMedicalRelationDO.getHisSerial());//医院退费操作流水号
        String result = requestYlz(data,funid,"医保结算冲销服务");
        if (result==null){
            throw new Exception("医保结算冲销服务失败！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            logger.info("医保结算冲销服务保存成功");
        }
        return result;
    }

    /**
     * 2.5.7获取医保结算页面地址（N20.17.04.07）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String getSettlementResultUrl(String registerNo) throws Exception{
        String funid = "N20.17.04.07";
        JSONObject data = new JSONObject();
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(registerNo);
        if (ylzMedicalRelationDO==null){
            throw new Exception("获取医保结算页面地址：结算信息为空！");
        }
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("ResultRedirectUrl");
        if (wlyyHospitalSysDictDO==null){
            throw new Exception("获取医保结算页面地址失败：回调地址为空");
        }
        data.put("region_code",ylzMedicalRelationDO.getRegionCode());//参保地区划代码
        data.put("name",ylzMedicalRelationDO.getName());//姓名
        data.put("idcard",ylzMedicalRelationDO.getIdcard());//证件号码
        data.put("cert_type",ylzMedicalRelationDO.getCertType());//证件类型
        data.put("medical_mode",ylzMedicalRelationDO.getMedicalMode());//医疗就诊方式
        data.put("medical_type",ylzMedicalRelationDO.getMedicalType());//医疗类别
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//
        data.put("his_bill_serial",ylzMedicalRelationDO.getHisBillSerial());//his收费单据流水号
        data.put("date",ylzMedicalRelationDO.getDate());//实际就诊日期
        data.put("leave_method","09");//离院方式
        data.put("pre_count",ylzMedicalRelationDO.getPreCount());//处方项目数
        data.put("total_amount",ylzMedicalRelationDO.getTotalAmount());//医疗费总金额
        data.put("person_cash",ylzMedicalRelationDO.getPersonCash());//个人现金支付金额（实付现金）
        data.put("person_account",ylzMedicalRelationDO.getPersonAccount());//个人账户支付金额
        data.put("fund_price",ylzMedicalRelationDO.getFundPrice());//基金支付总额
        data.put("data_source",ylzMedicalRelationDO.getDataSource());//数据来源
        data.put("his_serial",ylzMedicalRelationDO.getHisSerial());//his流水号
        data.put("doctor_level",ylzMedicalRelationDO.getDoctorLevel());//医师诊查费等级
        data.put("redirect_url",wlyyHospitalSysDictDO.getDictValue());//回调地址
        String result = requestYlz(data,funid,"获取医保结算结果");
        if (result==null){
            throw new Exception("获取医保结算结果失败！");
        }
        return result;
    }


    /**
     * 2.5.7获取医保结算页面地址（N20.17.04.07）
     *
     * 返回值
     *
     * @param registerNo 挂号号
     * @return
     * @throws Exception
     */
    public String getSettlementResultUrlToEntrance(String registerNo) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"getSettlementResultUrl?registerNo="+registerNo;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.5.8获取医保结算结果（N20.17.04.08）
     *
     * 返回值
     *
     * @param code
     * @return
     * @throws Exception
     */
    public String getSettlementResult(String code) throws Exception{
        String funid = "N20.17.04.08";
        JSONObject data = new JSONObject();
        data.put("code",code);//参保地区划代码
        String result = requestYlz(data,funid,"获取医保结算结果");
        if (result==null){
            throw new Exception("获取医保结算结果失败！");
        }
        return result;
    }

    /**
     * 2.5.8获取医保结算结果（N20.17.04.08）
     *
     * 返回值
     *
     * @param code
     * @return
     * @throws Exception
     */
    public String getSettlementResultToEntrance(String code) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"getSettlementResultUrl?code="+code;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.7.1上传用户病史病情及医学报告（N20.17.06.01）
     *
     * 返回值
     *
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String uploadMedicalHistory(String outpatientId) throws Exception{
        String funid = "N20.17.06.01";
        JSONObject data = new JSONObject();
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
        if (wlyyOutpatientDO==null){
            throw new Exception("医保上传户病史病情及医学报告失败！门诊为空");
        }
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(wlyyOutpatientDO.getRegisterNo());
        if (ylzMedicalRelationDO==null){
            throw new Exception("获取医保结算页面地址：结算信息为空！");
        }
        data.put("region_code","350200");//参保地区划代码
        data.put("idcard",wlyyOutpatientDO.getId());//身份证号
        data.put("name",wlyyOutpatientDO.getPatientName());//姓名
        data.put("cert_type","01");//证件类型
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("blood_type",wlyyOutpatientDO.getBloodType());//血型
        data.put("allergy",wlyyOutpatientDO.getAllergy());//过敏史
        data.put("diagnosis",wlyyOutpatientDO.getIcd10Name());//病理诊断
        data.put("describe",wlyyOutpatientDO.getDescription());//病情描述
        data.put("difficult_cases","无");//疑难病例
        data.put("file_list_count",0);//医学报告附件数量
        data.put("data_source","53");//数据来源

        String result = requestYlz(data,funid,"上传用户病史病情及医学报告");
        if (result==null){
            throw new Exception("上传用户病史病情及医学报告失败！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object.getString("flag").equalsIgnoreCase("1")){
            JSONObject encryptData = object.getJSONObject("encrypt_data");
            wlyyOutpatientDO.setInsuranceMedHistserial(encryptData.getString("insurance_med_hist_serial"));
            logger.info("上传用户病史病情及医学报告保存成功");
        }
        return result;
    }


    /**
     * 2.7.1上传用户病史病情及医学报告（N20.17.06.01）
     *
     * 返回值
     *
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String uploadMedicalHistoryToEntrance(String outpatientId) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"uploadMedicalHistory?outpatientId="+outpatientId;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.7.2作废用户病史病情及医学报告（N20.17.06.06）
     *
     * 返回值
     *
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String refundMedicalHistory(String outpatientId,String remark) throws Exception{
        String funid = "N20.17.06.06";
        JSONObject data = new JSONObject();
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
        if (wlyyOutpatientDO==null){
            throw new Exception("医保上传户病史病情及医学报告失败！门诊为空");
        }
        YlzMedicalRelationDO ylzMedicalRelationDO = ylzMedicailRelationDao.findByOutpatient(wlyyOutpatientDO.getRegisterNo());
        if (ylzMedicalRelationDO==null){
            throw new Exception("获取医保结算页面地址：结算信息为空！");
        }
        data.put("insurance_serial",ylzMedicalRelationDO.getInsuranceSerial());//医保流水号
        data.put("insurance_med_hist_serial",wlyyOutpatientDO.getInsuranceMedHistserial());//医保病史上传流水号
        data.put("invalid_reason",remark);//作废原因
        data.put("data_source","53");//数据来源
        String result = requestYlz(data,funid,"作废用户病史病情及医学报告");
        if (result==null){
            throw new Exception("作废用户病史病情及医学报告失败！");
        }

        return result;
    }

    /**
     * 2.7.2作废用户病史病情及医学报告（N20.17.06.06）
     *
     * 返回值
     *
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String refundMedicalHistoryToEntrance(String outpatientId,String remark) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"refundMedicalHistory?outpatientId="+outpatientId+"&remark="+remark;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    /**
     * 2.7.3获取问诊过程数据（N20.17.06.02）
     *
     * 返回值
     *
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String uploadIcdProcess(String outpatientId) throws Exception{
        String funid = "N20.17.06.02";
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(outpatientId);
        if (wlyyOutpatientDO==null){
            throw new Exception("获取问诊过程数据失败！门诊为空");
        }
        BaseDoctorDO doctorDO = doctorDao.findById(wlyyOutpatientDO.getDoctor());
        if (doctorDO==null){
            throw new Exception("获取问诊过程数据失败！医生信息为空");
        }
        JSONObject data = new JSONObject();
        data.put("region_code","350200");//参保地区划代码
        data.put("idcard",wlyyOutpatientDO.getIdcard());//身份证号
        data.put("name",wlyyOutpatientDO.getPatientName());//姓名
        data.put("cert_type","01");//证件类型
        data.put("service_serial_id",wlyyOutpatientDO.getRegisterNo());//问诊流水号
        data.put("doctor_id_card",doctorDO.getIdcard());//医师身份证
        data.put("doctor_name",wlyyOutpatientDO.getDoctorName());//医师姓名
        /*data.put("file_list_count","");//附件总数
        data.put("filelist","");//附件列表
        data.put("file_bytes","");//二进制字节流
        data.put("file_name","");//文件名
        data.put("order_num",0);//顺序号*/

        String result = requestYlz(data,funid,"获取问诊过程数据");
        if (result==null){
            throw new Exception("获取问诊过程数据失败！");
        }
        return result;
    }

    /**
     * 2.7.3获取问诊过程数据（N20.17.06.02）
     *
     * 返回值
     *
     * @param outpatientId
     * @return
     * @throws Exception
     */
    public String uploadIcdProcessToEntrance(String outpatientId) throws Exception{
        String result = "";
        String response="";
        String url = entranceHealthCareUrl+"uploadIcdProcess?outpatientId="+outpatientId;
        response = httpClientUtil.get(url,"GBK");
        logger.info("response:"+response);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getInteger("status")==200){
            result = object.getString("obj");
        }
        return result;
    }

    public Boolean isHospitalFlag(){
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("medicalFlag");
        if (hospitalSysDictDO!=null){
            if (hospitalSysDictDO.getDictValue().equalsIgnoreCase("1")){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }
}
