/******************************************************************************
 * 文件名称: InvokeHelper.cs
 * 文件说明: 调用助手，调用方法的封装
 * 当前版本: V1.0
 * 创建日期: 2022-04-12
 *
 * 2020-04-12: 增加 businessDLLInvoke 方法
 * 2020-04-12: 增加 writeLog 方法
 * 2020-04-14: 增加 businessDLLInvoke(重载) 方法
 * 2020-04-14: 增加 irisServiceInvoke 方法



******************************************************************************/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.APIGATEWAY_SDK;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Entity;
using PTMedicalInsurance.Forms;
using PTMedicalInsurance.Variables;
using SM2Crypto.Lib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace PTMedicalInsurance.Helper
{
    public class InvokeHelper
    {
        private string serviceURL;
        private string authorization;

        public InvokeHelper()
        {
            IniFile ini = new IniFile(Global.curEvt.path + @"\CenterServiceURL.ini");
            //Global.inf.centerURL = ini.ReadValue("CENTER", "url");
            //Global.inf.uploadURL = ini.ReadValue("CENTER", "upload");
            //Global.inf.downURL = ini.ReadValue("CENTER", "download");
            //Global.inf.ecURL = ini.ReadValue("CENTER", "ecToken");
        }


        #region 内部服务调用

        /// <summary>
        /// iris服务调用的封装
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject invokeIrisService(string data, string serviceDesc)
        {
            string rtn = "", url = "";
            JObject joRtn = new JObject();
            try
            {
                //先根据用户请求的uri构造请求地址
                url = serviceURL;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
                //添加头部信息
                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.Headers.Add("Authorization", authorization);
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                rtn = getResponseData(myResponse);
                joRtn = JObject.Parse(rtn);
                return joRtn;
            }
            catch (Exception ex)
            {
                joRtn = JsonHelper.setExceptionJson(-1, serviceDesc, ex.Message);
                rtn = JsonConvert.SerializeObject(joRtn);
                return joRtn;
            }
        }

        /// <summary>
        /// HIS服务调用的封装
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// 
        public JObject invokeHISService(string data, string serviceDesc)
        {
            JObject joRtn = new JObject();
            try
            {
                //先根据用户请求的uri构造请求地址
                serviceURL = string.Format("{0}/{1}", Global.hisConfig.ip, Global.hisConfig.url);
                authorization = Global.hisConfig.authorization;
                joRtn = invokeIrisService(data, serviceDesc);
                return joRtn;
            }
            catch (Exception ex)
            {
                joRtn = JsonHelper.setExceptionJson(-1, serviceDesc, ex.Message);
                return joRtn;
            }
            finally
            {
                Global.writeLog_Iris(serviceDesc + "(" + serviceURL + ")" + "Authorization:" + (authorization), JsonHelper.Compress(data), JsonHelper.Compress(joRtn));
            }
        }

        /// <summary>
        /// 医保平台服务调用的封装
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject invokeInsuService(string data, string serviceDesc)
        {
            string rtn = "";
            JObject joRtn = new JObject();
            try
            {
                //先根据用户请求的uri构造请求地址
                serviceURL = string.Format("{0}/{1}", Global.insuConfig.ip, Global.insuConfig.url);
                authorization = Global.insuConfig.authorization;
                joRtn = invokeIrisService(data, serviceDesc);
                rtn = JsonConvert.SerializeObject(joRtn);

                //if (serviceDesc == "插入签到信息")
                //{
                //    MessageBox.Show("插入签到信息入参：" + data +"|返回值："+ rtn.ToString()+"|"+ Global.insuConfig.url);
                //}

                return joRtn;
            }
            catch (Exception ex)
            {
                joRtn = JsonHelper.setExceptionJson(-1, serviceDesc, ex.Message);
                rtn = JsonConvert.SerializeObject(joRtn);
                return joRtn;
            }
            finally
            {
                Global.writeLog_Iris(serviceDesc + "(" + serviceURL + ")" + "Authorization:" + (authorization), JsonHelper.Compress(data), rtn);
            }
        }

        private string getResponseData(HttpWebResponse response)
        {
            string data = "";
            if (response != null)
            {
                Stream s = response.GetResponseStream();
                StreamReader sRead = new StreamReader(s);
                data = sRead.ReadToEnd();
                sRead.Close();
                response.Close();
            }
            return data;
        }

        #endregion

        #region 医保中心调用

        private JObject invokeCenterService(string data)
        {
            JObject joRtn = new JObject();
            IInvokeCenter center = InvokeCenterFactory.create();
            string outputData = "";
            string errMsg = "";
            try
            {
                int iInt = center.Init(ref errMsg);
                if (iInt == 0)
                {
                    iInt = center.Business(data, ref outputData, ref errMsg);
                    joRtn = JObject.Parse(outputData);
                    return joRtn;
                }
                else
                {
                    joRtn.Add("infcode", -1);
                    joRtn.Add("err_msg", "医保动态库初始化失败invokeInitByDLL:" + errMsg);
                    return joRtn;
                }
            }
            finally
            {
                if (!(data.Contains(@"""infno"": ""9101"""))) 
                this.saveCenterLog(JsonHelper.Compress(data), JsonHelper.Compress(joRtn), JsonHelper.Compress(data), JsonHelper.Compress(joRtn));
            }

        }

        private void prepareCallCenter(string funNo)
        {
            string prefix = Global.inf.centerURL;
            //switch (funNo)
            //{
            //    case "9101":
            //        prefix = Global.inf.uploadURL;
            //        break;
            //    case "9102":
            //        prefix = Global.inf.downURL;
            //        break;
            //    default:
            //        prefix = Global.inf.centerURL;
            //        break;
            //}
            Global.curEvt.URL = prefix ;
        }
  
        /// <summary>
        /// 这个是调用业务服务的invokeCenterService
        /// </summary>
        /// <param name="funNO"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject invokeCenterService(string funNO, JObject data)
        {
            // 动态调试模式
            if (Global.curEvt.enabledDebug)
            {
                CenterResult center = new CenterResult();
                center.setTradeNo(funNO);
                if (center.ShowDialog() == DialogResult.OK)
                {
                    string outPar = center.returnData;
                    return JObject.Parse(outPar);
                }
            }
            prepareCallCenter(funNO);
            return invokeCenterService(JsonHelper.toJsonString(data));
        }

        /// <summary>
        /// 这个是下载目录用的invokeCenterService
        /// </summary>
        /// <param name="funNO"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject invokeCenterService(string funNO, string data)
        {
            // 动态调试模式
            if (Global.curEvt.enabledDebug)
            {
                CenterResult center = new CenterResult();
                center.setTradeNo(funNO);
                if (center.ShowDialog() == DialogResult.OK)
                {
                    string outPar = center.returnData;
                    return JObject.Parse(outPar);
                }
            }

            prepareCallCenter(funNO);
            return invokeCenterService(data);
        }

        /// <summary>
        /// 医保目录txt文件下载
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject DownloadCenterFile(string data)
        {
            //download file
            IInvokeCenter center = InvokeCenterFactory.create();
            string outputMsg = "";
            JObject joRtn = new JObject();
            int rtnCode = center.DownloadFile(data, ref outputMsg);
            if(rtnCode==0)
            {
                joRtn = JObject.Parse(outputMsg);
            }
            else
            {
                joRtn.Add("infcode", -1);
                joRtn.Add("err_msg", "下载文件失败DownloadFile:" + outputMsg);
            }
            return joRtn;
        }

        #endregion


        #region 乌鲁木齐特有大文件上传9101
        
        public int UploadFileAsJsonStream(string filePath, string fileName, ref string outputData, ref string pErrMsg)
        {
            outputData = "";
            pErrMsg = "";

            string url = Global.inf.centerURL;
            string infno = "9101";

            try
            {
                // 生成 msgid（确保不超过30位）
                string rawMsgId = $"H{Global.inf.hospitalNO}{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";
                string msgid = rawMsgId.Length > 30 ? rawMsgId.Substring(0, 30) : rawMsgId;

                // 创建请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
                request.ProtocolVersion = HttpVersion.Version10;

                // ⚠️ 关键：提前计算 Content-Length（避免 chunked）
                long fileLength = new FileInfo(filePath).Length;
                Global.writeLog("文件大小: " + fileLength + " 字节");
                long base64Length = ((fileLength + 2) / 3) * 4; // Base64 后长度

                string jsonPrefix = GenerateJsonPrefix(infno, msgid, fileName);
                string jsonSuffix = "\"}}}";

                byte[] prefixBytes = Encoding.UTF8.GetBytes(jsonPrefix);
                byte[] suffixBytes = Encoding.UTF8.GetBytes(jsonSuffix);

                //long totalLength = prefixBytes.Length + base64Length + suffixBytes.Length;

                //request.ContentLength = totalLength;
                //request.SendChunked = false;
                //request.AllowWriteStreamBuffering = false;

                // 获取请求流
                using (Stream requestStream = request.GetRequestStream())
                {
                    // 1. 写入 JSON 前缀
                    requestStream.Write(prefixBytes, 0, prefixBytes.Length);

                    // 2. 流式读取文件，使用 Convert.ToBase64String 编码，并直接写入 requestStream
                    const int ChunkSize = 12288; // 必须是 3 的倍数（如 3*4096），保证 Base64 编码块完整，避免跨块填充问题
                    byte[] buffer = new byte[ChunkSize];

                    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 8192, useAsync: false))
                    {
                        int bytesRead;
                        while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            Global.writeLog($"读取到 {bytesRead} 字节");

                            // 将当前块编码为 Base64 字符串
                            string base64Chunk = Convert.ToBase64String(buffer, 0, bytesRead);

                            // 转为 UTF-8 字节（Base64 是 ASCII 子集）
                            byte[] encodedBytes = Encoding.UTF8.GetBytes(base64Chunk);

                            // 直接写入网络流
                            requestStream.Write(encodedBytes, 0, encodedBytes.Length);
                        }
                    }

                    // 3. 写入 JSON 后缀
                    requestStream.Write(suffixBytes, 0, suffixBytes.Length);

                    // 可选：记录完整请求内容（⚠️ 仅用于调试，大文件会爆内存）
                    // var fullRequest = StreamToString(requestStream); // ❌ 不要这样做！流已关闭或不可读

                    Global.writeLog("HTTP 请求体写入完成");
                    // requestStream.Close(); // ❌ 不要手动 Close，using 会自动处理
                }



                Global.writeLog("1");
                // 接收响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    outputData = GetResponseData(response);
                }
                Global.writeLog("2");
                // 提取 body
                if (!string.IsNullOrEmpty(outputData))
                {
                    var joRtn = Newtonsoft.Json.Linq.JObject.Parse(outputData);
                    if (joRtn.ContainsKey("body"))
                    {
                        outputData = joRtn["body"].ToString();
                    }
                }

                return 0;
            }
            catch (Exception ex)
            {
                pErrMsg = "流式上传失败: " + ex.Message;
                outputData = JsonHelper.setExceptionJson(-99, "流式上传异常", ex.Message).ToString();
                return -1;
            }
        }

        public  string StreamToString(Stream stream, Encoding encoding = null)
        {
            // 如果传入 null，使用 UTF8
            if (encoding == null) encoding = Encoding.UTF8;

            // 确保流位置从头开始
            if (stream.CanSeek)
                stream.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(stream, encoding))
            {
                return reader.ReadToEnd();
            }
        }


        // 提取 JSON 前缀生成逻辑
        private string GenerateJsonPrefix(string infno, string msgid, string fileName)
        {
            return "{" +
                $"\"infno\":\"{infno}\"," +
                $"\"msgid\":\"{msgid}\"," +
                $"\"mdtrtarea_admvs\":\"{Global.inf.areaCode}\"," +
                $"\"recer_sys_code\":\"YBXT\"," +
                $"\"dev_no\":\"2021\"," +
                $"\"signtype\":\"SM2\"," +
                $"\"infver\":\"v1.0\"," +
                $"\"opter_type\":\"1\"," +
                $"\"opter\":\"{Global.user.ID}\"," +
                $"\"opter_name\":\"{Global.user.name}\"," +
                $"\"inf_time\":\"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\"," +
                $"\"fixmedins_code\":\"{Global.inf.hospitalNO}\"," +
                $"\"fixmedins_name\":\"{Global.inf.hospitalName}\"," +
                $"\"sign_no\":\"{Global.curEvt.signno}\"," +
                $"\"serv_code\":\"HH00029\"," +
                $"\"serv_sign\":\"0C9BC4D70BDE653D8E\"," +
                "\"input\":{\"fsUploadIn\":{" +
                $"\"filename\":\"{EscapeJsonString(fileName)}\"," +
                $"\"fixmedins_code\":\"{Global.inf.hospitalNO}\"," +
                "\"in\":\"";
        }


        private string EscapeJsonString(string s)
        {
            return s?.Replace("\\", "\\\\")
                      .Replace("\"", "\\\"")
                      .Replace("\r", "\\r")
                      .Replace("\n", "\\n")
                      .Replace("\t", "\\t");
        }
        private string GetResponseData(HttpWebResponse response)
        {
            using (Stream stream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        

        #endregion

        #region 移动
        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="funNO"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject invokeMPService(string funNO, string data)
        {
            return invokeMPService(funNO, JObject.Parse(data));
        }
        public JObject invokeMPService(string funNO, JObject joInput)
        {
            JObject joRtn = new JObject();
            String outPar = "";
            try
            {
                string url = "";
                switch (funNO)
                {
                    case "6201":
                        url = "/org/local/api/hos/uldFeeInfo";
                        break;
                    case "6202":
                        url = "/org/local/api/hos/pay_order";
                        break;
                    case "6203":
                        url = "/org/local/api/hos/refund_Order";
                        break;
                    case "6301":
                        url = "/org/local/api/hos/query_order_info";
                        break;
                    case "6401":
                        url = "/org/local/api/hos/revoke_order";
                        break;
                    default:
                        break;
                }
                EncryptHelper encrypt = new EncryptHelper(Global.inf.MobilePay.appid, Global.inf.MobilePay.secretKey, Global.inf.MobilePay.publicKey, Global.inf.MobilePay.privateKey);
                //////测试环境
                //Global.inf.mobilePayURL = @"http:\\10.139.32.10:8080";
                ////正式环境
                ////Global.inf.mobilePayURL = @"http:\\10.139.97.107:8080";
                string data = JsonHelper.setMPCenterInpar(funNO, joInput);
                // 移动支付地址
                Global.curEvt.URL = Global.inf.MobilePay.url + url;
                Global.inf.centerURL = Global.curEvt.URL;

                string outputData = "", errMsg = "";

                // 动态调试模式
                if (Global.curEvt.enabledDebug)
                {
                    CenterResult center = new CenterResult();
                    center.setTradeNo(funNO);
                    if (center.ShowDialog() == DialogResult.OK)
                    {
                        outPar = center.returnData;
                        return JObject.Parse(outPar);
                    }
                }

                try
                {
                    InvokeRestCenter mobileCenter = new InvokeRestCenter();
                    int iInt = mobileCenter.Business(data, ref outputData, ref errMsg);
                    joRtn = JObject.Parse(outputData);

                    string encData = JsonHelper.getDestValue(joRtn, "encData");
                    string signData = JsonHelper.getDestValue(joRtn, "signData");
                    if (!string.IsNullOrEmpty(encData) && !string.IsNullOrEmpty(signData))
                    {
                        joRtn.Remove("encData");
                        joRtn.Remove("signData");
                        joRtn.Remove("data");
                        //解密
                        string decData = encrypt.decrypt(encData);
                        // 验签
                        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                        {
                            FloatParseHandling = FloatParseHandling.Decimal
                        };
                        joRtn.Add("data", JToken.FromObject(JsonConvert.DeserializeObject(decData)));

                        bool rtn = encrypt.verify(joRtn, signData);
                        if (rtn)
                        {
                            joRtn = JObject.Parse(decData);
                            joRtn.Add("success", "True");
                        }
                        else
                        {
                            Global.writeLog("验签失败，请核查!");
                        }
                    }

                    return joRtn;

                }
                finally
                {
                    this.saveCenterLog(JsonHelper.Compress(data), joRtn.ToString(), JsonHelper.Compress(data), joRtn.ToString());
                }

            }
            catch (Exception ex)
            {
                if (joRtn["infcode"] == null)
                { joRtn.Add("infcode", -1); }
                if (joRtn["err_msg"] == null)
                { joRtn.Add("err_msg", "invokeCenterService(3):" + ex.Message); }
                outPar = JsonHelper.Compress(joRtn);
                return joRtn;
            }
            finally
            {
                Global.writeLog(funNO + "(" + Global.curEvt.URL + ")", joInput.ToString(), joRtn.ToString());
                this.saveCenterLog(joInput.ToString(), joRtn.ToString(), joInput.ToString(), joRtn.ToString());
            }
        }

        /// <summary>
        /// 保存中心交易日志到数据库
        /// </summary>
        /// <param name="inParam"></param>
        /// <param name="outParam"></param>
        /// <param name="inParamPlain"></param>
        /// <param name="outParamPlain"></param>
        private void saveCenterLog(string inParam, string outParam, string inParamPlain, string outParamPlain)
        {
            dynamic joIris = new JObject();
            string sRtn = "";
            try
            {
                //解析postContent,插入医保交易日志表
                JObject joInParam = new JObject(JObject.Parse(inParam));
                //解包
                JObject joIn = Utils.removeWrapper(joInParam);

                JObject joOut = new JObject(JObject.Parse(outParam));
                JObject joInPlain = new JObject(JObject.Parse(inParamPlain));
                JObject joOutPlain = new JObject(JObject.Parse(outParamPlain));
                JArray jaParams = new JArray();
                JObject joParam = new JObject();
                joParam.Add("inParam", JObject.FromObject(joIn));
                joParam.Add("outParam", JObject.FromObject(joOut));
                joParam.Add("inParamPlain", JObject.FromObject(joInPlain));
                joParam.Add("outParamPlain", JObject.FromObject(joOutPlain));

                joParam.Add("HospitalDr", Global.inf.hospitalDr);
                joParam.Add("InterfaceDr", Global.inf.interfaceDr);
                joParam.Add("updateUserID", Global.user.ID);
                joParam.Add("psn_no", Global.pat.psn_no);
                jaParams.Add(joParam);
                joIris.code = "09010021";
                joIris.Add("params", jaParams);
                //InvokeHelper invoker = new InvokeHelper();
                sRtn = invokeInsuService(joIris.ToString(), "保存日志到数据库").ToString();
            }
            catch (Exception ex)
            {
                sRtn = JsonHelper.setExceptionJson(-100, "保存日志异常", ex.Message).ToString();
                Global.writeLog_Iris("保存日志异常:" + sRtn.ToString());
            }
        }

        #endregion

        #region 处方流转

        /// <summary>
        /// 医保电子处方流转调用服务
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private JObject invokeCenterServicePresCir(string data)
        {
            string postContent = "";
            JObject joRtn = new JObject();
            try
            {
                //内容类型                
                Signer signer = new Signer();
                signer.Key = Global.inf.PresCir.privateKey;                     //应用编码
                signer.Secret = Global.inf.PresCir.secretKey;               //secretKey 私钥

                string timestamp = TimeStamp.get13().ToString();  //当前时间戳（秒）
                string nonce = Guid.NewGuid().ToString();         //非重复的随机字符串（十分钟内不能重复）

                HttpRequest Resquest = new HttpRequest("POST", new Uri(Global.curEvt.URL));
                Resquest.headers.Add("charset", "UTF-8");
                //Resquest.headers.Add("x-hw-id", signer.Key);
                //Resquest.headers.Add("x-tif-timestamp", timestamp);
                //Resquest.headers.Add("x-tif-passid", signer.Key);
                //Resquest.headers.Add("x-tif-nonce", nonce);
                Resquest.body = data;

                string RtnStr;
                HttpWebRequest req = signer.Sign(Resquest);
                req.ContentType = "application/json;charset=utf8";
                req.Timeout = 5 * 10000;

                try
                {
                    var writer = new StreamWriter(req.GetRequestStream());
                    writer.Write(Resquest.body);
                    writer.Flush();
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    StreamReader reader = new StreamReader(resp.GetResponseStream());

                    RtnStr = reader.ReadToEnd();
                    joRtn = JObject.Parse(RtnStr);//返回Json数据
                    return joRtn;
                }
                catch (WebException e)
                {
                    HttpWebResponse resp = (HttpWebResponse)e.Response;
                    if (resp != null)
                    {
                        return JsonHelper.setExceptionJson(-99, "centerServeiceInvok中获得响应流异常(a)", new StreamReader(resp.GetResponseStream()).ReadToEnd() + "异常内容：" + e.Message);
                    }
                    else
                    {
                        RtnStr = "异常:" + e.Message;
                        return JsonHelper.setExceptionJson(-99, "centerServeiceInvok中获得响应流异常(b)", e.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                postContent = "调用中心服务异常" + ex.Message;
                joRtn.Add("infcode", -1);
                joRtn.Add("err_msg", "invokeCenterService(Exception_Last):" + ex.Message);
                return joRtn;
            }
        }

        /// </summary>
        /// <param name="funNO"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JObject invokeCenterServicePresCir(string funNO, string data)
        {
            JObject joRtn = new JObject();
            string outPar = "";

            try
            {
                if (funNO == "7101")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/uploadChk";
                }
                else if (funNO == "7102")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxFixmedinsSign";
                }
                else if (funNO == "7103")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxFileUpld";
                }
                else if (funNO == "7104")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxUndo";
                }
                else if (funNO == "7105")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/hospRxDetlQuery";
                }
                else if (funNO == "7106")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxChkInfoQuery";
                }
                else if (funNO == "7107")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxSetlInfoQuery";
                }
                else if (funNO == "7108")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxChkInfoCallback";
                }
                else if (funNO == "7109")
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/rxSetlInfoCallback";
                }
                else if (funNO == "7112") //电子处方药品目录查询
                {
                    Global.curEvt.URL = Global.inf.PresCir.url + "/fixmedins/circDrugQuery";
                }
                else
                {
                    Global.curEvt.URL = Global.inf.centerURL;
                }

                //Global.curEvt.URL = Global.inf.centerURL;
                joRtn = invokeCenterServicePresCir(data);
                outPar = JsonHelper.Compress(joRtn);

                return joRtn;
            }
            catch (Exception ex)
            {
                if (joRtn["infcode"] == null)
                { joRtn.Add("infcode", -1); }
                if (joRtn["err_msg"] == null)
                { joRtn.Add("err_msg", "invokeCenterServicePresCir(3):" + ex.Message); }
                outPar = JsonHelper.Compress(joRtn);
                return joRtn;
            }
            finally
            {
                Global.writeLog(funNO + "(" + Global.curEvt.URL + ")", JsonHelper.Compress(data), joRtn.ToString());
                //this.saveCenterLog(JsonHelper.Compress(data), outPar, JsonHelper.Compress(data), outPar);
            }
        }


        #endregion

        #region 调用一码付
        public JObject invokeOneCodePayService(string funNO, string data)
        {
            return invokeOneCodePayService(funNO, JObject.Parse(data));
        }

        public JObject invokeOneCodePayService(string funNO, JObject joInput)
        {
            JObject joRtn = new JObject();
            String outPar = "";
            try
            {
                string url = "";
                switch (funNO)
                {
                    case "QuerySignedPayStatus":
                        url = "/cfc/api/signedQuery";
                        break;
                    case "GetPayCert":
                        url = "/cfc/api/genPayCert";
                        break;
                    default:
                        break;
                }
                //EncryptHelper encrypt = new EncryptHelper();
                string data = JsonHelper.setOneCodePayInpar(joInput);
                // 一码付地址
                Global.curEvt.URL = Global.inf.oneCodePay.url + url;

                string outputData = "", errMsg = "";

                // 动态调试模式
                if (Global.curEvt.enabledDebug)
                {
                    CenterResult center = new CenterResult();
                    center.setTradeNo(funNO);
                    if (center.ShowDialog() == DialogResult.OK)
                    {
                        outPar = center.returnData;
                        return JObject.Parse(outPar);
                    }
                }

                try
                {
                    InvokeRestCenter oneCodePayRest = new InvokeRestCenter();
                    int iInt = oneCodePayRest.Business(data, ref outputData, ref errMsg);
                    joRtn = JObject.Parse(outputData);

                    return joRtn;

                }
                finally
                {
                    this.saveCenterLog(JsonHelper.Compress(data), joRtn.ToString(), JsonHelper.Compress(data), joRtn.ToString());
                }

            }
            catch (Exception ex)
            {
                if (joRtn["code"] == null)
                { joRtn.Add("code", -1); }
                if (joRtn["message"] == null)
                { joRtn.Add("message", "invokeOneCodePayService:" + ex.Message); }
                outPar = JsonHelper.Compress(joRtn);
                return joRtn;
            }
            finally
            {
                Global.writeLog(funNO + "(" + Global.curEvt.URL + ")", joInput.ToString(), joRtn.ToString());
                this.saveCenterLog(joInput.ToString(), joRtn.ToString(), joInput.ToString(), joRtn.ToString());
            }
        }

        #endregion



    }
}
