using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace NetPanel.Help
{
    public class MyController : Controller
    {
        /// <summary>
        /// 是否 get
        /// </summary>
        public bool IsHttpGet
        {
            get { return Request.Method == "GET"; }
        }

        /// <summary>
        /// 是否 post
        /// </summary>
        public bool IsHttpPost
        {
            get { return Request.Method == "POST"; }
        }


        /// <summary>
        /// 获取get 参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetQuery<T>(string key)
        {
            try
            {
                if (Request.Query.ContainsKey(key))
                {
                    //一般类型
                    return (T)Convert.ChangeType(Request.Query[key].FirstOrDefault(), typeof(T));
                }
                else
                {
                    return default(T);
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
        /// <summary>
        /// 获取post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetForm<T>(string key)
        {
            try
            {
                if (Request.Form.ContainsKey(key))
                {
                    //一般类型
                    return (T)Convert.ChangeType(HttpContext.Request.Form[key].FirstOrDefault(), typeof(T));
                }
                else
                {
                    return default(T);
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }



        /// <summary>
        /// 获取Get或Post的数据并转换为Json格式。
        /// </summary>
        /// <returns></returns>
        public string GetJsonStr()
        {
            if (IsHttpGet)
            {
                string text = Request.QueryString.Value;
                if (text.Length > 0)
                {
                    text = text.Substring(1);
                }
                Dictionary<string, string> keyValue = GetRequestKeyValue(text);
                return JsonConvert.SerializeObject(keyValue);
            }
            else if (IsHttpPost)
            {
                string json = "";
                using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    //json = reader.ReadToEnd();
                    json = reader.ReadToEndAsync().Result;
                }
                if (Request.ContentType.Contains("application/json"))
                {
                    return json;
                }
                else
                {
                    Dictionary<string, string> keyValue = GetRequestKeyValue(json.UrlDecode());
                    return JsonConvert.SerializeObject(keyValue);
                }
            }
            return "{}";
        }

        /// <summary>
        /// 获取Get或Post的数据并转换为Json格式。
        /// </summary>
        /// <returns></returns>
        public JObject GetJson()
        {
            string str = GetJsonStr();
            if (str.IsNotNull())
            {
                return JObject.Parse(str);
            }
            return new JObject();
        }



        /// <summary>
        ///  获取 get 或 post 的 参数
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetRequestKeyValue(string val)
        {
            string[] arr = val.Split("&", StringSplitOptions.RemoveEmptyEntries);
            Dictionary<string, string> keyValue = new Dictionary<string, string>();
            foreach (var item in arr)
            {
                string[] arr1 = item.Split("=", StringSplitOptions.RemoveEmptyEntries);
                if (arr1.Length == 1)
                {
                    if (!keyValue.ContainsKey(arr1[0]))
                    {
                        keyValue.Add(arr1[0], "");
                    }
                }
                else if (arr1.Length == 2)
                {
                    if (!keyValue.ContainsKey(arr1[0]))
                    {
                        keyValue.Add(arr1[0], arr1[1]);
                    }
                    else
                    {
                        keyValue[arr1[0]] = arr1[1];
                    }
                }
            }
            return keyValue;
        }

    }
}