
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Business.Core.SelfServiceMachine.ProcessScheduler;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Forms;
using PTMedicalInsurance.Forms.ElectronicSettlementCertificates;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;

namespace PTMedicalInsurance
{

    public class InsuBusiness : IInsuBusiness
    {
        //定义相关的变量
        //private Patients patient;
        //private Fees fee;
        //private Settlements settlement;

        //json对象属性
        private JObject joInParam;
        private JArray jaSession ;
        private JArray jaParams;
        private JObject joParam;
        private JObject joInterface;
        private JObject joInsuAdmObj;

        //设置业务实例
        CenterBusiness cBus = new CenterBusiness();
        HisMainBusiness hBus = new HisMainBusiness();
        HisIrisServices hIS = new HisIrisServices();
        MIIrisServices mIS= new MIIrisServices();
        InvokeHelper invoker = new InvokeHelper();
        //
        private string businessType;
        private string operationType;

        public InsuBusiness()
        {
            Global.curEvt.path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            ComputerInfo comp = new ComputerInfo();
            Global.curEvt.mac = comp.GetMAC();
            Global.curEvt.ip = comp.GetIP();
            Global.pat.insuplc_admdvs = "";        //如果是NULL中心会报错
        }

        private int parseInparam(string inParam,out string errMsg)
        {
            errMsg = "";
            try
            {
                joInParam = JObject.Parse(inParam);
                jaSession = JArray.Parse(JsonHelper.getDestValue(joInParam, "session"));
                Global.curEvt.jaSession = jaSession;
                jaParams = JArray.Parse(JsonHelper.getDestValue(joInParam, "params"));
                joParam = JObject.FromObject(jaParams[0]);

                if (JsonHelper.getDestValue(joInParam, "insuAdmObj") != "")
                    joInsuAdmObj = JObject.Parse(JsonHelper.getDestValue(joInParam, "insuAdmObj"));
                joInterface = JObject.Parse(JsonHelper.getDestValue(joInParam, "interfaceinfo"));

                businessType = JsonHelper.getDestValue(joInParam, "businessType");
                operationType = JsonHelper.getDestValue(joInParam, "operationType");
                Global.pat.businessType = businessType;
                if (businessType.Substring(0, 2) == "M6")
                {
                    string onlineYBFalg = JsonHelper.getDestValue(joInsuAdmObj, "onlineYBFalg");
                    if (String.IsNullOrEmpty(onlineYBFalg))
                        onlineYBFalg = "N";
                    if (onlineYBFalg == "Y")
                        Environment.CurrentDirectory = @"D:\HttpServerAPI\bin\libs"; ;
                }

                return 0;
            }
            catch (Exception e)
            {
                errMsg = "parseInparam 解析入参异常：" + e.Message;
                return -1;
            }
        }
        
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string Init(string InParam)
        {
            string errMsg, rtnResult ="";
            JObject joRtn = new JObject();
            try
            {
                if (hBus.initEnvironment(InParam, out errMsg) != 0)
                {   
                    return JsonHelper.setExceptionJson(-100, "initEnvironment 失败", errMsg).ToString();
                }
                else
                {
                    if (mIS.isSigned(ref Global.curEvt.signno) != true)
                    {
                        if ((businessType != "BasicData") && (businessType != "CloudImageUpload")) //如果是打开数据对照界面不调用初始化 
                        {
                            //签到
                            if (cBus.signIn(out joRtn) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "签到异常", (string)joRtn["err_msg"]).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                Global.curEvt.signno = JsonHelper.getDestValue(joRtn, "output.signinoutb.sign_no");

                                //插入签到表
                                if (mIS.saveSignRecord(Global.curEvt.signno, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setIrisReturnValue(0, "中心签到成功但插入签到表失败:" + errMsg, null).ToString();
                                }
                                else
                                {
                                    rtnResult = JsonHelper.setIrisReturnValue(0, "签到成功", joRtn).ToString();
                                }
                            }
                        }
                        else
                        {
                            Global.curEvt.signno = "ABC123";
                            rtnResult = JsonHelper.setIrisReturnValue(0, "初始化成功（医保对照不初始化）！", null).ToString();
                        }
                    }
                    else
                    {
                        rtnResult = JsonHelper.setIrisReturnValue(0, "初始化成功！", null).ToString();
                    }
                    return rtnResult;
                }
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-100, "Init 异常", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("初始化结果：" + rtnResult);
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="inParam"></param>
        /// <param name="outParam"></param>
        /// <returns></returns>
        private int init(string inParam, out string outParam)
        {
            string errMsg;
            outParam = "";
            try
            {
                //BS架构调用方式问题，每次调用都需要重新初始化
                JObject joInitRtn = JObject.Parse(Init(inParam));
                if (JsonHelper.parseIrisRtnValue(joInitRtn, out errMsg) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-100, "init(HIS医保环境初始化)", errMsg).ToString();
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outParam = JsonHelper.setExceptionJson(-100, "init(HIS医保环境初始化)异常", ex.Message).ToString();
                return -1;
            }
        }

        /// <summary>
        /// 获取患者信息
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string GetPatientInfo(string InParam)
        {
            Global.writeLog("GetPatientInfo入参:" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string  rtnResult = "",outParam;
            //BS架构调用方式问题，每次调用都需要重新初始化
            if (init(InParam,out outParam)!= 0)
            {
                rtnResult = outParam;
                return rtnResult;
            }
            JObject joInParam = JObject.Parse(InParam);
            string businessType = JsonHelper.getDestValue(joInParam,"businessType");

            try
            {
                switch (businessType)
                {
                    case "M1"://门诊读卡
                        {
                            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
                            if (hBus.readCard(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-100, "读卡失败！", outParam).ToString();
                            }
                            else if (string.IsNullOrEmpty(outParam))
                            {
                                // 点击取消或关闭
                                rtnResult = JsonHelper.setExceptionJson(-100, "读卡失败！", "读卡信息为空").ToString();
                            }
                            else
                            {
                                //if (Global.pat.ecToken != "")
                                //{ 
                                //    OneCodePay oneCodePay = new OneCodePay();
                                //    if (oneCodePay.QuerySignedPayStatus(out errMsg) !=0)
                                //    {
                                //        MessageBox.Show("查询一码付状态失败" + errMsg);
                                //    }
                                //}

                                //展示患者信息界面
                                if (hBus.showPatInfo(outParam, out outParam) != 0)
                                {
                                    rtnResult = outParam;
                                }
                                else
                                {
                                    rtnResult = JsonHelper.setIrisReturnValue(0, "", JObject.Parse(outParam)).ToString();
                                }
                            }
                            break;
                        }
                    case "Z1"://住院读卡
                        {
                            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
                            if (hBus.readCard(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-100, "读卡失败！", outParam).ToString();
                            }
                            else
                            {
                                string patInfo = outParam;

                                //if (Global.pat.ecToken != "")
                                //{ 
                                //    OneCodePay oneCodePay = new OneCodePay();
                                //    if (oneCodePay.QuerySignedPayStatus(out errMsg) !=0)
                                //    {
                                //        MessageBox.Show("查询一码付状态失败" + errMsg);
                                //    }
                                //}

                                //展示患者信息界面
                                if (hBus.showPatInfo(patInfo, out outParam) != 0)
                                {
                                    rtnResult = outParam;
                                }
                                else
                                {
                                    rtnResult = JsonHelper.setIrisReturnValue(0,"",JObject.Parse(outParam)).ToString();
                                }
                            }
                            break;
                        }     
                }
                return rtnResult;
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setIrisReturnValue(-1 , "GetPatientInfo发生异常;" + ex.Message,null).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("GetPatientInfo出参:" + JsonHelper.Compress(rtnResult));
            }
        }

        /// <summary>
        /// 登记
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string Register(string InParam)
        {
            Global.writeLog("Register 入参:" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;
            try
            {
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "", errMsg).ToString();
                    return rtnResult;
                }
                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out outParam) != 0)
                {
                    rtnResult = outParam;
                    return rtnResult;
                }
                //获取pat
                hBus.GetRegPatInfo(businessType, joInParam, out Global.pat);
                switch (businessType)
                {
                    case "M2"://门诊登记
                        {
                            string patInfo = "";
                            errMsg = showPatientInfo(out patInfo, out outParam);
                            if (!errMsg.Equals("0"))
                            {
                                return errMsg;
                            }


                            JObject reg = JObject.Parse(patInfo);

                            this.OutpatientReg(reg,patInfo);

                            break;
                        }
                    case "M2C"://门诊登记撤销
                        {
                            break;
                        }
                    case "Z0"://住院修改
                        {


                            break;
                        }
                    case "Z2"://入院登记
                        {
                            string  regInParam = "";
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }

                            if (hBus.checkName(Global.pat.name, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "姓名校验异常！", errMsg).ToString();
                                return rtnResult;
                            }
                            //显示登记面板
                            if (hBus.showInPatRegisterForm( out regInParam) == 0)
                            {

                                //#region【住院正式结算前调用验密】
                                //if (Global.pat.mdtrtcertType != "05")
                                //{
                                //    if (hBus.IdentityVerify(out errMsg) != 0)
                                //    {
                                //        rtnResult = JsonHelper.setExceptionJson(-1, "入院登记前验密失败", errMsg).ToString();
                                //        return rtnResult;
                                //    }
                                //}

                                //#endregion

                                JObject joRegIn_plain = JObject.Parse(JsonHelper.setCenterInpar_plain("2401", regInParam));
                                JObject joRegIn = JObject.Parse(JsonHelper.setCenterInpar("2401", regInParam));
                                //上传给中心
                                JObject joRegOut = invoker.invokeCenterService("2401", joRegIn);
                                //将中心返回的结果返回HIS,调用HIS服务进行保存
                                if (JsonHelper.parseCenterRtnValue(joRegOut,out errMsg) == 0)
                                {
                                    joRegOut.Add("validflag",1);
                                    joRegOut.Add("regstate", 1);
                                    joRegOut.Add("type", 1);
                                    Global.pat.mdtrtID = JsonHelper.getDestValue(joRegOut, "output.result.mdtrt_id");
                                    //插入患者本次就诊用的参保信息
                                    if (hBus.insertPatCurInsuInfo(JsonHelper.getDestValue(joParam, "patientInfo"), out outParam) != 0)
                                    {
                                        if (DialogResult.Yes == MessageBox.Show(outParam, " 是否继续？ ", MessageBoxButtons.YesNo))
                                        {

                                        }
                                        else
                                        {
                                            rtnResult = JsonHelper.setExceptionJson(-1, "插入患者本次就诊用的参保信息，请联系管理员！", outParam).ToString();
                                            return rtnResult;
                                        }
                                    }

                                    //插入医保平台
                                    if (mIS.saveInpatRegisterInfo(joRegIn_plain, joRegOut, out outParam) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "云平台保存登记信息", outParam).ToString();
                                        return rtnResult;
                                    }

                                    #region【插入全量信息表-自助机业务】
                                    JObject joOutput = new JObject();
                                    joOutput.Add("output", JObject.Parse(JsonHelper.getDestValue(joParam, "patientInfo.output")));
                                    //插入医保平台全量信息表
                                    if (mIS.saveMIPatFullInsuInfo(joOutput, out outParam) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "云平台保存登记全量信息失败", outParam).ToString();
                                        return rtnResult;
                                    }
                                    //插入费用核查表 入院登记
                                    if (mIS.saveDischargeAudit(3, 2, 0, joRegIn, out outParam) != 0)                                    
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "云平台保存费用核查入院登记信息", outParam).ToString();
                                        return rtnResult;
                                    }

                                    //插入费用核查表 出院登记 默认，具体需要最终审核
                                    JObject joDisReg = (JObject)joRegIn.DeepClone();
                                    //joDisReg["input"]["mdtrtinfo"]["psn_setlway"] = new JObject();
                                    joDisReg["input"]["mdtrtinfo"]["psn_setlway"] = "01";
                                    //joDisReg["input"]["mdtrtinfo"]["acct_used_flag"] = new JObject();
                                    joDisReg["input"]["mdtrtinfo"]["acct_used_flag"] = "1";
                                    //joDisReg["input"]["mdtrtinfo"]["mid_setl_flag"] = new JObject();
                                    joDisReg["input"]["mdtrtinfo"]["mid_setl_flag"] = "0";
                                    if (mIS.saveDischargeAudit(3, 3, 0, joDisReg, out outParam) != 0)                                    
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "云平台保存费用核查出院登记信息(默认)", outParam).ToString();
                                        return rtnResult;
                                    }
                                    #endregion

