using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Business;
using System.Windows.Forms;
using PTMedicalInsurance.Helper;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Variables;
using PTMedicalInsurance.Forms;
using System.IO;
using System.Reflection;
using System.Data;

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;

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

        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]);
                joInterface = JObject.Parse(JsonHelper.getDestValue(joInParam, "interfaceinfo"));

                businessType = JsonHelper.getDestValue(joInParam, "businessType");
                return 0;
            }
            catch (Exception ex)
            {
                errMsg = "parseInparam 解析入参异常：" + errMsg;
                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 (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
                    {
                        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);
            }
        }

        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, "GetPatientInfo(读卡)", "初始化失败：" + errMsg).ToString();
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outParam = JsonHelper.setExceptionJson(-100, "GetPatientInfo(读卡)", "初始化异常：" + ex.Message).ToString();
                return -1;
            }
        }

        /// <summary>
        /// 获取患者信息
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        public string GetPatientInfo(string InParam)
        {
            Global.writeLog("GetPatientInfo入参:" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            int errCode;
            string errMsg, 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 (hBus.showPatInfo(outParam, out outParam) != 0)
                                {
                                    rtnResult = outParam;
                                }
                                else
                                {
                                    rtnResult = outParam;
                                }
                            }
                            break;
                        }
                    case "Z1"://住院读卡
                        {
                            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
                            if (hBus.readCard(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-100, "读卡失败！", outParam).ToString();
                            }
                            else
                            {
                                //展示患者信息界面
                                if (hBus.showPatInfo(outParam, 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"://门诊登记
                        {



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


                            break;
                        }
                    case "Z2"://入院登记
                        {
                            Global.writeLog(Global.pat.insuType);
                            string  regInParam = "";
                            
                            //显示登记面板
                            if (hBus.showInPatRegisterForm( out regInParam) == 0)
                            {
                                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, joRegOut, out outParam) != 0)
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "云平台保存登记信息", outParam).ToString();
                                        return rtnResult;
                                    }
                                    //返回登记信息，插入HIS
                                    if (hIS.returnRegisterInfo(joRegIn, 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 (DialogResult.Yes == MessageBox.Show("即将进行取消中心医保登记，确定继续吗？", " 询问？ ", MessageBoxButtons.YesNo))
                            {

                            }
                            else
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "收费员撤销取消登记操作！", outParam).ToString();
                                return rtnResult;
                            }


                            //取消中心登记
                            if (cBus.cancleRegister("2404", out outParam) != 0)
                            {
                                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
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "取消医保登记成功", null).ToString();
                                return rtnResult;
                            }
                        }
                    case "Z6"://出院登记
                        {



                            break;
                        }
                    case "Z6C"://出院登记取消
                        {

                            if (cBus.cancleRegister("2405", out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消出院登记", errMsg).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "取消出院登记成功", null).ToString();
                                return rtnResult;
                            }
                            break;
                        }
                    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));
            //设置返回值，错误信息
            int errCode;
            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);
                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");
                            //先取消中心费用传送
                            cBus.cancleFeeUpload("2302", out errMsg);
                            //再删除医保传送表的数据
                            mIS.deleteFee( out errMsg);
                            //开始进行费用传送
                            //调用HIS费用查询信息
                            if (hIS.getHisFee(Global.pat, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "获取HIS费用", outParam).ToString();
                                return rtnResult;
                            }
                            //调用医保平台转换
                            JObject joHisFee = JObject.Parse(outParam);
                            if (mIS.convertHisFeeWithInsuCode(joHisFee,out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "转换HIS费用", outParam).ToString();
                                return rtnResult;
                            }

                            JArray jaFeeDetail = JArray.Parse(JsonHelper.getDestValue(JObject.Parse(outParam), "data"));
                            //按指定条数分割后上传，保存，更新
                            if (hBus.uploadFeeToCenter("2301",10, jaFeeDetail, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "上传费用", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "住院费用上传成功", null).ToString();
                                return rtnResult;
                            }
                        }
                    case "Z3C"://住院费用上传取消
                        {
                            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));
            }

        }

        /// <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);
                switch (businessType)
                {
                    case "M4"://门诊预结算
                        {
                            OutpatientRegistration frmReg = new OutpatientRegistration();
                            if (frmReg.ShowDialog() == DialogResult.OK)
                            {
                                rtnResult = "调用结束";
                            }
                            break;
                        }
                    case "M4C"://门诊预结算撤销
                        {
                            break;
                        }
                    case "M5"://门诊结算
                        {
                            string patInfo ="";
                            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
                            if (hBus.readCard(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-100, "读卡失败！", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                patInfo = outParam;
                                //展示患者信息界面
                                if (hBus.showPatInfo(patInfo, out outParam) != 0)
                                {
                                    rtnResult = outParam;
                                    return rtnResult;
                                }
                            }
                            //患者信息赋值给全局变量
                            patInfo = outParam;
                            
                            if (hBus.setGlobalPatAfaterShowPatInfo(patInfo, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "setGlobalPatAfaterShowPatInfo", errMsg).ToString();
                                return rtnResult;
                            }
                            ////如果患者异地的则就医地需要该为 369900
                            Global.writeLog(Global.pat.insuplc_admdvs);
                            if (Global.pat.insuplc_admdvs.Substring(0, 4) != Global.inf.areaCode.Substring(0, 4))
                            {
                                Global.inf.areaCode = "369900";
                            }

                            //显示登记面板
                            if (hBus.showOutPatRegisterForm(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "显示登记面板", outParam).ToString();
                                return rtnResult;
                            }
                            JObject joReg = JObject.Parse(outParam);
                            //医保挂号
                            JObject jo2201Inpar = JObject.Parse(JsonHelper.getDestProperty(joReg, "data"));
                            jo2201Inpar = JObject.Parse(JsonHelper.setCenterInpar("2201", jo2201Inpar));
                            //此处先取到就诊信息上传的入参，只要挂号成功就保存到云HIS后台（保存后台需要用到2203入参）
                            JObject jo2203Inpar = new JObject();
                            jo2203Inpar.Add("mdtrtinfo", JObject.Parse(JsonHelper.getDestValue(joReg, "mdtrtinfo")));
                            jo2203Inpar.Add("diseinfo",JArray.Parse(JsonHelper.getDestValue(joReg, "diseinfo")));
                            jo2203Inpar = JObject.Parse(JsonHelper.setCenterInpar("2203", jo2203Inpar));
                            JObject jo2201Rtn = invoker.invokeCenterService("2201", jo2201Inpar);
                            if (JsonHelper.parseCenterRtnValue(jo2201Rtn, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "医保挂号", errMsg).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                Global.pat.mdtrtID = JsonHelper.getDestValue(jo2201Rtn, "output.data.mdtrt_id");
                                //插入患者本次就诊用的参保信息
                                if (hBus.insertPatCurInsuInfo(patInfo, out outParam) != 0)
                                {
                                    if (DialogResult.Yes == MessageBox.Show(outParam, " 是否继续？ ", MessageBoxButtons.YesNo))
                                    {
                                        
                                    }
                                    else
                                    {
                                        rtnResult = JsonHelper.setExceptionJson(-1, "插入患者本次就诊用的参保信息，请联系管理员！是否继续？", outParam).ToString();
                                        return rtnResult;
                                    }
                                }
                                jo2203Inpar["input"]["mdtrtinfo"]["mdtrt_id"] = Global.pat.mdtrtID;
                                //插入云医保平台
                                jo2201Rtn.Add("validflag", 1);
                                jo2201Rtn.Add("regstate", 1);
                                jo2201Rtn.Add("type", 3);
                                if (mIS.saveOutpatRegisterInfo(jo2201Inpar, jo2201Rtn,jo2203Inpar ,out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心登记成功但医保平台保存失败，请联系管理员！", errMsg).ToString();
                                    return rtnResult;
                                }
                            }
                            //门诊就诊信息上传
                            
                            JObject jo2203Rtn = invoker.invokeCenterService("2203",jo2203Inpar );
                            if (JsonHelper.parseCenterRtnValue(jo2203Rtn, out errMsg) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "门诊就诊信息上传", errMsg).ToString();
                                return rtnResult;
                            }
                            //费用上传
                            if (hBus.uploadFee("2204", 50, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "费用上传", outParam).ToString();
                                return rtnResult;
                            }
                            //预结算
                            //调用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 (hBus.preSettlement_OutPat(joSettlement, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算信息展示", outParam).ToString();
                                return rtnResult;
                            }
                            //结算
                             JObject joData = new JObject();
                            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
                            {
                                //返回给云医保平台结算信息
                                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();
                                    Global.writeLog(rtnResult);
                                    MessageBox.Show(errMsg);
                                    //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);
                                    rtnResult = JsonHelper.setIrisReturnValue(0, "结算成功", JObject.Parse(outParam)).ToString();
                                    return rtnResult;
                                }
                            }
                        }
                    case "M5C"://门诊结算撤销
                        {
                            //退中心结算
                            if (cBus.cancleSettlement("2208", out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消中心结算", outParam).ToString();
                                return rtnResult;
                            }
                            //退云医保平台结算
                            if (mIS.cancleSettlement(out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消平台结算信息", outParam).ToString();
                                //return rtnResult;
                            }
                            //中心取消传送
                            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;
                            }
                            //取消中心登记
                            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;
                            }
                            //退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;
                            }
                        }
                    case "Z4"://住院预结算
                        {
                            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;
                            }
                        }
                    case "Z4C"://住院预结算撤销
                        {
                            rtnResult = JsonHelper.setExceptionJson(-100, "该接口不支持预结算取消！", null).ToString();
                            return rtnResult;
                        }
                    case "Z5"://住院结算
                        {
                            JObject joPreSetOutpar ;
                            if (hBus.preSettlement("2303",out joPreSetOutpar, out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算信息展示", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                JObject joSettlement = JObject.Parse(JsonHelper.getDestValue(joPreSetOutpar, "Settlement"));
                                joSettlement.Add("data",joSettlement);
                                //出院登记
                                JObject joDischargeRegister = JObject.Parse(JsonHelper.getDestValue(joPreSetOutpar, "DischargeRegister"));
                                JObject jo2402Rtn = invoker.invokeCenterService("2402", JsonHelper.setCenterInpar("2402", joDischargeRegister));
                                if (JsonHelper.parseCenterRtnValue(jo2402Rtn, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "结算失败", errMsg).ToString();
                                    return rtnResult;
                                }
                                //验密(南昌不需要)
                                //hBus.readCard(out outParam)
                                //正式结算
                                JObject jo2304Rtn = invoker.invokeCenterService("2304",JsonHelper.setCenterInpar("2304",joSettlement));
                                if (JsonHelper.parseCenterRtnValue(jo2304Rtn, out errMsg) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "结算失败", errMsg).ToString();
                                    cBus.cancleRegister("2405", out errMsg);
                                    return rtnResult;
                                }
                                else
                                {
                                    //返回给云医保平台结算信息
                                    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;
                                    }
                                }
                            }

                        }
                    case "Z5C"://住院结算撤销
                        {
                            //取消中心结算信息
                            if (cBus.cancleSettlement("2305", out outParam) != 0)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "取消中心结算信息失败！", outParam).ToString();
                                return rtnResult;
                            }
                            else
                            {
                                //取消平台结算信息
                                if (mIS.cancleSettlement(out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心结算取消成功，医保平台结算信息取消失败！", outParam).ToString();
                                    return rtnResult;
                                }
                                //取消HIS医保结算信息
                                if (hIS.cancleSettlementInfo(joParam, out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(-1, "中心跟医保平台结算取消成功， 取消HIS结算信息失败！", outParam).ToString();
                                    return rtnResult;
                                }
                                //取消出院登记
                                if (cBus.cancleRegister("2405", out outParam) != 0)
                                {
                                    rtnResult = JsonHelper.setExceptionJson(0, "中心，医保平台及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));
            }


        }

        /// <summary>
        /// 辅助交易
        /// </summary>
        /// <param name="InParam"></param>
        /// <returns></returns>
        //[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]
        public string AgentFun(string InParam)
        {
            Global.writeLog("AgentFun 入参:" + JsonHelper.Compress(InParam));
            //设置返回值，错误信息
            int errCode;
            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);
                switch (businessType)
                {
                    case "BasicData"://基础数据维护
                        {
                            MessageBox.Show(businessType);

                            break;
                        }
                    case "Exception"://异常处理
                        {
                            //显示异常处理界面
                            HandleException frmEX = new HandleException();
                            if (frmEX.ShowDialog() == DialogResult.OK)
                            {

                            }
                            break;
                        }
                    case "CheckAndClearing"://对账清算
                        {
                            MessageBox.Show(businessType);

                            break;
                        }
                    case "Print"://打印
                        {
                            //显示打印界面
                            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();
                            break;
                        }
                    case "Log"://日志
                        {
                            MessageBox.Show(businessType);

                            break;
                        }
                    case "RecordUpload"://上传记录
                        {
                            MessageBox.Show(businessType);
                            break;
                        }
                    case "HospitalRegister"://备案
                        {
                            MessageBox.Show(businessType);
                            break;
                        }
                    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));
            //设置返回值，错误信息
            int errCode;
            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.Download(funNO, downloadParam);
                            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);
            }


        }

    }
}
