/******************************************************************************
  * 文件名称: JsonHelper.cs
 * 文件说明: Json业务的封装，处理JSON串的封装，解析等
 * 当前版本: V1.0
 * 创建日期: 2022-04-14
 *
 * 2020-04-14: 增加 setIrisInpar 方法
 * 2020-04-14: 增加 setIrisInpar（重载） 方法
 * 2020-04-14: 增加 getIrisExceptionJson 方法
 * 2020-04-14: 增加 parseBusinessJson 方法

 ******************************************************************************/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Common.SMLib;
using PTMedicalInsurance.Variables;
using SM2Crypto.Lib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Helper
{
    public class JsonHelper
    {

        public static string toJsonString(object obj,bool missingNull)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            if (missingNull)
            {
                settings.NullValueHandling = NullValueHandling.Ignore;
            }
            return JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
        }

        public static string toJsonString(object obj)
        {
            return toJsonString(obj,true);
        }

        public static object toObject(string json)
        {
            return JsonConvert.DeserializeObject(json);
        }

        public static T toObject<T>(JObject joObject)
        {
            return joObject.ToObject<T>();
        }

        /// <summary>
        /// 解析医保平台返回对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <returns></returns>
        public static T getOutput<T>(JObject response)
        {
            if (response.ContainsKey("output")) 
            {
                return response["output"].ToObject<T>();
            }

            return response.ToObject<T>();
        }
        
        /// <summary>
        /// 解析IRIS系统返回对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <returns></returns>
        public static T getResult<T>(JObject response)
        {
            Response resp = response.ToObject<Response>();
            if (resp.errorCode == "0")
            {
                if (resp.result?.GetType() == typeof(JObject))
                {
                    JObject ret = (JObject)resp.result;
                    JArray lists = ret.Value<JArray>("rows");
                    if (lists?.Count > 0)
                    {
                        return lists.ToObject<T>();
                    }
                    else {
                        return ret.ToObject<T>();
                    }
                }
                if (resp.result?.GetType() == typeof(JArray))
                {
                    JArray lists = (JArray)resp.result;
                    if (lists?.Count > 0)
                    {
                        return lists[0].ToObject<T>();
                    }
                }
            }

            return default;

        }

        /// <summary>
        /// 根据JSonPath查找节点值，如果节点不存在则返回空值
        /// </summary>
        /// <param name="jo"></param>
        /// <param name="jsonPath"></param>
        /// <returns></returns>
        public static string getDestValue(JObject jo, string destPath)
        {
            JToken jt = jo.SelectToken("$." + destPath);
            if (jt != null)
            {
                return jt.ToString();
            }
            else
            {
                Global.writeLog(destPath + "的JToken属性值为空");
                return "";
            }
        }

        /// <summary>
        /// 将指定的json内容转为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jo"></param>
        /// <param name="destPath"></param>
        /// <returns></returns>
        public static T parseObject<T>(JObject jo, string destPath)
        {
            JToken jt = jo.SelectToken("$." + destPath);
            if (jt != null)
            {
                return jt.ToObject<T>();
            }
            else
            {
                Global.writeLog(destPath + "的JToken属性值为空");
                return default;
            }
        }


        public static string getDestProperty(JObject jo, string propertyName)
        {
            JProperty jp = jo.Property(propertyName);
            if (jp != null)
            {
                string jpStr = jp.ToString();
                string rtnResult = "{ " + jpStr + "}";
                return rtnResult;
            }
            else
            {
                Global.writeLog(propertyName + "的JProperty属性值为空");
                return "";
            }
            
        }
        /// <summary>
        /// 压缩JSON，占用体积减小(重载)
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string Compress(string json)
  {
      StringBuilder sb = new StringBuilder();
      using (StringReader reader = new StringReader(json))
      {
          int ch = -1;
          int lastch = -1;
         bool isQuoteStart = false;
          while ((ch = reader.Read()) > -1)
         {
             if ((char) lastch != '\\' && (char) ch == '\"')
             {
                 if (!isQuoteStart)
                 {
                     isQuoteStart = true;
                 }
                 else
                 {
                     isQuoteStart = false;
                 }
             }
             if (!Char.IsWhiteSpace((char) ch) || isQuoteStart)
             {
                 sb.Append((char) ch);
             }
             lastch = ch;
         }
     }
     return sb.ToString();
 }
        public static string Compress(JObject jsonObj)
        {
            //https://blog.csdn.net/yangjiaosun/article/details/103717256
            return Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
        }

        /// <summary>
        /// 组织异常JSON串
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public static JObject setExceptionJson(int errorCode, string eventName, string errorMessage)
        {
            dynamic joRtn = new JObject();
            joRtn.errorCode = errorCode;
            joRtn.errorMessage = eventName + "提示：" + errorMessage;
            return joRtn;
        }

        /// <summary>
        /// 组织中心入参(明文)。部分代码是需要解析明文入参的，为了方便增加该方法
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setCenterInpar_plain(string infno, string input)
        {
            return setCenterInpar_plain(infno, (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(input));
        }

        /// <summary>
        /// 组织中心入参(明文)。部分代码是需要解析明文入参的，为了方便增加该方法
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setCenterInpar_plain(string infno, JObject joInput)
        {
            dynamic Jo = new JObject();
            Jo.infno = infno;
            Global.curEvt.msgid = Global.inf.hospitalNO + DateTime.Now.ToString("yyyyMMddHHmmssffff");
            Jo.msgid = Global.curEvt.msgid;
            Jo.mdtrtarea_admvs = Global.inf.areaCode;
            Global.pat.mdtrtarea_admvs = Jo.mdtrtarea_admvs;
            Jo.insuplc_admdvs = Global.pat.insuplc_admdvs;
            Jo.recer_sys_code = Global.inf.recivedSystem;
            Jo.dev_no = Global.inf.dev_no;
            Jo.dev_safe_info = Global.inf.dev_safe_info; //设备编号
            Jo.cainfo = Global.inf.cainfo;//设备安全信息
            Jo.signtype = Global.inf.signatureType; ;
            Jo.infver = Global.inf.version; ;
            Jo.opter_type = Global.user.type; ;
            Jo.opter = Global.user.ID; ;
            Jo.opter_name = Global.user.name; ;
            Jo.inf_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Jo.fixmedins_code = Global.inf.hospitalNO;
            Jo.fixmedins_name = Global.inf.hospitalName;
            Jo.sign_no = Global.curEvt.signno;
            Jo.enc_type = "";

            Jo.Add("input", joInput);

            var request = Utils.Wrapper(Jo);

            return request.ToString();
        }

        /// <summary>
        /// 组织中心入参
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setCenterInpar(string infno, string input)
        {

            JObject joInput = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(input);
            return setCenterInpar(infno, joInput);
        }

        /// <summary>
        /// 移动支付组织中心入参
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setMPCenterInpar(string infno, string txtData)
        {
            EncryptHelper encrypt = new EncryptHelper(Global.inf.MobilePay.appid, Global.inf.MobilePay.secretKey, Global.inf.MobilePay.publicKey, Global.inf.MobilePay.privateKey);
            string plainText = SignUtil.SortInput(JObject.Parse(txtData));
            string signData = "";
            string output = encrypt.encrypt(txtData, ref signData);
            return output;
        }

        public static string setMPCenterInpar(string infno, JObject joInput)
        {
            return setMPCenterInpar(infno, joInput.ToString());
        }
        /// <summary>
        /// 组织中心入参
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setCenterInpar(string infno, JObject joInput)
        {
            Global.writeLog("setCenterInpar1");
            dynamic Jo = new JObject();
            Jo.infno = infno;
            Global.curEvt.msgid = Global.inf.hospitalNO + DateTime.Now.ToString("yyyyMMddHHmmssffff");
            Jo.msgid = Global.curEvt.msgid;
            Global.pat.mdtrtarea_admvs = Global.inf.areaCode;

            // 参保地
            Jo.insuplc_admdvs = Global.pat.insuplc_admdvs;
            // 就医地
            Jo.mdtrtarea_admvs = Global.pat.mdtrtarea_admvs;

            if (Global.pat.isWorkInjury)
            {
                Jo.recer_sys_code = "GGS";
            }
            else
            {
                Jo.recer_sys_code = "YBXT";
            }
            
            Jo.dev_no = "2021";
            Jo.dev_safe_info = Global.inf.dev_safe_info; //设备编号
            Jo.signtype = "SM2"; ;
            Jo.infver = "v1.0";
            Jo.opter_type = Global.user.type; ;
            Jo.opter = Global.user.ID; ;
            Jo.opter_name = Global.user.name; ;
            Jo.inf_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Jo.fixmedins_code = Global.inf.hospitalNO;
            Jo.fixmedins_name = Global.inf.hospitalName;
            Jo.sign_no = Global.curEvt.signno;
            //Jo.app_id = "";
            Jo.enc_type = "";
            //Jo.pw_ecToken = "";

            // 报文签名(不包含cainfo和input)
            //EncryptHelper encrypt = new EncryptHelper();
            Jo.cainfo = ""; // encrypt.signWithSM2(Jo);
            // 服务商信息
            Jo.serv_code = "HH00029";
            Jo.serv_sign = "0C9BC4D70BDE653D8E";
            Global.writeLog("setCenterInpar2");
            if (joInput != null)
            {
                Jo.Add("input", joInput);
            }
            else
            {
                Jo.Add("input", "");
            }
            Global.writeLog("setCenterInpar3");
            // 下载不需要wrapper
            if ("9102".Equals(infno))
            { 
                return JsonHelper.toJsonString(Jo);
            }

            var request = Utils.Wrapper(Jo);
            Global.writeLog("setCenterInpar4");
            return JsonHelper.toJsonString(request);
            
        }

        /// <summary>
        /// 组织Iris入参
        /// </summary>
        /// <param name="code"></param>
        /// <param name="joParam"></param>
        /// <returns></returns>
        public static JObject setIrisInpar(string code, JObject joParam)
        {
            try
            {
                dynamic joInparam = new JObject();
                joInparam.code = code;
                JArray jaParam = new JArray();
                //// 去掉包装
                //JObject joInput = Utils.removeWrapper(joParam);
                jaParam.Add(joParam);
                joInparam.Add("HospitalDr", Global.inf.hospitalDr);
                joInparam.Add("InterfaceDr", Global.inf.interfaceDr);
                joInparam.Add("params", JArray.FromObject(jaParam));
                joInparam.Add("session", Global.curEvt.jaSession);
                return joInparam;
            }
            catch (Exception ex)
            {
                return setExceptionJson(-1, "setIrisInpar:", ex.Message);
            }

        }

        /// <summary>
        /// 组织Iris入参
        /// </summary>
        /// <param name="code"></param>
        /// <param name="joParam"></param>
        /// <returns></returns>
        public static JObject setIrisInpar(string code, JArray jaParams)
        {
            try
            {
                dynamic joInparam = new JObject();
                joInparam.code = code;
                dynamic joTmp = new JObject();
                joInparam.Add("HospitalDr", Global.inf.hospitalDr);
                joInparam.Add("InterfaceDr", Global.inf.interfaceDr);
                joInparam.Add("params", jaParams);
                joInparam.Add("session", Global.curEvt.jaSession);
                return joInparam;
            }
            catch (Exception ex)
            {
                return setExceptionJson(-1, "setIrisInpar:", ex.Message);
            }

        }

        /// <summary>
        /// 解析中心返参
        /// </summary>
        /// <param name="joRtn"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static int parseCenterRtnValue(JObject joRtn,  out string errorMsg)
        {
            try
            {
                string code = getDestValue(joRtn, "code");
                string errcode = getDestValue(joRtn, "errcode");
                string errorCode = getDestValue(joRtn, "errorCode");
                if (code != "")
                {
                    errorMsg = getDestValue(joRtn, "message");
                    return -1;
                }
                else if (errcode != "")
                {
                    errorMsg = getDestValue(joRtn, "errmsg");
                    return -1;
                }
                else if (errorCode != "")
                {
                    errorMsg = getDestValue(joRtn, "errorMessage");
                    return -2;
                }
                else
                {
                    errorMsg = getDestValue(joRtn, "err_msg");
                    return int.Parse(getDestValue(joRtn, "infcode"));
                }
            }
            catch (Exception ex)
            {
                errorMsg = "解析中心返参发生异常：" + ex.Message;
                return -1;
            }
        }


        /// <summary>
        /// 解析Com反参
        /// </summary>
        /// <param name="joRtn"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static int parseComRtnValue(JObject joRtn, out string errorMsg)
        {
            try
            {
                string code = getDestValue(joRtn, "code");
                errorMsg = getDestValue(joRtn, "message");

                if (code != "0")
                {
                    return -1;
                }
                else
                    return 0;
            }
            catch (Exception ex)
            {
                errorMsg = "解析中心返参发生异常：" + ex.Message;
                return -1;
            }
        }
        /// <summary>
        /// 解析移动返参
        /// </summary>
        /// <param name="joRtn"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static int parseMPRtnValue(JObject joRtn, out string errorMsg)
        {
            try
            {
                string success = getDestValue(joRtn, "success");
                string message = getDestValue(joRtn, "message");
                string encData = getDestValue(joRtn, "encData");
                //Global.writeLog("success:" + success);
                if (success != "True")
                {
                    errorMsg = message;
                    return -1;
                }
                else
                {
                    errorMsg = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                errorMsg = "解析中心返参发生异常：" + ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 组织IRIS返参
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="errorMessage"></param>
        /// <param name="joResult"></param>
        /// <returns></returns>
        public static JObject setIrisReturnValue(int errorCode, string errorMessage, JObject joResult)
        {
            try
            {
                dynamic joRtn = new JObject();
                joRtn.errorCode = errorCode;
                joRtn.errorMessage = errorMessage;
                joRtn.Add("result", joResult);
                return joRtn;
            }
            catch (Exception ex)
            {
                return setExceptionJson(-1, "setIrisReturnValue:", ex.Message);
            }
        }

        /// <summary>
        /// 解析IRIS返参
        /// </summary>
        /// <param name="joRtn"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        /// 
        public static int parseIrisRtnValue(JObject joRtn, out string errorMsg)
        {
            try
            {
                errorMsg = getDestValue(joRtn, "errorMessage");
                return int.Parse(getDestValue(joRtn, "errorCode"));
            }
            catch (Exception ex)
            {
                errorMsg = "解析Iris返参发生异常：" + ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 解析业务JSON串（业务串固定格式为{errorCode = ,errorMessage = ,result ={}}）
        /// </summary>
        /// <param name="json"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static int parseCenterReturnJson(JObject json, out string errorMsg)
        {
            try
            {
                errorMsg = "";
                if (int.Parse(json["infcode"].ToString()) != 0)
                {
                    errorMsg = json["err_msg"].ToString();
                }
                return int.Parse(json["infcode"].ToString());
            }
            catch (Exception ex)
            {
                errorMsg = "parseCenterReturnJson" + ex.Message;
                return -1;
            }

        }

        #region 处方流转


        /// <summary>
        /// 组织中心入参-医保电子处方流转
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setCenterInparPresCirNew(JObject data)
        {
            #region【测试环境】

            ////应用ID
            //Global.inf.appId = "990844B1397C413788D75B3D3712E5F9"; 
            ////Global.inf.appId = "57E2D561E97141A3871DEFB410ADD920"; 
            ////应用秘钥
            //Global.inf.Secret = "6F11A0DAD7D94E84A8B9CD52D21D7B8F";
            ////Global.inf.Secret = "F30D0D261BA04063A0BCAEF19F8ADBCC";
            ////应用私钥
            //Global.inf.privateKey = "NCYs1ddhvyJtv6mdcihqfIkNDYvy+3Di3Q2Wv8Mgp24=";    //中心邮件下发 
            ////Global.inf.privateKey = "AKyhfvPbT+tIJHJkZSDILrw7t+FOG1U58UcupYYTzCOj";  //中心Demo
            ////应用公钥
            ////Global.inf.publicKey = "BKRejz4MwM8G8Krc4hyIIvhphvwrQpnHIsGWTd0sn0TJYr2eKJGAv87AKnrT8pL50H6hdVHdU0FFaL18GApDEbU"; //中心邮件下发
            //Global.inf.publicKey = "BFZ3xSMqfiNS1KBnQZ2czC7jpxKSvK7iYbinUlnozhpcf/OX7SRm8bKNuR8MGp6izCt9YVp1DpjcCYy95S1qSPY=";  //中心Demo

            ////Global.inf.cardURL = "http://10.126.105.66/hsa-hgs-adapt/api/card/initDll";   //测试环境
            //Global.inf.presCenterURL = "http://10.139.33.68:8080/epc/api";

            #endregion

            #region【正式环境】
            //if (Global.inf.interfaceDr == 21) //兰2
            //{
            //    //应用ID
            //    Global.inf.appId = "4D967CAB5DA44E3583F4246D7FE897F0";
            //    //应用秘钥
            //    Global.inf.Secret = "586BD24D03E5481C8AE4FE9DD8424FFE";
            //    //应用私钥
            //    Global.inf.privateKey = "XTbX+Tt1np5Fma0+twhYi+vtM4J0UJ8VX5fFEZ7t/ro=";
            //    //应用公钥            
            //    Global.inf.publicKey = "BIFd2+2CgjuPAj5FMj5L/L3azTWu86suPtlIJkCo8zjQ44R7SQUUkTgZGdVelRQCM5pW+x9tZGzDPaUNbfD499w=";
            //}
            //else if (Global.inf.interfaceDr == 25) //兰1
            //{
            //    //应用ID
            //    Global.inf.appId = "6C9B786AF7E848B29B0EF5783D630263";
            //    //应用秘钥
            //    Global.inf.Secret = "6055AE5A9CAD4D9BA8A98EB20431364E";
            //    //应用私钥
            //    Global.inf.privateKey = "AKReZmOYcTOdbrnlZZFIXn8LQSHPzdAK1Q0CXDnE4Jhk";
            //    //应用公钥            
            //    Global.inf.publicKey = "BIFd2+2CgjuPAj5FMj5L/L3azTWu86suPtlIJkCo8zjQ44R7SQUUkTgZGdVelRQCM5pW+x9tZGzDPaUNbfD499w=";
            //}

            //Global.inf.presCenterURL = "http://10.126.34.36:8080/epc/api";
            //Global.inf.presCenterURL = "http://10.139.33.68:8080/epc/api";
            //Global.inf.presCenterURL = "http://10.139.97.79:80/epc/api";
            #endregion

            Global.writeLog("密钥id：" + Global.inf.PresCir.appid);
            Global.writeLog("密钥key：" + Global.inf.PresCir.secretKey);
            Global.writeLog("定点医药机构私钥：" + Global.inf.PresCir.privateKey);
            Global.writeLog("医保电子处方中心公钥：" + Global.inf.PresCir.publicKey);

            //Global.curEvt.msgid = Global.inf.hospitalNO + DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string timestamp = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds).ToString();
            Global.curEvt.msgid = timestamp;

            JObject requestData = new JObject();
            requestData.Add("appId", Global.inf.PresCir.appid);
            requestData.Add("version", "1.0.0");
            requestData.Add("encType", "SM4");
            requestData.Add("signType", "SM2");
            requestData.Add("timestamp", timestamp);

            Global.writeLog("加密前入参:" + data.ToString());
            //加密
            String encData = SMUtil.encrypt(JsonConvert.SerializeObject(data, Formatting.None), Global.inf.PresCir.appid, Global.inf.PresCir.secretKey);
            //Global.writeLog("入参加密前：" + "\r\n" + JsonConvert.DeserializeObject(data.ToString()) + "\r\n" + "入参加密后：" + "\r\n" + encData);

            JObject signDto = (JObject)JObject.Parse(JsonConvert.SerializeObject(requestData, Formatting.None));
            signDto.Add("data", data);

            //加签
            String signData = SMUtil.sign(signDto, Global.inf.PresCir.secretKey, Global.inf.PresCir.privateKey);
            Global.writeLog("签名结果：" + "\r\n" + signData);

            //报文
            requestData.Add("encData", encData);
            requestData.Add("signData", signData);

            dynamic Jo = new JObject();
            Jo.appId = Global.inf.PresCir.appid;
            //Jo.version = "2.0.1";
            Jo.timestamp = timestamp;
            Jo.encType = "SM4";
            Jo.signType = "SM2";
            Jo.signData = signDto.ToString();
            Jo.encData = data.ToString();
            Global.writeLog(data.ToString());
            Global.writeLog("加密前报文：" + "\r\n" + Jo.ToString() + "\r\n" + "加密后报文：" + "\r\n" + JsonConvert.SerializeObject(requestData, Formatting.None));

            //本地解密
            //String decData = SMUtil.decrypt(encData, Global.inf.appId, Global.inf.Secret);
            //Global.writeLog("解密：" + decData);
            //使用应用公钥（publicKey示例默认值）对本地自签名的数据进行验签示例
            //Boolean isVerify = SMUtil.verify(signDto, Global.inf.Secret, Global.inf.publicKey, signData);
            //Global.writeLog("验签：" + isVerify);

            return requestData.ToString();
        }

        /// <summary>
        /// 解析中心返参
        /// </summary>
        /// <param name="joRtn"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static int parseCenterRtnValuePresCir(JObject joRtn, out string errorMsg)
        {
            try
            {
                string errcode = getDestValue(joRtn, "errcode");
                string errorCode = getDestValue(joRtn, "errorCode");
                if (errcode != "")
                {
                    errorMsg = getDestValue(joRtn, "message");
                    return -1;
                }
                else if (errorCode != "")
                {
                    errorMsg = getDestValue(joRtn, "errorMessage");
                    return -2;
                }
                else
                {
                    errorMsg = getDestValue(joRtn, "message");
                    return int.Parse(getDestValue(joRtn, "code"));
                }
            }
            catch (Exception ex)
            {
                errorMsg = "解析中心返参发生异常：" + ex.Message;
                return -1;
            }
        }
        #endregion

        #region 一码付入参
        /// <summary>
        /// 一码付组织中心入参
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setOneCodePayInpar(string jsonStr)
        {
            if (string.IsNullOrWhiteSpace(jsonStr))
                throw new ArgumentException("输入的 JSON 字符串不能为空", nameof(jsonStr));

            // 1. 获取时间戳
            string timestamp = SignUtils.CurrentTimeStamp().ToString();

            // 2. 若不确定，可在此处压缩：
            var compactJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(jsonStr), Formatting.None);
            string encData = OneCodePayEncryptUtil.encrypt(compactJson, Global.inf.oneCodePay.businessSystemKey);

            // 3. 构建外层请求对象
            var request = new JObject
            {
                ["reqtType"] = "sys&350000",
                ["encData"] = encData,
                ["orgId"] = "hnddyyjgxxxt",
                ["timestamp"] = timestamp,
                ["version"] = "1.0.0"
            };

            // 4. 输出紧凑 JSON（医保接口要求无空格）
            return request.ToString(Formatting.None);
        }

        public static string setOneCodePayInpar(JObject joInput)
        {
            return setOneCodePayInpar(joInput.ToString());
        }

        /// <summary>
        /// 解析一码付返参
        /// </summary>
        /// <param name="joRtn"></param>
        /// <param name="errorMsg"></param>
        /// {
        ///	"code": 0,
        ///	"type": "success",
        ///	"message": "成功",
        ///	"data": {
        ///		"encData": "FD2C1AB3770A04FC7C833D52F2559D6DD8544BC9A6E677D474BF5FE8104B51E2EE106024829CE4765EAAEAF413EEE62F69A15618D90BB90145BA86367EA8F"
        ///	}
        //}
        /// <returns></returns>
        public static int parseOneCodePayRtnValue(JObject joRtn, out string errorMsg)
        {
            try
            {
                string type = getDestValue(joRtn, "type");
                string code = getDestValue(joRtn, "code");
                string message = getDestValue(joRtn, "message");
                string encData = getDestValue(joRtn, "data.encData");
                if (code != "0")
                {
                    errorMsg = message;
                    return -1;
                }
                else
                {
                    errorMsg = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                errorMsg = "解析中心返参发生异常：" + ex.Message;
                return -1;
            }

        }
        #endregion
    }
}