                                    //返回登记信息，插入HIS
                                    if (hIS.returnRegisterInfo(joRegIn_plain, joRegOut, out outParam) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "HIS平台保存登记信息", outParam).ToString();
                                        return rtnResult;
                                    }
                                    else
                                    {
                                        rtnResult = JsonHelper.setIrisReturnValue(0, "登记成功", null).ToString();
                                        return rtnResult;
                                    }
                                }
                                else
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "展示登记界面", errMsg).ToString();
                                    return rtnResult;
                                }
                            }
                            else
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "展示登记界面", regInParam).ToString();
                                return rtnResult;
                            }

                        }
                    case "Z2C"://入院登记取消
                        {
                            //从医保平台获取患者详细的医保登记信息
                            if (mIS.queryRegisterInfo(1, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "查询患者云平台登记信息", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joReg = JObject.Parse(outParam);
                            Global.pat.insuType = JsonHelper.getDestValue(joReg, "data.InsuType");
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }

                            //取消中心登记
                            if (cBus.cancleRegister("2404", out outParam) != 0)
                            {
                                //如果医保中心没有HIS所传的医保登记信息则默认撤销HIS登记信息
                                int i = outParam.IndexOf("不存在有效的就诊登记信息");
                                if (i != 0)
                                {
                                    if (DialogResult.Yes != MessageBox.Show("医保中心提示：" + outParam+ "，是否强制撤销HIS医保登记信息？", "提示", MessageBoxButtons.YesNo))
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "中心取消登记失败，", outParam).ToString();
                                        return rtnResult;
                                    }
                                }
                            }

                            //取消医保平台登记
                            if (mIS.cancleRegister(1, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "中心取消登记成功，但云医保平台取消失败，", outParam).ToString();
                                return rtnResult;
                            }

                            //取消HIS 登记
                            if (hIS.cancleRegister( out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "中心和云医保平台取消登记成功，但HIS取消失败，", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                //CM 20230602 删除医保平台医保费用明细上传表数据
                                mIS.deleteFee(out errMsg);
                                rtnResult = JsonHelper.setIrisReturnValue(0, "取消医保登记成功", null).ToString();
                                return rtnResult;
                            }

                        }
                    case "Z6"://出院登记
                        {



                            break;
                        }
                    case "Z6C"://出院登记取消
                        {
                            //从医保平台获取患者详细的医保登记信息
                            if (mIS.queryRegisterInfo(1, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "查询患者云平台登记信息", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joReg = JObject.Parse(outParam);
                            Global.pat.insuType = JsonHelper.getDestValue(joReg, "data.InsuType");
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }

                            if (cBus.cancleRegister("2405", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消出院登记", errMsg).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "取消出院登记成功", null).ToString();
                                return rtnResult;
                            }
}
                    default:
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "Register 交易", "传入的业务编码不对！").ToString();
                            return rtnResult;
                        }

                }
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setIrisReturnValue(-1, "Register 发生异常;" + ex.Message, null).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("Register 出参:" + JsonHelper.Compress(rtnResult));
            }


            return "";
        }

        /// <summary>
        /// 费用上传
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string FeeUpload(string InParam)
        {
            Global.writeLog("FeeUpload 入参:" +  JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;
            try
            {
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "", errMsg).ToString();
                    return rtnResult;
                }
                
                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out outParam) != 0)
                {
                    rtnResult = outParam;
                    return rtnResult;
                }
                //获取pat
                hBus.GetFeeHisInfo(businessType, joInParam, out Global.pat);
                hBus.getPreAndInProcessConfingure();
                switch (businessType)
                {
                    case "M3"://门诊费用上传
                        {
                            break;
                        }
                    case "M3C"://门诊费用撤销
                        {

                            break;
                        }
                    case "Z3"://入院费用上传
                        {
                            //从医保平台获取患者详细的医保登记信息
                            if (mIS.queryRegisterInfo(1, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "查询患者云平台登记信息", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joReg = JObject.Parse(outParam);
                            Global.pat.medType = JsonHelper.getDestValue(joReg, "data.MedicalType");
                            Global.pat.insuType = JsonHelper.getDestValue(joReg, "data.InsuType");
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }
                            //先取消中心费用传送
                            cBus.cancleFeeUpload("2302", out errMsg);
                            //再删除医保传送表的数据
                            mIS.deleteFee(out errMsg);

                            #region【住院费用上传前调用3101事前服务】
                            if (hBus.PreOrInprocessAnalysis("IPChargeRegistrationTrigScen", "3101", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, $"【3101】医保明细审核事中分析服务调用失败", errMsg).ToString();
                                return rtnResult;
                            }
                            #endregion

                            //费用上传
                            if (hBus.uploadFee("2301", 50, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "费用上传", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "住院费用上传成功", null).ToString();
                                return rtnResult;
                            }
                        }
                    case "Z3C"://住院费用上传取消
                        {
                            //从医保平台获取患者详细的医保登记信息
                            if (mIS.queryRegisterInfo(1, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "查询患者云平台登记信息", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joReg = JObject.Parse(outParam);
                            Global.pat.medType = JsonHelper.getDestValue(joReg, "data.MedicalType");
                            Global.pat.insuType = JsonHelper.getDestValue(joReg, "data.InsuType");
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }

                            if (cBus.cancleFeeUpload("2302", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消中心费用", errMsg).ToString();
                                return rtnResult;
                            }

                            if (mIS.deleteFee( out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "删除医保平台费用", errMsg).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "住院费用上传取消成功", null).ToString();
                                return rtnResult;
                            }

                        }

                    default:
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "FeeUpload 交易", "传入的业务编码不对！").ToString();
                            return rtnResult;
                        }
                }
                return rtnResult;
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-1, "FeeUpload 交易", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("FeeUpload 出参：" + JsonHelper.Compress(rtnResult));
            }

        }

        public JObject OutpatientReg(JObject joReg,string patInfo)
        {
           
            //医保挂号
            JObject jo2201Inpar = JObject.Parse(JsonHelper.getDestProperty(joReg, "data"));
            jo2201Inpar = JObject.Parse(JsonHelper.setCenterInpar("2201", jo2201Inpar));

            JObject jo2201Rtn = invoker.invokeCenterService("2201", jo2201Inpar);
            string errMsg = "";
            if (JsonHelper.parseCenterRtnValue(jo2201Rtn, out errMsg) != 0)
            {
                return  JsonHelper.setExceptionJson(-1, "医保挂号", errMsg);
            }
            else
            {
                Global.pat.mdtrtID = JsonHelper.getDestValue(jo2201Rtn, "output.data.mdtrt_id");
                string outParam = "";
                //插入患者本次就诊用的参保信息
                if (hBus.insertPatCurInsuInfo(patInfo, out outParam) != 0)
                {
                    if (DialogResult.Yes != MessageBox.Show(outParam, " 是否继续？ ", MessageBoxButtons.YesNo))
                    {
                       return JsonHelper.setExceptionJson(-1, "插入患者本次就诊用的参保信息，请联系管理员！是否继续？", outParam);
                    }
                }
            }
            return jo2201Rtn;
        }

        private string showPatientInfo(out string patInfo,out string outParam)
        {
            patInfo = "";
            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
            if (hBus.readCard(out outParam) != 0)
            {
                return JsonHelper.setExceptionJson(-100, "读卡失败！", outParam).ToString(); 
            }
            else
            {
                patInfo  = outParam;
                //展示患者信息界面
                if (hBus.showPatInfo(patInfo, out outParam) != 0)
                {
                    return JsonHelper.setExceptionJson(-100, "操作员取消！", outParam).ToString();
                }
            }
            
            //患者信息赋值给全局变量
            patInfo = outParam;

            string errMsg = "";
            if (hBus.setGlobalPatAfaterShowPatInfo(patInfo, out errMsg) != 0)
            {
                return  JsonHelper.setExceptionJson(-1, "setGlobalPatAfaterShowPatInfo", errMsg).ToString();
            }
            //校验HIS姓名与医保姓名是否一致
            if (hBus.checkName(Global.pat.name, out errMsg) != 0)
            {
                return  JsonHelper.setExceptionJson(-1, "校验HIS与医保姓名是否一致", errMsg).ToString();
            }

            //先登记
            if (hBus.showOutPatRegisterForm(out outParam) != 0)
            {
                return JsonHelper.setExceptionJson(-1, "显示登记面板", outParam).ToString();
            }
          
            return "0";
        }

        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string Settlement(string InParam)
        {
            Global.writeLog("Settlement 入参：" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;
            try
            {
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "", errMsg).ToString();
                    return rtnResult;
                }
                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out outParam) != 0)
                {
                    rtnResult = outParam;
                    return rtnResult; 
                }
                //获取pat
                hBus.GetSettlementHisInfo(businessType, joInParam, out Global.pat);
                hBus.getPreAndInProcessConfingure();
                switch (businessType)
                {
                    case "M4"://门诊预结算
                        {
                            // 没有做任何处理？是否必须？？？
                            //OutpatientRegistration frmReg = new OutpatientRegistration();
                            //if (frmReg.ShowDialog() == DialogResult.OK)
                            //{
                            //    rtnResult = "调用结束";
                            //}
                            break;
                        }
                    case "M4C"://门诊预结算撤销
                        {
                            break;
                        }
                    case "M5"://门诊结算
                        {                            
                            #region 读卡
                            string patInfo = "";
                            errMsg = showPatientInfo(out patInfo,out outParam);
                            if (!errMsg.Equals("0"))
                            {
                                return errMsg;
                            }
                            #endregion

                            #region 门诊挂号[2201]
                            JObject joReg = JObject.Parse(outParam);
                            JObject jo2201Inpar_plain = JObject.Parse(JsonHelper.getDestProperty(joReg, "data"));
                            jo2201Inpar_plain = JObject.Parse(JsonHelper.setCenterInpar("2201", jo2201Inpar_plain));
                            JObject jo2201Rtn = OutpatientReg(joReg, patInfo);
                            
                            //此处先取到就诊信息上传的入参，只要挂号成功就保存到云HIS后台（保存后台需要用到2203入参）
                            JObject jo2203Inpar = new JObject();
                            JObject jo2203Inpar_plain = new JObject();
                            jo2203Inpar.Add("mdtrtinfo", JObject.Parse(JsonHelper.getDestValue(joReg, "mdtrtinfo")));
                            jo2203Inpar.Add("diseinfo", JArray.Parse(JsonHelper.getDestValue(joReg, "diseinfo")));

                            jo2203Inpar["mdtrtinfo"]["mdtrt_id"] = Global.pat.mdtrtID;
                            jo2203Inpar_plain = JObject.Parse(JsonHelper.setCenterInpar_plain("2203", jo2203Inpar));
                            jo2203Inpar = JObject.Parse(JsonHelper.setCenterInpar("2203", jo2203Inpar));

                            //门诊登记信息，插入云医保平台
                            jo2201Rtn.Add("validflag", 1);
                            jo2201Rtn.Add("regstate", 1);
                            jo2201Rtn.Add("type", 3);

                            if (mIS.saveOutpatRegisterInfo(jo2201Inpar_plain, jo2201Rtn, jo2203Inpar_plain, out errMsg) != 0)
                            {
                                return JsonHelper.setExceptionJson(-1, "中心登记成功但医保平台保存失败，请联系管理员！", errMsg).ToString();
                            }
                            #endregion

                            #region 就诊信息上传[2203]/[2203A]
                            //门诊就诊信息上传                            
                            JObject jo2203Rtn = invoker.invokeCenterService("2203", jo2203Inpar );
                            if (JsonHelper.parseCenterRtnValue(jo2203Rtn, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "门诊就诊信息上传", errMsg).ToString();
                                return rtnResult;
                            }

                            #endregion

                            #region【门诊就诊信息上传成功后调用3101事前服务】
                            //1.门诊挂号 2.门诊收费登记 3.住院登记 4.住院收费登记 5.住院执行医嘱 6.门诊结算 7.门诊预结算 8.住院结算 9.住院预结算 10.购药划卡
                            if (hBus.PreOrInprocessAnalysis("OPChargeRegistrationTrigScen", "3101", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, $"【3101】医保明细审核事中分析服务调用失败", errMsg).ToString();
                                return rtnResult;
                            }
                            #endregion

                            #region 费用上传[2204]
                            if (hBus.uploadFee("2204", 50, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "费用上传", outParam).ToString();
                                return rtnResult;
                            }
                            #endregion                           

                            #region 门诊预结算[2206]
                            //调用IRIS获取医保各项金额
                            if (mIS.getSumFee(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "获取医保费用各项汇总金额", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joSumFee = JObject.Parse(outParam);
                            JObject joSettlement = JObject.Parse(JsonHelper.getDestValue(joReg, "settlement"));
                            //修改joSettlement的就诊ID ,总金额等
                            joSettlement["mdtrt_id"] = Global.pat.mdtrtID;
                            joSettlement["medfee_sumamt"] = JsonHelper.getDestValue(joSumFee, "data.Sumamt");

                            if ("RegisterOP".Equals(operationType))
                            {
                                // 门诊挂号（医疗类别）
                                joSettlement["med_type"] = "12";
                            }

                            #region【门诊预结算2206前调用3102医保明细审核事中服务】                            
                            if (hBus.PreOrInprocessAnalysis("OPPreSetTrigScen", "3102", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, $"【3102】医保明细审核事中分析服务调用失败", errMsg).ToString();
                                return rtnResult;
                            }
                            #endregion

                            //预结算2206
                            if (hBus.preSettlement_OutPat(joSettlement, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算信息展示", outParam).ToString();
                                return rtnResult;
                            }
                            #endregion


                            #region【门诊结算2207前调用3101医保明细审核事中服务】 
                            string trig_scen;
                            if (Global.operationType.Equals("RegisterOP"))
                            {
                                trig_scen = "OPRegTrigScen";
                            }
                            else
                            {
                                trig_scen = "OPSetTrigScen";
                            }
                            if (hBus.PreOrInprocessAnalysis(trig_scen, "3102", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, $"【3102】医保明细审核事中分析服务调用失败", errMsg).ToString();
                                return rtnResult;
                            }
                            
                            #endregion

                            #region 正式结算[2207]


                            JObject joData = new JObject();
                            joSettlement["mdtrt_cert_no"] = Global.pat.mdtrtcertNO;
                            joData.Add("data",joSettlement);
                            JObject joRtn = invoker.invokeCenterService("2207", JsonHelper.setCenterInpar("2207", joData));
                            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算失败", errMsg).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                Global.pat.admType = 1;
                                Global.pat.ExpContent = "";  //门诊不需要保存 外伤标志等相关扩展参数
                                //返回给云医保平台结算信息
                                if (mIS.saveSettlement(joRtn, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "结算成功，但云医保平台保存失败", errMsg).ToString();
                                    return rtnResult;
                                }
                                //返回给云医保平台结算明细信息
                                if (mIS.saveSettlementDetail(joRtn, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "云医保平台保存结算明细失败", errMsg).ToString();

                                    return rtnResult;
                                }
                                //返回给HIS
                                JObject joSetlinfo = JObject.Parse(JsonHelper.getDestValue(joRtn, "output.setlinfo"));
                                if (hIS.returnOutpatSettlementInfo(joSettlement, joSetlinfo, out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "返回结算信息给HIS", outParam).ToString();
                                    return rtnResult;
                                }
                                else
                                {
                                    JObject joHisServieRtn = JObject.Parse(outParam);
                                    hBus.returnToFrontEndAfterSettlement(joRtn, joHisServieRtn, out outParam);

                                    #region 一码付启用
                                    if (Global.pat.isOneCodePayEnabled)
                                    {
                                        OneCodePay oneCodePay = new OneCodePay();
                                        if (oneCodePay.GetCertAndSendToHis(Global.Set.psnCashAmt, out errMsg) != 0)
                                        {
                                            MessageBox.Show("一码付支付失败！如需要用一码付，请退费后重新结算!");
                                        }
                                        else
                                        {
                                            Global.writeLog($"一码付成功，返回给HIS{errMsg}");
                                            rtnResult = errMsg;
                                            return rtnResult;//已封装好，无需setIrisReturnValue
                                        }
                                    }
                                    #endregion

                                    rtnResult = JsonHelper.setIrisReturnValue(0, "结算成功", JObject.Parse(outParam)).ToString();
                                    return rtnResult;
                                }
                            }
                        #endregion

                        }
                    case "M5C"://门诊结算撤销
                        {
                            #region 查询结算信息

                            //查询HIS医保结算记录表获取该病人的参保地
                            string sqlStr = "SELECT * FROM  BS_MedInsuSettlement WHERE billType = 1 and ValidFlag = 1 ";
                            sqlStr = sqlStr + " AND Hospital_Dr=" + Global.inf.hospitalDr + " AND Interface_Dr=" + Global.inf.interfaceDr;
                            sqlStr = sqlStr + " AND SettlementID ='" + Global.pat.settlID + "'";

                            JObject joSql = new JObject();
                            joSql.Add("sqlStr", sqlStr);
                            JObject joSettlInfo = mIS.QuerySettlementInfo(joSql);
                            //if (JsonHelper.parseIrisRtnValue(joSettlInfo, out errMsg) != 0)
                            //{
                            //    rtnResult = JsonHelper.setExceptionJson(-1, "查询结算信息失败！", errMsg).ToString();
                            //    return rtnResult;
                            //}
                            Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joSettlInfo, "result.data[0].SpecialType");

                            if (JsonHelper.getDestValue(joSettlInfo, "result.data[0].SpecialType") == "GGS")
                            {
                                Global.pat.isWorkInjury = true;
                            }
                            #endregion

                            #region 门诊结算撤销 [2208]
                            string newSettleID = "";
                            if (cBus.cancleSettlement("2208", out outParam) != 0)
                            {
                                int i = outParam.IndexOf("获取到的就诊信息为无效状态，不能办理结算撤销业务");
                                if (i != 0)
                                {
                                    if (DialogResult.Yes != MessageBox.Show("医保中心提示：" + outParam + "，是否强制撤销HIS结算信息？", "提示", MessageBoxButtons.YesNo))
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "中心取消结算失败，", outParam).ToString();
                                        return rtnResult;
                                    }

                                    newSettleID = "YC";
                                }
                                else
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "取消中心结算", outParam).ToString();
                                    //查看是医保平台是否已经退费，如果是，则询问是否继续退费
                                    string SqlStr = " SELECT * FROM  BS_MedInsuSettlement WHERE  ValidFlag = 0 AND BillType = -1 ";
                                    SqlStr = SqlStr + " AND Hospital_Dr=" + Global.inf.hospitalDr + " AND Interface_Dr=" + Global.inf.interfaceDr;
                                    SqlStr = SqlStr + " AND SettlementID ='" + Global.pat.settlID + "'";

                                    JObject joSqlStr = new JObject();
                                    joSqlStr.Add("sqlStr", SqlStr);

                                    JObject joCancleSettlInfo = mIS.QuerySettlementInfo(joSqlStr);


                                    JArray jaCancleSettlInfo = JArray.Parse(JsonHelper.getDestValue(joCancleSettlInfo, "result.data"));
                                    if (jaCancleSettlInfo.Count == 1)
                                    {
                                        //询问收款员是否继续进行HIS退费
                                        if (DialogResult.Yes == MessageBox.Show("中心提示：" + outParam, " 该费用在医保中心已成功退费但在HIS未成功退费，是否强制退HIS费用？ ", MessageBoxButtons.YesNo))
                                        {
                                            rtnResult = JsonHelper.setExceptionJson(0, "该费用在医保中心已成功退费但在HIS未成功退费，收款员选择强制退HIS费用！", outParam).ToString();
                                        }
                                    }
                                    else
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "取消中心结算(云医保平台未退费或未查询到退费记录)", outParam).ToString();
                                    }

                                    return rtnResult;
                                }

                            }
                            else
                            {
                                newSettleID = JsonHelper.getDestValue(JObject.Parse(outParam), "output.setlinfo.setl_id");
                            }
                           

                            //退云医保平台结算
                            if (mIS.cancleSettlement(newSettleID, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消平台结算信息", outParam).ToString();
                                //return rtnResult;
                            }

                            #endregion

                            if (newSettleID != "YC")
                            {
                                #region 费用明细取消[2205]

                                //中心取消传送
                                if (cBus.cancleFeeUpload("2205", out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "取消中心费用", errMsg).ToString();
                                    return rtnResult;
                                }
                                //云平台取消传送
                                if (mIS.deleteFee(out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "删除医保平台费用", errMsg).ToString();
                                    return rtnResult;
                                }
                                #endregion

                                #region 取消挂号[2202]

                                //取消中心登记
                                if (cBus.cancleRegister("2202", out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心取消登记失败，", outParam).ToString();
                                    return rtnResult;
                                }
                                //取消医保平台登记
                                if (mIS.cancleRegister(3, out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心取消登记成功，但云医保平台取消失败，", outParam).ToString();
                                    return rtnResult;
                                }

                                #endregion
                            }

                            #region 退HIS结算
                            if (hIS.cancleSettlementInfo(joParam, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消HIS结算信息", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "取消结算成功", null).ToString();
                                return rtnResult;
                            }

                            #endregion
                        }
                    case "M6"://门诊移动支付结算
                        {
                            MobilePay mp = new MobilePay(InParam, out errMsg);
                            if (errMsg != "")
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", errMsg).ToString();
                                return rtnResult;
                            }
                            if (mp.MobilePaySettlement(out outParam) != 0)
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", outParam).ToString();
                            else
                                rtnResult = outParam;
                            return rtnResult;
                        }
                    case "M6C"://门诊移动支付结算撤销
                        {
                            string onlineYBFalg = JsonHelper.getDestValue(joInsuAdmObj, "onlineYBFalg");
                            MobilePay mp = new MobilePay(InParam, out errMsg);
                            if (errMsg != "")
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", errMsg).ToString();
                                return rtnResult;
                            }

                            if (String.IsNullOrEmpty(onlineYBFalg))
                                mp.MSettl.onlineYBFalg = "N";
                            else
                                mp.MSettl.onlineYBFalg = onlineYBFalg;

                            if (mp.MobilePayCancelSettlement(out outParam) != 0)
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", outParam).ToString();
                            else
                                rtnResult = JsonHelper.setExceptionJson(0, "Settlement 交易", outParam).ToString();
                            return rtnResult;
                        }
                    case "M6Confirm"://门诊移动支付确认
                        {
                            MobilePay mp = new MobilePay(InParam, out errMsg);
                            if (errMsg != "")
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", errMsg).ToString();
                                return rtnResult;
                            }
                            if (mp.MobilePayConfirmSettlement(out outParam) != 0)
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", outParam).ToString();
                            else
                                rtnResult = outParam;
                            return rtnResult;
                        }
                    case "M6CallBack"://门诊移动支付回调
                        {
                            JObject jo = JObject.Parse(InParam);
                            joInsuAdmObj = new JObject();
                            joInsuAdmObj.Add("payOrdId", "");
                            jo.Add("insuAdmObj",joInsuAdmObj);
                            MobilePay mp = new MobilePay(jo.ToString(), out errMsg);
                            if (errMsg != "")
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", errMsg).ToString();
                                return rtnResult;
                            }
                            if (mp.MobilePayCallbackSettlement(out outParam) != 0)
                                rtnResult = outParam;
                            else
                                rtnResult = outParam;
                            return rtnResult;
                        }
                    case "Z4"://住院预结算
                        {
                            #region 预结算（需先进行调用费用明细上传）

                            Global.pat.RYorCY = "2";
                            JObject joSettle = new JObject();                            
                            if (hBus.preSettlement("2303",out joSettle, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算信息展示", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "预结算成功", null).ToString();
                                return rtnResult;
                            }

                            #endregion
                        }
                    case "Z4C"://住院预结算撤销
                        {
                            rtnResult = JsonHelper.setExceptionJson(-100, "该接口不支持预结算取消！", null).ToString();
                            return rtnResult;
                        }
                    case "Z5"://住院结算
                        {
                            //从医保平台获取患者详细的医保登记信息
                            if (mIS.queryRegisterInfo(1, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "查询患者云平台登记信息", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joReg = JObject.Parse(outParam);
                            Global.pat.insuType = JsonHelper.getDestValue(joReg, "data.InsuType");
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }
                            

                            Global.pat.admType = 2;
                            Global.pat.RYorCY = "2";

                            JObject joPreSetOutpar ;
                            // 结算前先调用预结算？
                            if (hBus.preSettlement("2303",out joPreSetOutpar, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算信息展示", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {

                                #region 出院登记
                                JObject jo2402Inpar = JObject.Parse(JsonHelper.getDestValue(joPreSetOutpar, "DischargeRegister"));
                                JObject jo2402Rtn = invoker.invokeCenterService("2402", JsonHelper.setCenterInpar("2402", jo2402Inpar));

                                if (JsonHelper.parseCenterRtnValue(jo2402Rtn, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "预结算失败：出院登记失败", errMsg).ToString();
                                    return rtnResult;
                                }
                                #endregion

                                #region 住院结算之前调用3102
                                if (hBus.PreOrInprocessAnalysis("IPPreSetTrigScen", "3102", out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, $"【3102】医保明细审核事中分析服务调用失败", errMsg).ToString();
                                    return rtnResult;
                                }
                                #endregion

                                #region 正式出院结算
                                JObject joSettlement =  JObject.Parse(JsonHelper.getDestValue(joPreSetOutpar, "Settlement"));
                                joSettlement["mdtrt_cert_no"] = Global.pat.mdtrtcertNO;
                                JObject joSettl = new JObject();
                                joSettl.Add("data", joSettlement);
                                JObject jo2304Rtn = invoker.invokeCenterService("2304",JsonHelper.setCenterInpar("2304", joSettl));
                                if (JsonHelper.parseCenterRtnValue(jo2304Rtn, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "结算失败", errMsg).ToString();
                                    cBus.cancleRegister("2405", out errMsg);
                                    return rtnResult;
                                }
                                else
                                {
                                    Global.pat.admType = 2;
                                    //返回给云医保平台结算信息
                                    if (mIS.saveSettlement(jo2304Rtn, out errMsg) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "结算成功，但云医保平台保存失败", errMsg).ToString();
                                        return rtnResult;
                                    }
                                    //返回给云医保平台结算明细信息
                                    if (mIS.saveSettlementDetail(jo2304Rtn, out errMsg) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "云医保平台保存结算明细失败", errMsg).ToString();
                                        Global.writeLog(rtnResult);
                                        MessageBox.Show(errMsg);
                                    }
                                    //返回给HIS
                                    JObject joSetlinfo = JObject.Parse(JsonHelper.getDestValue(jo2304Rtn, "output.setlinfo"));
                                    if (hIS.returnInpatSettlementInfo(joParam, joSetlinfo, out outParam) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "返回结算信息给HIS", outParam).ToString();
                                        return rtnResult;
                                    }
                                    else
                                    {
                                        //返回给前端
                                        JObject joHisServieRtn = JObject.Parse(outParam);
                                        hBus.returnToFrontEndAfterSettlement(jo2304Rtn, joHisServieRtn, out outParam);
                                        rtnResult = JsonHelper.setIrisReturnValue(0, "结算成功", JObject.Parse(outParam)).ToString();
                                        return rtnResult;
                                    }
                                }
                                #endregion

                            }

                        }
                    case "Z5C"://住院结算撤销
                        {
                            //查询结算表
                            string sqlStr = "SELECT * FROM  BS_MedInsuSettlement WHERE billType = 1 and Hospital_Dr=" + Global.inf.hospitalDr
                                          + " and Adm_Dr='" + Global.pat.adm_Dr + "'"
                                          + " and MdtrtID='" + Global.pat.mdtrtID + "'"
                                          + " Order By ID DESC ";

                            JObject joSql = new JObject();
                            joSql.Add("sqlStr", sqlStr);
                            JObject joSettlInfo = mIS.QuerySettlementInfo(joSql);
                            //if (JsonHelper.parseIrisRtnValue(joSettlInfo, out errMsg) != 0)
                            //{
                            //    rtnResult = JsonHelper.setExceptionJson(-1, "查询结算信息失败！", errMsg).ToString();
                            //    return rtnResult;
                            //}

                            //MessageBox.Show(joSettlInfo.ToString());

                            Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joSettlInfo, "result.data[0].insuplc_admdvs");
                            Global.pat.insuType = JsonHelper.getDestValue(joSettlInfo, "result.data[0].InsuranceType");
                            if (Global.pat.insuType == "410")
                            {
                                Global.pat.isWorkInjury = true;
                            }
                            Global.pat.SettID_YBJSB = JsonHelper.getDestValue(joSettlInfo, "result.data[0].SettlementID");

                            if (Global.pat.settlID != Global.pat.SettID_YBJSB)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", "通过09010059服务获取到的SettlementID<" + Global.pat.settlID + ">与DLL通过SQL语句" +
                                                                            joSql + ",获取到的SettlementID<" + Global.pat.SettID_YBJSB + ">不同,可能存在HIS单边账,请联系医保开发人员处理该笔结算记录！").ToString();
                                //return rtnResult;
                            }

                            Global.pat.settlID = Global.pat.SettID_YBJSB;

                            //取消中心结算信息
                            if (cBus.cancleSettlement("2305", out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消中心结算信息失败！", outParam).ToString();

                                //查看是医保平台是否已经退费，如果是，则询问是否继续退费
                                string SqlStr = " SELECT * FROM  BS_MedInsuSettlement WHERE  ValidFlag = 0 AND BillType = -1 ";
                                SqlStr = SqlStr + " AND Hospital_Dr=" + Global.inf.hospitalDr + " AND Interface_Dr=" + Global.inf.interfaceDr;
                                SqlStr = SqlStr + " AND SettlementID ='" + Global.pat.settlID + "'";

                                JObject joSqlStr = new JObject();
                                joSqlStr.Add("sqlStr", SqlStr);

                                JObject joCancleSettlInfo = mIS.QuerySettlementInfo(joSqlStr);
                                JArray jaCancleSettlInfo = JArray.Parse(JsonHelper.getDestValue(joCancleSettlInfo, "result.data"));
                                if (jaCancleSettlInfo.Count == 1)
                                {
                                    //询问收款员是否继续进行HIS退费
                                    if (DialogResult.Yes == MessageBox.Show("中心提示：" + outParam, " 该费用在医保中心已成功退费但在HIS未成功退费，是否强制退HIS费用？ ", MessageBoxButtons.YesNo))
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(0, "该费用在医保中心已成功退费但在HIS未成功退费，收款员选择强制退HIS费用！", outParam).ToString();
                                    }
                                }
                                else
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "取消中心结算(云医保平台未退费或未查询到退费记录)", outParam).ToString();
                                }

                                return rtnResult;
                            }
                            else
                            {
                                //退结算会返一个新的ID
                                string newSettleID = JsonHelper.getDestValue(JObject.Parse(outParam), "output.setlinfo.setl_id");
                                //取消平台结算信息
                                if (mIS.cancleSettlement(newSettleID, out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心结算取消成功，医保平台结算信息取消失败！", outParam).ToString();
                                    return rtnResult;
                                }

                                //取消出院登记
                                if (cBus.cancleRegister("2405", out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(0, "中心，医保平台及HIS结算信息取消成功，取消出院登记失败！请手工取消出院登记！", outParam).ToString();
                                    return rtnResult;
                                }


                                //中心取消传送
                                if (cBus.cancleFeeUpload("2302", out errMsg) != 0)
                                {
                                    //rtnResult = JsonHelper.setExceptionJson(-1, "取消中心费用", errMsg).ToString();
                                    //return rtnResult;
                                }
                                //云平台取消传送
                                if (mIS.deleteFee(out errMsg) != 0)
                                {
                                    //rtnResult = JsonHelper.setExceptionJson(-1, "删除医保平台费用", errMsg).ToString();
                                    //return rtnResult;
                                }

                                //取消HIS医保结算信息
                                if (hIS.cancleSettlementInfo(joParam, out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心跟医保平台结算取消成功， 取消HIS结算信息失败！", outParam).ToString();
                                    return rtnResult;
                                }
                                

                                rtnResult = JsonHelper.setIrisReturnValue(0, "取消结算成功", null).ToString();
                                return rtnResult;
                            }
                        }
                    default:
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", "传入的业务编码不对！").ToString();
                            return rtnResult;
                        }
                }
                return rtnResult;
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("Settlement 出参：" + JsonHelper.Compress(rtnResult));
            }
        }

        //[STAThread]
        //public void print(JObject joInParam)
        //{
        //    //显示打印界面
        //    SettlementChecklist frmSettlList;
        //    string insuAdmObj = JsonHelper.getDestValue(joInParam, "insuAdmObj");
        //    if (insuAdmObj == "")
        //    {
        //        frmSettlList = new SettlementChecklist();
        //    }
        //    else
        //    {
        //        JObject joInsuAdmObj = JObject.Parse(insuAdmObj);
        //        frmSettlList = new SettlementChecklist(joInsuAdmObj);
        //    }
        //    if (frmSettlList.ShowDialog() == DialogResult.OK)
        //    {

        //    };
        //}
        //[STAThread]

        /// <summary>
        /// 辅助交易
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string AgentFun(string InParam)
        {
            Global.writeLog("AgentFun 入参:" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;
            try
            {
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "", errMsg).ToString();
                    return rtnResult;
                }
                
                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out outParam) != 0)
                {
                    Global.writeLog("初始化异常:"+outParam);
                    rtnResult = outParam;
                    // 基础数据没有初始化成功，也可以运行
                    if (!businessType.Equals("BasicData")) {
                        return rtnResult;
                    }
                    
                }
                //获取pat
                hBus.GetAgentFunHisInfo(businessType, joInParam, out Global.pat);
                switch (businessType)
                {
                    case "BasicData"://基础数据维护
                        {
                            STA sta = new STA();
                            Thread thread = new Thread(sta.BasicData);
                            thread.SetApartmentState(ApartmentState.STA); //重点
                            thread.IsBackground = true;
                            thread.Start();
                            thread.Join();
                            break;
                        }
                    case "Exception"://异常处理
                        {
                            STA sta = new STA();
                            Thread thread = new Thread(sta.Exception);
                            thread.SetApartmentState(ApartmentState.STA); //重点
                            thread.IsBackground = true;
                            thread.Start();
                            thread.Join();
                            break;
                        }
                    case "CheckAndClearing"://对账清算
                        {
                            STA sta = new STA();
                            Thread thread = new Thread(sta.CheckAndClearing);
                            thread.SetApartmentState(ApartmentState.STA); //重点
                            thread.IsBackground = true;
                            thread.Start();
                            thread.Join();
                            break;
                        }
                    case "PrescribeCirculation"://处方流转
                        {
                            STA sta = new STA();
                            Thread thread = new Thread(sta.PrescribeCirculation);
                            thread.SetApartmentState(ApartmentState.STA); //重点
                            thread.IsBackground = true;
                            thread.Start();
                            thread.Join();
                            break;
                        }
                    case "Print"://打印
                        {
                            try
                            {
                                //显示打印界面
                                SettlementChecklist frmSettlList;
                                string insuAdmObj = JsonHelper.getDestValue(joInParam, "insuAdmObj");
                                if (insuAdmObj == "")
                                {
                                    frmSettlList = new SettlementChecklist();
                                    frmSettlList.ShowDialog();
                                }
                                else
                                {
                                    JObject joInsuAdmObj = JObject.Parse(insuAdmObj);
                                    frmSettlList = new SettlementChecklist(joInsuAdmObj);

                                    string groupID = JsonHelper.getDestValue((JObject)Global.curEvt.jaSession[0], "groupID");
                                    DataTable dt = (DataTable)frmSettlList.dgvSettlRecord.DataSource;

                                    if (dt.Rows.Count != 1)
                                    {
                                        frmSettlList.ShowDialog();
                                    }
                                    else
                                    {
                                        frmSettlList.btnPrint_Click(null, null);
                                    }
                                }

                                return JsonHelper.setIrisReturnValue(0, "", null).ToString();

                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            break;
                        }
                    case "Log"://日志
                        {
                            MessageBox.Show(businessType);

                            break;
                        }
                    case "RecordUpload"://上传记录
                        {
                            MessageBox.Show(businessType);
                            break;
                        }
                    case "HospitalRegister"://备案
                        {
                            HospitalRegister Referral = new HospitalRegister();
                            if (Referral.ShowDialog() != DialogResult.OK)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-100, "", "已退出备案信息界面").ToString();
                                return rtnResult;
                            }
                            break;
                        }
                    case "PreAndInProcessAnalysis"://事前分析  诊间只有住院的事前分析
                        {
                            Global.pat.adm_Dr = int.Parse(JsonHelper.getDestValue(joInParam, "params[0].admID"));
                            JObject joResult = new JObject();

                            joResult.Add("result", JObject.Parse(JsonHelper.getDestValue(joParam, "insuData")));
                            //事前分析
                            if (Global.curEvt.ext.isOpenAnalysis)
                            {
                                if (hBus.PreAnalysis("5", joResult.ToString(), out errMsg) != 0)
                                {
                                    MessageBox.Show(errMsg);
                                    break;
                                }
                            }

                            break;
                        }
                    case "PreAndInProcessAnalysisNew"://事前分析  诊间只有住院的事前分析
                        {
                            if (!Global.curEvt.ext.isOpenAnalysis)
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(-1, "事前事中服务接口未开启", null).ToString();
                                break;
                            }

                            Global.pat.adm_Dr = int.Parse(JsonHelper.getDestValue(joInParam, "params[0].admID"));
                            Global.pat.mdtrtID = JsonHelper.getDestValue(joInParam, "insuAdmObj.mdtrt_id");
                            Global.pat.psn_no = JsonHelper.getDestValue(joInParam, "insuAdmObj.psn_no");
                            Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joInParam, "params[0].insuData.patient_dtos[0].poolarea");
                            Global.pat.insuType = JsonHelper.getDestValue(joInParam, "params[0].insuData.patient_dtos[0].fsi_encounter_dtos[0].insutype");
                            //Global.pat.medType = JsonHelper.getDestValue(joInParam, "params[0].insuData.patient_dtos[0].fsi_encounter_dtos[0].med_type");

                            JObject joResult = new JObject();
                            joResult.Add("result", JObject.Parse(JsonHelper.getDestValue(joParam, "insuData")));

                            //场景
                            string scen = JsonHelper.getDestValue(joInsuAdmObj, "scen");

                            List<int> admTypeArr = new List<int>();
                            string trig_scen = "";

                            hBus.getPreAndInProcessConfingure();
                            if (scen == "门诊医嘱保存")
                            {
                                admTypeArr = new List<int> { 3, 4 };
                                trig_scen = Global.pat.preAndInPro.OPOrderTrigScen;
                                Global.pat.medType = Global.pat.preAndInPro.OPMedType;
                            }
                            else
                            {
                                admTypeArr = new List<int> { 1, 2 };
                                trig_scen = Global.pat.preAndInPro.IPOrderTrigScen;
                                Global.pat.medType = Global.pat.preAndInPro.IPMedType;
                            }
                            //查询患者的医保登记信息
                            if (String.IsNullOrEmpty(Global.pat.mdtrtID))
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(-1, "未获取到患者的医保就诊ID.请检查该患者是否已经进行了医保登记！", null).ToString();
                                break;
                            }

                            if (mIS.queryRegisterInfo(admTypeArr, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "查询医保登记信息！", errMsg).ToString();
                                break;
                            }
                            JObject joReg = JObject.Parse(errMsg);

                            if ((JsonHelper.getDestValue(joReg, "data") == "") || (JsonHelper.getDestValue(joReg, "data") == "{}"))
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(-1, "查询医保登记信息返回值为空！", null).ToString();
                                break;
                            }
                            Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joReg, "data.InsuranceAreaCode");



                            PreAndInProcessAnalysis preAnalysis = new PreAndInProcessAnalysis(joResult.ToString());
                            if (preAnalysis.setPatientByHisBaseInfo(out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(-1, "医生站事前服务" + errMsg, null).ToString();
                                break;
                            }

                            JObject jo3101Out = new JObject();
                            if (preAnalysis.Get3101Inpar(trig_scen, Global.pat, out jo3101Out, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(-1, "获取3101入参" + errMsg, null).ToString();
                                break;
                            }

                            JObject joRtn = invoker.invokeCenterService("3101", JsonHelper.setCenterInpar("3101",jo3101Out));


                            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(-1, "医生站事前服务" + errMsg, null).ToString();
                                break;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "医生站事前服务" + errMsg, joRtn).ToString();
                            }
                            break;
                        }
                    case "CenterQuery"://中心查询
                        {
                            STA sta = new STA();
                            Thread thread = new Thread(sta.CenterQuery);
                            thread.SetApartmentState(ApartmentState.STA); //重点
                            thread.IsBackground = true;
                            thread.Start();
                            thread.Join();
                            break;
                        }
                    case "ElectronicSettlementCertificate":// 电子结算凭证上传
                        {
                            EcSettlCertMainForm ecCert = new EcSettlCertMainForm();
                            ecCert.ShowDialog();
                            break;
                        }
                    case "CloudImageUpload":// 云影像（个人医保云影像云）数据采集
                        {
                            // 从入参中获取交易编号和input数据
                            string cloudInfno = JsonHelper.getDestValue(joInParam, "funNO");
                            if (string.IsNullOrEmpty(cloudInfno))
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "CloudImageUpload", "缺少funNO参数").ToString();
                                return rtnResult;
                            }

                            // 获取HIS传入的input入参
                            JObject cloudInput = new JObject();
                            string input = JsonHelper.getDestValue(joParam, "insuData");
                            if (string.IsNullOrEmpty(input))
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "CloudImageUpload", "insuData为空").ToString();
                                return rtnResult;
                            }
                            cloudInput = JObject.Parse(input);
                            string rcd_num = JsonHelper.getDestValue(cloudInput, "rcd_num");
                            if (string.IsNullOrEmpty(rcd_num))
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "CloudImageUpload", "insuData.rcd_num为空").ToString();
                                return rtnResult;
                            }
                            if (!int.TryParse(rcd_num, out int s))
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "CloudImageUpload", "insuData.rcd_num不是有效整数").ToString();
                                return rtnResult;
                            }
                            //cloudInput.Remove("rcd_num");
                            //if (!cloudInput.HasValues)
                            //{
                            //    rtnResult = JsonHelper.setExceptionJson(-1, "CloudImageUpload", "insuData仅包含rcd_num,未包含具体入参").ToString();
                            //    return rtnResult;
                            //}

                            // 创建云影像服务实例并执行交易
                            CloudImageService cloudService = new CloudImageService();
                            cloudService.SetAPIKey(Global.inf.cloudImage.apiKey);
                            cloudService.SetCollectServerUrl(Global.inf.cloudImage.collectServerUrl);
                            cloudService.SetMedPreServerUrl(Global.inf.cloudImage.medPreServerUrl);
                            cloudService.SetFixmedinsCode(Global.inf.hospitalNO);
                            JObject joCloudRtn = cloudService.Execute(cloudInfno, cloudInput);

                            // 解析返回结果
                            string cloudErrMsg;
                            if (JsonHelper.parseIrisRtnValue(joCloudRtn, out cloudErrMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "云影像接口调用失败", cloudErrMsg).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "云影像接口调用成功", joCloudRtn).ToString();
                                return rtnResult;
                            }
                        }
                    default:
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "AgentFun 交易", "传入的业务编码不对！").ToString();
                            return rtnResult;
                        }
                }
                return rtnResult;
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-1, "AgentFun 交易", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("AgentFun 出参：" + JsonHelper.Compress(rtnResult));
            }

        }

        public string Download(string InParam)
        {
            Global.writeLog("Download 入参:" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;

            try
            {
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "", errMsg).ToString();
                    return rtnResult;
                }

                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out outParam) != 0)
                {
                    rtnResult = outParam;
                    return rtnResult;
                }

                dynamic joData = new JObject();

                joData.data = joParam["data"];
                //string code = (string)joInParam["code"];
                string funNO = (string)joParam["funNO"];
                switch (businessType)
                {

                    case "DirectoryDownload":
                        {
                            string downloadParam = JsonHelper.setCenterInpar(funNO, joData.ToString());
                            rtnResult = hBus.DownloadDirectory(funNO, downloadParam).ToString();
                            break;
                        }
                    case "DictionayDownload":
                        {
                            string downloadParam = JsonHelper.setCenterInpar(funNO, joData.ToString());
                            rtnResult = hBus.downDictionary(downloadParam);
                            break;
                        }
                }
                return rtnResult;

            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-100, "Download", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("Download 出参：" +  rtnResult);
            }


        }
        
        public string PlatformDirectConnect(string InParam)
        {            
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;
            try
            {
                Global.writeLog("PlatformDirectConnect 入参:" + JsonHelper.Compress(InParam));
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "", errMsg).ToString();
                    return rtnResult;
                }

                Global.businessType = businessType;
                string funNO = JsonHelper.getDestValue(joInParam, "funNO");
                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out outParam) != 0)
                {
                    rtnResult = outParam;
                    return rtnResult;
                }

                if (funNO=="4101Y")
                    Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joInParam, "insuplc_admdvs");

                Global.writeLog("1");

                if (funNO == "3602")
                {
                    Clearing frm = new Clearing();
                   
                    //先进行9101文件上传
                    string finalAchPath = JsonHelper.getDestValue(joParam, "data.filePath");
                    Global.writeLog($"finalAchPath:{finalAchPath}");
                    //检测文件大小
                    // 创建一个 FileInfo 对象
                    FileInfo fileInfo = new FileInfo(finalAchPath);

                    // 检查文件是否存在
                    if (fileInfo.Exists)
                    {
                        // 获取文件大小（以字节为单位）
                        long fileSizeInBytes = fileInfo.Length;

                        Global.writeLog("文件大小为: " + fileSizeInBytes + " 字节");

                        //long maxUploadSize = 10 * 1024 * 1024;//不能超过30M 否则溢出
                        //if (fileSizeInBytes > maxUploadSize)
                        //{
                        //    rtnResult = JsonHelper.setExceptionJson(-1, $"平台直连错误:【9101】文件上传失败！文件过大，请检查！", outParam).ToString();

                        //    return rtnResult;
                        //}
                    }
                    else
                    {
                        rtnResult = JsonHelper.setExceptionJson(-1, $"平台直连错误:【9101】文件上传失败！{finalAchPath}文件不存在", outParam).ToString();

                        return rtnResult;
                    }


                    string file_qury_no = "";
                    JObject joTmp = new JObject();

                    //byte[] zipBytes = File.ReadAllBytes(finalAchPath);
                    //string base64String = Convert.ToBase64String(zipBytes);



                    //var sb = new StringBuilder();
                    //using (var writer = new StringWriter(sb))
                    //{
                    //    Base64StreamingEncoder.ConvertToBase64Stream(finalAchPath, writer);
                    //}
                    //string base64String = sb.ToString(); // 仍可能 OOM，慎用于大文件！


                    //joTmp.Add("in", base64String);
                    //joTmp.Add("filename", Path.GetFileName(finalAchPath));
                    //joTmp.Add("fixmedins_code", Global.inf.hospitalNO);
                    //JObject joFsUploadIn = new JObject();
                    //joFsUploadIn.Add("fsUploadIn", joTmp);
                    //InvokeHelper invoker = new InvokeHelper();
                    //JObject jo9101Rtn = invoker.invokeCenterService("9101", JsonHelper.setCenterInpar("9101", joFsUploadIn.ToString()));
                    //if (JsonHelper.parseCenterReturnJson(jo9101Rtn, out outParam) != 0)
                    //{
                    //    rtnResult = JsonHelper.setExceptionJson(-1, "平台直连错误:【9101】文件上传失败", outParam).ToString();

                    //    return rtnResult;
                    //}
                    //else
                    //{
                    //    file_qury_no = JsonHelper.getDestValue(jo9101Rtn, "output.file_qury_no");
                    //}

                    string result = "";
                    if (invoker.UploadFileAsJsonStream(finalAchPath, Path.GetFileName(finalAchPath), ref result, ref errMsg) != 0)
                    {
                        rtnResult = JsonHelper.setExceptionJson(-1, "9101上传测试", errMsg).ToString();
                        return rtnResult;
                    }
                    else
                    {
                        JObject jo9101Rtn = JObject.Parse(result);
                        Global.writeLog("9101Rtn:" + jo9101Rtn.ToString());
                        if (JsonHelper.parseCenterReturnJson(jo9101Rtn, out outParam) != 0)
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "平台直连错误:【9101】文件上传失败", outParam).ToString();

                            return rtnResult;
                        }
                        else
                        {
                            file_qury_no = JsonHelper.getDestValue(jo9101Rtn, "output.file_qury_no");
                        }


                    }


                    if (!((JObject)joParam["data"]).ContainsKey("exp_content"))
                    {
                        rtnResult = JsonHelper.setExceptionJson(-1, "平台直连错误", "3602交易入参必须包含exp_content节点").ToString();
                        return rtnResult;
                    }
                    JObject joExp = JObject.Parse(JsonHelper.getDestValue(joParam, "data.exp_content"));
                    if (joExp.ContainsKey("file_qury_no"))
                    {
                        joExp["file_qury_no"] = file_qury_no;
                    }
                    else
                    {
                        joExp.Add("file_qury_no", file_qury_no);
                    }
                        
                    joParam["data"]["exp_content"] = JsonConvert.SerializeObject(joExp);
                }


                JObject joRtn = invoker.invokeCenterService(funNO, JsonHelper.setCenterInpar(funNO, joParam));
                if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "平台直连错误", errMsg).ToString();
                    return rtnResult;
                }
                else
                {
                    rtnResult = JsonHelper.setIrisReturnValue(0, "", joRtn).ToString();
                    return rtnResult;
                }
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-1, "PlatformDirectConnect 交易", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("PlatformDirectConnect 出参：" + JsonHelper.Compress(rtnResult));
            }
        }

        /// <summary>
        /// 自助机
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string SelfServiceMachine(string InParam)
        {
            Global.writeLog("SelfServiceMachine 入参：" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            string errMsg, rtnResult = "", outParam;
            try
            {
                //解析入参
                if (parseInparam(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "parseInparam", errMsg).ToString();
                    return rtnResult;
                }
                //获取pat
                hBus.GetSelfServiceMachineInfo(businessType, joInParam, out Global.pat);
                //BS架构调用方式问题，每次调用都需要重新初始化
                if (init(InParam, out errMsg) != 0)
                //if (hBus.InitA(InParam, out errMsg) != 0)
                {
                    rtnResult = JsonHelper.setExceptionJson(-1, "InitA", errMsg).ToString(); ;
                    return rtnResult;
                }
                else
                {
                    //joInParam.Add("patInfo", errMsg);
                    Global.writeLog($"InitA初始化成功！");
                }

                switch (businessType)
                {
                    case "GetPatientInfo"://读取患者信息，该节点无需重定向
                        {
                            Business.Core.SelfServiceMachine.PatientService patientService = new Business.Core.SelfServiceMachine.PatientService();
                            rtnResult = patientService.GetPatientInfo();
                            break;      
                        }
                    case "OPReg"://门诊挂号
                        {                
                            #region 【链条式任务调度者】
                            OPRegService service = new OPRegService();
                            rtnResult = service.Charge(operationType, joInParam);
                            break;
                            #endregion
                        }
                    case "OPSettl"://门诊结算
                        {
                            OPSettlementService service = new OPSettlementService();
                            rtnResult = service.Charge(operationType, joInParam);
                            break;
                        }
                    case "IPInReg"://入院登记
                        {
                            IPAdmRegService service = new IPAdmRegService();
                            rtnResult = service.Register(operationType, joInParam);
                            break;
                        }
                    case "IPInRegCancel"://取消入院登记
                        {
                            IPAdmRegService service = new IPAdmRegService();
                            rtnResult = service.CancelRegister(operationType, joInParam);
                            break;
                        }
                    case "IPOutReg"://出院登记
                        {
                            break;
                        }
                    case "IPUpoload"://住院费用上传
                        {
                            break;
                        }
                    case "IPPreSettl"://住院预计结算
                        {
                            break;
                        }
                    case "IPSettl"://住院结算
                        {
                            IPSettlementService service = new IPSettlementService();
                            rtnResult = service.Charge(joInParam);
                            return rtnResult;
                        }
                    case "DischargeAudit"://费用核查
                        {
                            DischargeAuditService service = new DischargeAuditService();
                            rtnResult = service.Audit(joInParam);
                            return rtnResult;
                        }
                    default:
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "SelfServiceMachine 交易", "传入的业务编码不对！").ToString();
                            return rtnResult;
                        }

                }
                return rtnResult;
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-1, "SelfServiceMachine 交易", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("SelfServiceMachine 出参：" + JsonHelper.Compress(rtnResult));
            }
        }

    }
}
