using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;

namespace Mall.Common.Plugin
{
    public class WeiXinHelper
    {

        /// <summary>
        /// 获取微信用户OpenId
        /// </summary>
        /// <param name="AppId"></param>
        /// <param name="AppSecret"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static string GetWeChatOpenId(string AppId, string AppSecret, string Code)
        {
            string result = "";
            string openid = "";
            try
            {
                //请求路径
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + AppSecret + "&js_code=" + Code + "&grant_type=authorization_code";
                result= Common.Plugin.HttpHelper.HttpGet(url);
                if (result != null && !string.IsNullOrEmpty(result))
                {
                    JObject jObj = JObject.Parse(result);
                    openid = jObj["openid"].ToString();
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetWeChatOpenId:result="+ result);
            }
            return openid;
        }
    }

    /// <summary>
    /// 获取用心信息帮助类
    /// </summary>
    public class GetUsersHelper
    {

        /// <summary> 
        /// 获取链接返回数据 
        /// </summary> 
        /// <param name="Url">链接</param> 
        /// <param name="type">请求类型</param> 
        /// <returns></returns> 
        public string GetUrltoHtml(string Url, string type)
        {
            try
            {
                System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
                // Get the response instance. 
                System.Net.WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();
                // Dim reader As StreamReader = New StreamReader(respStream) 
                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }
    }

    #region 实体类
    /// <summary>  
    /// 微信小程序验证返回结果  
    /// </summary>  
    public class result
    {
        /// <summary>
        /// openid
        /// </summary>
        public string openid { get; set; }

        /// <summary>
        /// session_key
        /// </summary>
        public string session_key { get; set; }

        /// <summary>
        /// 错误状态码
        /// </summary>
        public string errcode { get; set; }

        /// <summary>
        /// 错误提示信息
        /// </summary>
        public string errmsg { get; set; }
    }
    #endregion







    public class WxPayData
    {
        public const string SIGN_TYPE_MD5 = "MD5";
        public const string SIGN_TYPE_HMAC_SHA256 = "HMAC-SHA256";
        public WxPayData()
        {

        }

        //采用排序的Dictionary的好处是方便对数据包进行签名，不用再签名之前再做一次排序
        private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();

        /**
        * 设置某个字段的值
        * @param key 字段名
         * @param value 字段值
        */
        public void SetValue(string key, object value)
        {
            m_values[key] = value;
        }

        /**
        * 根据字段名获取某个字段的值
        * @param key 字段名
         * @return key对应的字段值
        */
        public object GetValue(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            return o;
        }

        /**
         * 判断某个字段是否已设置
         * @param key 字段名
         * @return 若字段key已被设置，则返回true，否则返回false
         */
        public bool IsSet(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            if (null != o)
                return true;
            else
                return false;
        }

        /**
        * @将Dictionary转成xml
        * @return 经转换得到的xml串
        * @throws WxPayException
        **/
        public string ToXml()
        {
            //数据为空时不能转化为xml格式
            if (0 == m_values.Count)
            {
                //_logger.LogError(this.GetType().ToString(), "WxPayData数据为空!");
                throw new Exception("WxPayData数据为空!");
            }

            string xml = "<xml>";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                //字段值不能为null，会影响后续流程
                if (pair.Value == null)
                {
                    //_logger.LogError(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
                    throw new Exception("WxPayData内部含有值为null的字段!");
                }

                if (pair.Value.GetType() == typeof(int))
                {
                    xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
                }
                else if (pair.Value.GetType() == typeof(string))
                {
                    xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
                }
                else//除了string和int类型不能含有其他数据类型
                {
                    //_logger.LogError(this.GetType().ToString(), "WxPayData字段数据类型错误!");
                    throw new Exception("WxPayData字段数据类型错误!");
                }
            }
            xml += "</xml>";
            return xml;
        }



        public SortedDictionary<string, object> NoSignFromXml(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                //_logger.LogError(this.GetType().ToString(), "将空的xml串转换为WxPayData不合法!");
                throw new Exception("将空的xml串转换为WxPayData不合法!");
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
            }

            return m_values;
        }

        /**
        * @Dictionary格式转化成url参数格式
        * @ return url格式串, 该串不包含sign字段值
        */
        public string ToUrl()
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value == null)
                {
                    //_logger.LogError(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
                    throw new Exception("WxPayData内部含有值为null的字段!");
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    buff += pair.Key + "=" + pair.Value + "&";
                }
            }
            buff = buff.Trim('&');
            return buff;
        }



        public bool CheckSign()
        {
            ////如果没有设置签名，则跳过检测
            //if (!IsSet("sign"))
            //{
            //    //_logger.LogError(this.GetType().ToString(), "WxPayData签名存在但不合法!");
            //    throw new Exception("WxPayData签名存在但不合法!");
            //}
            ////如果设置了签名但是签名为空，则抛异常
            //else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            //{
            //    //_logger.LogError(this.GetType().ToString(), "WxPayData签名存在但不合法!");
            //    throw new Exception("WxPayData签名存在但不合法!");
            //}

            ////获取接收到的签名
            //string return_sign = GetValue("sign").ToString();

            ////在本地计算新的签名
            //string cal_sign = payReq.CreateMd5Sign(_accessor, model.WeChatApiSecret);
            return true;
            //if (cal_sign == return_sign)
            //{
            //    return true;
            //}

            //_logger.LogError(this.GetType().ToString(), "WxPayData签名验证错误!");
            throw new Exception("WxPayData签名验证错误!");
        }
    }
}
