/******************************************************************************
  * 文件名称: 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.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PTMedicalInsurance.Common;
using System.IO;
using PTMedicalInsurance.Variables;
using Newtonsoft.Json;
using AnHuiMI.Common;
using GMCrypto.Lib;

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 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 "";
            }
        }


        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, JObject joInput)
        {
            return setMPCenterInpar(infno, joInput.ToString());
        }

        

        public static string setMPCenterInpar(string infno, string txtData)
        {
            EncryptHelper encrypt = new EncryptHelper();

            string plainText = SignUtil.SortInput(JObject.Parse(txtData));

            Global.writeLog(infno + "【明文入参】:\r\n" + plainText);

            string signData = "";


            string output = encrypt.encrypt(txtData, ref signData);

            Global.writeLog(infno + "【密文入参】:\r\n" + output);

            return output;
        }

        /// <summary>
        /// 组织中心入参
        /// </summary>
        /// <param name="infno"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string setCenterInpar(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;

            if (string.IsNullOrEmpty(Global.pat.insuplc_admdvs))
            {
                Global.pat.insuplc_admdvs = Global.inf.areaCode;
            }

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


            //if(Global.pat.insuplc_admdvs == "340001"&& infno=="1101"&& Global.inf.interfaceDr==12)
            //{
            //    Jo.insuplc_admdvs = "349900";
            //}

            Jo.recer_sys_code = "MBS_LOCAL";
            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; ;
            if(Global.inf.interfaceDr == 12)//安徽省基线版-瑶海
            {
                Jo.opter = "A05CA9455BE8BF66";
            }
            if (Global.inf.interfaceDr == 16)//合肥市基线版-瑶海
            {
                Jo.opter = "7571C4995A2F4290";
            }
            if (Global.inf.interfaceDr == 15)//安徽省基线版-蜀山老院
            {
                Jo.opter = "48664E4455CC0F8F";
            }
            if (Global.inf.interfaceDr == 17)//合肥市基线版-蜀山老院
            {
                Jo.opter = "4D91C975CF902EB2";
            }

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


            if (joInput != null)
            {
                Jo.Add("input", joInput);
            }
            else
            {
                Jo.Add("input", "");
            }
            // 下载不需要wrapper
            if ("9102".Equals(infno))
            { 
                return JsonHelper.toJsonString(Jo);
            }

            var request = Utils.Wrapper(Jo);

            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;
                dynamic joTmp = new JObject();

                JArray jaParam = new JArray();
                // 去掉包装
                JObject joInput = Utils.removeWrapper(joParam);
                jaParam.Add(joInput);

                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("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 errcode = getDestValue(joRtn, "errcode");
                string errorCode = getDestValue(joRtn, "errorCode");
                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>
        /// 解析移动返参
        /// </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");
                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;
            }

        }
    }
}
