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;
        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]);                

                joInterface = JObject.Parse(JsonHelper.getDestValue(joInParam, "interfaceinfo"));

                businessType = JsonHelper.getDestValue(joInParam, "businessType");
                operationType = JsonHelper.getDestValue(joInParam, "operationType");
                if ((businessType == "M6") || (businessType == "M6C") || (businessType == "M6Confirm"))
                {
                    Environment.CurrentDirectory = @"D:\HttpServerAPI\bin\libs";
                }
                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 (businessType != "BasicData")//如果是打开数据对照界面不调用初始化 
                        {
                            // 济南不签到
                            Global.curEvt.signno = "000000";
                            rtnResult = JsonHelper.setIrisReturnValue(0, "签到成功", joRtn).ToString();

                            //CallResult callResult = new SignInProcess().Process(joRtn);
                            //if (callResult.Success)
                            //{
                            //    rtnResult = callResult.Data;
                            //}
                        }
                        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"://门诊读卡
                    case "Z1"://住院读卡
                        {
                            //打开读卡窗口，操作员选择读卡类型后进行读卡器读卡，再进行1101获取参保信息
                            PatientService patientService = new PatientService();
                            patientService.readPatientInfo(out outParam);
                            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;
                            //}

                            //Global.writeLog("获取到病人信息:" + patInfo);

                            //JObject reg = JObject.Parse(patInfo);

                            //this.OutpatientReg(reg,patInfo);

                            break;
                        }
                    case "M2C"://门诊登记撤销
                        {
                            break;
                        }
                    case "Z0"://住院修改
                        {
                            break;
                        }
                    case "Z2"://入院登记
                        {
                            Global.Set.clearingWay = "1"; //住院
                            rtnResult = new InpatientRegistionProcess().Process(joParam).Data;
                            break;
                        }
                    case "Z2C"://入院登记取消
                        {
                            rtnResult = new InpatientRegCancelProcess().Process(joParam).Data;
                            break;

                        }
                    case "Z6"://出院登记
                        {
                            break;
                        }
                    case "Z6C"://出院登记取消
                        {
                            rtnResult = new InpatientExitCancelProcess().Process(joParam).Data;
                            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 rtnResult;
        }

        /// <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);
                switch (businessType)
                {
                    case "M3"://门诊费用上传
                        {
                            break;
                        }
                    case "M3C"://门诊费用撤销
                        {

                            break;
                        }
                    case "Z3"://入院费用上传
                        {
                            rtnResult = new InpatientFeeUploadProcess().Process(joParam).Data;
                            break;
                        }
                    case "Z3C"://住院费用上传取消
                        {
                            rtnResult = new InpatientFeeUploadCancelProcess().Process(joParam).Data;
                            break;
                        }

                    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"://门诊结算
                        {
                            Global.Set.clearingWay = "6"; //门诊
                            LocalOPSettleService opService = new LocalOPSettleService();
                            rtnResult = opService.Charge(operationType, joInParam);
                            break;
                        }
                    case "M5C"://门诊结算撤销
                        {
                            LocalOPSettleService opService = new LocalOPSettleService();
                            rtnResult = opService.DisCharge(joParam);
                            break;
                        }
                    case "M6"://门诊移动支付结算
                        {
                            #region 移动支付
                            //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;
                            #endregion
                            break;
                        }
                    case "M6C"://门诊移动支付结算撤销
                        {
                            #region 移动支付取消
                            //MobilePay mp = new MobilePay(InParam, out errMsg);
                            //if (errMsg != "")
                            //{
                            //    rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", errMsg).ToString();
                            //    return rtnResult;
                            //}
                            //if (mp.MobilePayCancelSettlement(out outParam) != 0)
                            //    rtnResult = JsonHelper.setExceptionJson(-1, "Settlement 交易", outParam).ToString();
                            //else
                            //    rtnResult = outParam;
                            //return rtnResult;
                            #endregion
                            break;
                        }
                    case "M6Confirm"://门诊移动支付确认
                        {
                            #region 移动支付确认
                            //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;
                            #endregion
                            break;
                        }
                    case "Z4"://住院预结算
                        {
                            #region 预结算
                            Global.pat.RYorCY = "2";
                            JObject joSettle = new JObject();
                            CallResult result = new IPPreSettlementProcess().Process(joParam);
                            if (result.Success)
                            {
                                rtnResult = JsonHelper.setExceptionJson(-1, "结算信息展示", result.Data).ToString();
                            }
                            else
                            {
                                rtnResult = JsonHelper.setIrisReturnValue(0, "预结算成功", null).ToString();
                            }
                            break;
                            #endregion
                        }
                    case "Z4C"://住院预结算撤销
                        {
                            rtnResult = JsonHelper.setExceptionJson(-100, "该接口不支持预结算取消！", null).ToString();
                            return rtnResult;
                        }
                    case "Z5"://住院结算
                        {
                            Global.Set.clearingWay = "1"; //住院
                            IPSettlementService ipService = new IPSettlementService();
                            rtnResult = ipService.Charge(operationType,joParam);
                            break;
                        }
                    case "Z5C"://住院结算撤销
                        {
                            IPSettlementService ipService = new IPSettlementService();
                            rtnResult = ipService.DisCharge(joParam);
                            break;
                        }
                    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>
        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"://基础数据维护
                        {
                            BasicData bd = new BasicData();
                            bd.ShowDialog();
                            break;
                        }
                    case "Exception"://异常处理
                        {
                            //显示异常处理界面
                            HandleException frmEX = new HandleException();
                            if (frmEX.ShowDialog() == DialogResult.OK)
                            {

                            }
                            break;
                        }
                    case "CheckAndClearing"://对账清算
                        {
                            ClearingQuery frmEX = new ClearingQuery();
                            if (frmEX.ShowDialog() == DialogResult.OK)
                            {

                            }
                            break;
                        }
                    case "Print"://打印
                        {
                            try
                            {
                                rtnResult = new LocalSettleBillPrintProcess().Process(joInParam).Data;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            break;
                        }
                    case "Log"://日志
                        {
                            MessageBox.Show(businessType);

                            break;
                        }
                    case "RecordUpload"://上传记录
                        {
                            MessageBox.Show(businessType);
                            break;
                        }
                    case "HospitalRegister"://备案
                        {
                            ToRecordChoose Referral = new ToRecordChoose();
                            Referral.ShowDialog();
                            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;
                        }
                    default:
                        {
                            rtnResult = JsonHelper.setExceptionJson(-1, "AgentFun 交易", "传入的业务编码不对！").ToString();
                            break;
                        }
                }
                return rtnResult;
            }
            catch (Exception ex)
            {
                rtnResult = JsonHelper.setExceptionJson(-1, "AgentFun 交易", ex.Message).ToString();
                return rtnResult;
            }
            finally
            {
                Global.writeLog("AgentFun 出参：" + JsonHelper.Compress(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");
                TradeEnum trade = TradeEnum.DEFAULT.GetByCode(funNO);
                JObject joRtn = invoker.invokeCenterService(trade, 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));
            }
        }

    }
}
