using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.Extension;
using Hncore.Pass.PaymentCenter.Model;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using XC.RSAUtil;

namespace Hncore.Pass.PaymentCenter.WeiFuTong
{
    public class Util
    {
        public static void CheckSignFromXml(string xmlText, MchInfo mchInfo)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = null;
            xmlDoc.LoadXml(xmlText);
            XmlNode root = xmlDoc.SelectSingleNode("xml");
            XmlNodeList xnl = root.ChildNodes;

            if (root.SelectSingleNode("status") == null || root.SelectSingleNode("status").InnerText != "0")
            {
                return;
            }

            SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
            string responseSign = "";
            string signType = "MD5";


            foreach (XmlNode xnf in xnl)
            {
                var parameter = xnf.Name;
                var parameterValue = xnf.InnerText;

                if (parameter == "sign")
                {
                    responseSign = parameterValue;
                }

                if (parameter == "sign_type")
                {
                    signType = parameterValue;
                }

                if (parameter.Has() && parameterValue.Has() && parameter != "sign")
                {
                    if (dic.Keys.Contains(parameter))
                    {
                        dic.Remove(parameter);
                    }

                    dic.Add(parameter, parameterValue);
                }
            }

            string sign = "";

            foreach (var item in dic)
            {
                sign += item.Key + "=" + item.Value + "&";
            }


            if (signType == "MD5" || string.IsNullOrEmpty(signType))
            {
                sign += "key=" + mchInfo.Key;
                sign = SecurityHelper.GetMd5Hash(sign).ToUpper();

                if (responseSign.ToUpper() != sign)
                {
                    BusinessException.Throw("验签失败");
                }
            }
            else if (signType == "RSA_1_1")
            {
                sign = sign.Substring(0, sign.Length - 1);

                var verify = new RsaPkcs8Util(Encoding.UTF8
                        , mchInfo.RSAPublicKey
                        , mchInfo.RSAPrivateKey)
                    .VerifyData(sign, responseSign, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

                if (!verify)
                {
                    BusinessException.Throw("验签失败");
                }
            }
            else
            {
                BusinessException.Throw("未知签名方式");
            }
        }
        
      
    }
}