using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Atomx.Utils.Extension
{
    public static class StringExtension
    {
        // <summary>
        /// MD5加密，输出的字母是大写
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ToMD5(this string text)
        {
            MD5 md5 = MD5.Create();
            return BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
        }

        /// <summary>
        /// 字符串加密为通用的密码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ToMd5Password(this string text)
        {
            var md5 = text.ToMD5().ToMD5();
            return md5;
        }

        /// <summary>
        /// 随机数字字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetRandomNumberString(int length)
        {
            string buffer = "0123456789";
            StringBuilder sb = new StringBuilder();
            Random r = new Random();
            int range = buffer.Length;
            for (var i = 0; i < length; i++)
            {
                sb.Append(buffer.Substring(r.Next(range), 1));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 随机数字字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetRandomString(int length)
        {
            string buffer = "abcdefghijklmnopqrstuvwxyz";
            StringBuilder sb = new StringBuilder();
            Random r = new Random();
            int range = buffer.Length;
            for (var i = 0; i < length; i++)
            {
                sb.Append(buffer.Substring(r.Next(range), 1));
            }
            return sb.ToString();
        }


        /// <summary>
        /// 获取URL参数字段值
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public static string GetQueryString(this string queryString, string paramName)
        {
            if (string.IsNullOrEmpty(queryString) || string.IsNullOrEmpty(paramName))
            {
                return "";
            }
            string paramValue = HttpUtility.ParseQueryString(queryString).Get(paramName)?.ToString() ?? string.Empty;
            return paramValue ?? "";
        }

        /// <summary>
        /// 转换URL参数
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string BuildQueryString(this object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null)
                return buff.ToString();


            var modelDict = source.GetType().GetProperties().ToDictionary(a => a.Name.ToLower());
            foreach (var item in modelDict)
            {
                if (item.Value.PropertyType != typeof(DateTime?[]))
                {
                    System.Reflection.PropertyInfo? pi = null;
                    if (modelDict.TryGetValue(item.Key, out pi))
                    {
                        object? obj = pi.GetValue(source, null);
                        if (pi != null && obj != null)
                        {
                            var value = obj.ToString();
                            if (!string.IsNullOrEmpty(value))
                            {
                                buff.Append($"{item.Key}={value}&");
                            }
                        }
                    }
                }
                else
                {
                    System.Reflection.PropertyInfo? pi = null;
                    if (modelDict.TryGetValue(item.Key, out pi))
                    {
                        object? obj = pi.GetValue(source, null);
                        if (pi != null && obj != null)
                        {
                            var data = obj as DateTime?[];
                            if (data != null)
                            {
                                long start = 0;
                                long end = 0;
                                if (data[0].HasValue) {
                                    var time1 = data[0].Value.ConvertStartDateTime();
                                    start = time1.DateToNumber();
                                }
                                if (data[1].HasValue)
                                {
                                    var time1 = data[1].Value.ConvertEndDateTime();
                                    end = time1.DateToNumber();
                                }
                                if (start > 0 && end > 0)
                                {
                                    buff.Append($"{item.Key}={start}-{end}&");
                                }
                            }
                        }
                    }
                }
            }
            return buff.ToString().Trim('&');
        }

        /// <summary>
        /// url参数转换成字典
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ToUrlDictionary(this string formData)
        {
            if (string.IsNullOrEmpty(formData))
            {
                return new Dictionary<string, object>();
            }
            try
            {
                //将参数存入字符数组
                string[] dataArry = formData.Split('&');

                //定义字典,将参数按照键值对存入字典中
                Dictionary<string, object> dataDic = new Dictionary<string, object>();
                //遍历字符数组
                for (int i = 0; i <= dataArry.Length - 1; i++)
                {
                    //当前参数值
                    string dataParm = dataArry[i];
                    //"="的索引值
                    int dIndex = dataParm.IndexOf("=");
                    //参数名作为key
                    string key = dataParm.Substring(0, dIndex);
                    //参数值作为Value
                    string value = dataParm.Substring(dIndex + 1, dataParm.Length - dIndex - 1);
                    //将编码后的Value解码
                    string deValue = HttpUtility.UrlDecode(value, Encoding.GetEncoding("utf-8"));
                    if (key != "__VIEWSTATE")
                    {
                        //将参数以键值对存入字典
                        dataDic.Add(key, deValue);
                    }
                }

                return dataDic;
            }
            catch (Exception)
            {
                return new Dictionary<string, object>();
            }
        }
    }
}
