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

namespace Edu.Common.Plugin
{
    /// <summary>
    /// 微信帮助类
    /// </summary>
    public class WeChatHelper
    {
        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="AppSecret"></param>
        /// <returns></returns>
        public static string GetAccessToken(string AppID, string AppSecret)
        {
            string token = string.Empty;
            try
            {
                string wechatapi = Config.WechatApi;
                string appID = AppID;
                string appSecret = AppSecret;
                //获取微信token
                string token_url = wechatapi + "cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(token_url);
                //请求方式
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                myResponse.Close();
                reader.Dispose();
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                token = jo["access_token"].ToString();
            }
            catch (Exception ex)
            {
                token = "";
                Common.Plugin.LogHelper.Write(ex, "GetAccessToken");
            }
            return token;
        }


        /// <summary>
        /// 生成小程序码
        /// </summary>
        /// <param name="token"></param>
        /// <param name="url">跳转地址</param>
        /// <param name="width">宽度</param>
        /// <returns></returns>
        public static string GetWeChatQRCode(string token, string url, int width)
        {
            string result = "";
            string tempPath = "\\upfile\\temporary\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
            string basepath = AppContext.BaseDirectory + tempPath;
            string fileName = DateTime.Now.Ticks + ".jpg";
            if (!Directory.Exists(basepath))
            {
                Directory.CreateDirectory(basepath);
            }
            if (!string.IsNullOrEmpty(token))
            {
                //获取小程序码
                string apiurl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;
                var postData = new
                {
                    path = url,
                    width
                };
                var Robj = HttpHelper.HttpPostImageToBase64(apiurl, JsonHelper.Serialize(postData), path: basepath + fileName, resultType: 0);
                result = "/upfile/temporary/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName;
            }
            return result;
        }




        /// <summary>
        /// 获取微信用户OpenId
        /// </summary>
        /// <param name="AppId"></param>
        /// <param name="AppSecret"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static result GetWeChatOpenId(string AppId, string AppSecret, string Code)
        {
            // string result = "";
            result userInfo = new result();
            string resultInfo = "";

            try
            {
                //请求路径
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + AppSecret + "&js_code=" + Code + "&grant_type=authorization_code";
                resultInfo = Common.Plugin.HttpHelper.HttpGet(url);
                if (resultInfo != null && !string.IsNullOrEmpty(resultInfo))
                {
                    userInfo = JsonConvert.DeserializeObject<result>(resultInfo);
                }
            }
            catch (Exception ex)
            {
                //GetWeChatOpenId:result={"errcode":40163,"errmsg":"code been used, hints: [ req_id: AHGbGiqNe-OhJh.a ]"}&&Code=051S1Ykl2wYCF64U7gnl2AK6ga0S1Yk2
                //Code过期
                Common.Plugin.LogHelper.Write(ex, string.Format("GetWeChatOpenId:result={0}&&Code={1}", resultInfo, Code));

            }
            return userInfo;
        }

        /// <summary>
        /// 获取微信授权手机号码
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="code"></param>
        /// <param name="ivStr"></param>
        /// <returns></returns>
        public static result GetWechatMobile(string encryptedData, string code, string iv)
        {
            string Appid = Common.Config.JiaXiaoHeAppId;
            var Secret = Common.Config.JiaXiaoHeAppSecret;
            string grant_type = "authorization_code";
            //向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
            string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type;
            string type = "utf-8";
            GetUsersHelper GetUsersHelper = new GetUsersHelper();
            result res = new Common.Plugin.result();
            string j = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串                                              
            //将字符串转换为json格式 
            JObject jo = JObject.Parse(j);
            //微信服务器验证成功 
            res.openid = jo.GetStringValue("openid");
            res.session_key = jo.GetStringValue("session_key");
            res.unionid = jo.GetStringValue("unionid");
            if (!string.IsNullOrWhiteSpace(res.openid))
            {
                if (!string.IsNullOrEmpty(encryptedData) && !string.IsNullOrEmpty(iv))
                {
                    //解析手机号码
                    res.phoneNumber = Common.EncryptionHelper.AES_decrypt(encryptedData, res.session_key, iv);
                }
            }
            return res;
        }
    }


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


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

        /// <summary>
        /// openid
        /// </summary>
        public string unionid { 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; }

        /// <summary>
        /// 电话号码
        /// </summary>
        public string phoneNumber { get; set; }
    }

}