using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing.Imaging;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace WebAPIServer.Extensions
{
    /// <summary>
    /// 字符串扩展函数工具类
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// 将\r\n替换成BR
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToSafeBR(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
            }
            return str;
        }

        /// <summary>
        /// 得到父部门的ID
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetDepartmentFatherID(this string str)
        {
            if (!string.IsNullOrEmpty(str) && str.Length > 2)
            {
                str = str.Substring(0, str.Length - 3);
            }
            return str;
        }

        /// <summary>
        /// 截取字符串，超过部分用...代替
        /// </summary>
        /// <param name="source"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string Substr(this string source, int len)
        {
            return source.Substr(len, "...");
        }

        /// <summary>
        /// 截取字符串，超过部分用自定义代替
        /// </summary>
        /// <param name="source"></param>
        /// <param name="len"></param>
        /// <param name="att"></param>
        /// <returns></returns>
        public static string Substr(this string source, int len, string att)
        {
            if (string.IsNullOrEmpty(source))
            {
                return string.Empty;
            }
            att = (att ?? string.Empty);
            Regex regex = new Regex("[\\u4e00-\\u9fa5]");
            Regex regex2 = new Regex("^[A-Za-z0-9]+$");
            if (regex.IsMatch(source))
            {
                if (source.Length <= len)
                {
                    return source;
                }
                return source.Substring(0, len) + att;
            }
            else if (regex2.IsMatch(source))
            {
                if (source.Length <= len * 2)
                {
                    return source;
                }
                return source.Substring(0, len * 2) + att;
            }
            else
            {
                if (source.Length <= len)
                {
                    return source;
                }
                return source.Substring(0, len) + att;
            }
        }

        public static string InputStr(this string source)
        {
            if (!string.IsNullOrEmpty(source))
            {
                Regex regex = new Regex("[\\u4e00-\\u9fa5]");
                Regex regex2 = new Regex("^[A-Za-z0-9]+$");
                if (regex.IsMatch(source))
                {
                    if (source.Length < 3)
                    {
                        return string.Format("{0}**", source[0]);
                    }
                    if (source.Length == 3)
                    {
                        return string.Format("{0}*{1}", source[0], source[source.Length - 1]);
                    }
                    if (source.Length > 3)
                    {
                        return string.Format("{0}**{1}", source[0], source[source.Length - 1]);
                    }
                }
                else
                {
                    if (!regex2.IsMatch(source))
                    {
                        return string.Format("{0}**", source.Substring(0, 2));
                    }
                    if (source.Length < 6)
                    {
                        return string.Format("{0}**", source.Substring(0, 2));
                    }
                    return string.Format("{0}****{1}", source.Substring(0, 2), source.Substring(source.Length - 3, 2));
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 移除掉所有的Html代码
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string RemoveHtml(this string strHtml)
        {
            Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
            strHtml = regex.Replace(strHtml, "");
            strHtml = strHtml.Replace("&nbsp;", "");
            return strHtml;
        }

        /// <summary>
        /// 生成0-9随机数
        /// </summary>
        /// <param name="VcodeNum">生成长度</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            StringBuilder stringBuilder = new StringBuilder(VcodeNum);
            Random random = new Random();
            for (int i = 1; i < VcodeNum + 1; i++)
            {
                int num = random.Next(9);
                stringBuilder.AppendFormat("{0}", num);
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 返回星号的加密
        /// </summary>
        /// <param name="items"></param>
        /// <param name="mask"></param>
        /// <returns></returns>
        public static string MaskStar(Dictionary<string, string> items, bool mask)
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (mask)
            {
                foreach (KeyValuePair<string, string> keyValuePair in items)
                {
                    stringBuilder.Append(string.Concat(new string[]
                    {
                        "$('#",
                        keyValuePair.Key,
                        "').attr('name', '",
                        keyValuePair.Key,
                        "mask');"
                    }));
                }
                stringBuilder.Append("$('.maskstar').attr('disabled', true);");
                stringBuilder.Append("$('.maskstar').val('***');");
            }
            else
            {
                foreach (KeyValuePair<string, string> keyValuePair2 in items)
                {
                    stringBuilder.Append(string.Concat(new string[]
                    {
                        "$('#",
                        keyValuePair2.Key,
                        "').attr('name', '",
                        keyValuePair2.Key,
                        "');"
                    }));
                    stringBuilder.Append(string.Concat(new string[]
                    {
                        "$('#",
                        keyValuePair2.Key,
                        "').val('",
                        keyValuePair2.Value,
                        "');"
                    }));
                }
                stringBuilder.Append("$('.maskstar').attr('disabled', false);");
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 给自动填充使用
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static string ToAutoComplate(this string str1, string str2)
        {
            if (!string.IsNullOrEmpty(str1) && !string.IsNullOrEmpty(str2))
            {
                return str1 + "," + str2;
            }
            return "";
        }

        /// <summary>
        /// 返回红色字体
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToRedColor(this int value)
        {
            if (value != 0)
            {
                return "<font color='red'>" + value.ToString() + "</font>";
            }
            return value.ToString();
        }

        /// <summary>
        /// 返回安全的字符串类型如果为NULL则返回空
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToSafeString(this object value)
        {
            if (value == null)
            {
                return "";
            }
            return value.ToString();
        }

        /// <summary>
        /// 将中文转换成Unicode编码，主要用在URL传递中文
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GB2Unicode(this string str)
        {
            string text = "";
            Encoding encoding = Encoding.GetEncoding("GB2312");
            Encoding unicode = Encoding.Unicode;
            byte[] bytes = encoding.GetBytes(str);
            for (int i = 0; i < bytes.Length; i++)
            {
                string str2 = "%" + bytes[i].ToString("x");
                text += str2;
            }
            return text;
        }

        /// <summary>
        /// 将字符串转换成为大写的MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMD5(this string str)
        {
            MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();
            byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte b in array)
            {
                stringBuilder.Append(b.ToString("x2"));
            }
            return stringBuilder.ToString().ToUpper();
        }

        /// <summary>
        /// 字节码长度转可读字符串 00000000 bytes 0.0GB
        /// </summary>
        /// <param name="KSize"></param>
        /// <returns></returns>
        public static string ByteSizeToString(this long KSize)
        {
            if (KSize > 0L)
            {
                string[] array = new string[]
                {
                    "B",
                    "KB",
                    "MB",
                    "GB",
                    "TB"
                };
                double num = 0.0;
                int num2 = array.Length - 1;
                while (num2 >= 0 && (num = Math.Round((double)KSize / Math.Pow(1024.0, (double)num2), 2)) < 1.0)
                {
                    num2--;
                }
                return string.Format("{0}{1}", num, array[num2]);
            }
            return string.Empty;
        }


        /// <summary>
        /// 将字符串转换成为大写的MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string GetMD5Code(this string str)
        {
            StringBuilder stringBuilder = new StringBuilder();
            using (MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider())
            {
                byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
                foreach (byte b in array)
                {
                    stringBuilder.Append(b.ToString("x2"));
                }
            }
            return stringBuilder.ToString();
        }

    }
}
