using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;

namespace New_College.Common
{
    public class WeixinHelper
    {
        /// <summary>
        /// 获取AuthCodeSession
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static T AuthCode2Session<T>(string appid, string secret, string code) where T :new()
        {
            var authinfo = new T();
            try
            {

                string requestUri = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", appid, secret, code); ;
                var httpClientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
                };

                using (HttpClient httpClient = new HttpClient(httpClientHandler))
                {
                    var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
                    var obj = JsonConvert.DeserializeObject<T>(responseStr);
                    return obj;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /**
    * 
    * 统一下单
    * @param WxPaydata inputObj 提交给统一下单API的参数
    * @param int timeOut 超时时间
    * @throws WePayException
    * @return 成功时返回，其他抛异常
    */
        public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 60)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //检测必填参数
            if (!inputObj.IsSet("out_trade_no"))
            {
                throw new Exception("缺少统一支付接口必填参数out_trade_no！");
            }
            else if (!inputObj.IsSet("body"))
            {
                throw new Exception("缺少统一支付接口必填参数body！");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new Exception("缺少统一支付接口必填参数total_fee！");
            }
            else if (!inputObj.IsSet("trade_type"))
            {
                throw new Exception("缺少统一支付接口必填参数trade_type！");
            }

            //关联参数
            if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
            {
                throw new Exception("统一支付接口中，缺少必填参数openid！trade_type为JSAPI时，openid为必填参数！");
            }
            if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
            {
                throw new Exception("统一支付接口中，缺少必填参数product_id！trade_type为JSAPI时，product_id为必填参数！");
            }

            //异步通知url未设置，则使用配置文件中的url
            if (!inputObj.IsSet("notify_url"))
            {
                inputObj.SetValue("notify_url", WeixinConfig.NotifyUrl);//异步通知url
            }

            inputObj.SetValue("appid", WeixinConfig.Appid);//公众账号ID
            inputObj.SetValue("mch_id", WeixinConfig.MCHID);//商户号
            inputObj.SetValue("spbill_create_ip", "8.8.8.8");//终端ip              
            inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串

            //签名
            inputObj.SetValue("sign", inputObj.MakeSign());
            string xml = inputObj.ToXml();

            var start = DateTime.Now;

            // Log.Info("XcxPayApi", "UnfiedOrder request : " + xml);
            string response = HttpPost(xml, url, "application/xml", timeOut);
            //Log.Info("XcxPayApi", "UnfiedOrder response : " + response);
            // WebHookHelper.WebHookmarkdownSend(response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();
            result.FromXml(response);
            //  ReportCostTime(url, timeCost, result);//测速上报网络不好时使用
            return result;
        }


        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <returns></returns>
        public static string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }


        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="postData"></param>
        /// <param name="url"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="timeOut"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static string HttpPost(string postData, string url, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";

            var httpClientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
            };
            using (HttpClient httpClient = new HttpClient(httpClientHandler))
            {
                if (headers != null)
                {
                    foreach (var header in headers)
                        httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent client = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        client.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = httpClient.PostAsync(url, client).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
        }




        /// <summary>
        /// 后台解密手机号
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="IV"></param>
        /// <param name="Session_key"></param>
        /// <returns></returns>
        public static string getPhoneNumber(string encryptedData, string IV, string Session_key)
        {
            try
            {

                byte[] encryData = Convert.FromBase64String(encryptedData);  // strToToHexByte(text);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(Session_key); // Encoding.UTF8.GetBytes(AesKey);
                rijndaelCipher.IV = Convert.FromBase64String(IV);// Encoding.UTF8.GetBytes(AesIV);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);
                //动态解析result 成对象
                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                return model.phoneNumber;

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                return "";

            }
        }

    }



}
