using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace QYZH.InteractiveMagazine.Common.Extensions
{
    /// <summary>
    /// 字符串扩展方法
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">原始字符串</param>
        /// <returns>MD5哈希值(32位小写)</returns>
        public static string ToMd5(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }

            using (var md5 = MD5.Create())
            {
                byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                var sb = new StringBuilder();
                foreach (byte b in bytes)
                {
                    sb.Append(b.ToString("x2"));
                }
                return sb.ToString();
            }
        }

        /// <summary>
        /// SHA256加密
        /// </summary>
        /// <param name="input">原始字符串</param>
        /// <returns>SHA256哈希值(64位小写)</returns>
        public static string ToSha256(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }

            using (var sha256 = SHA256.Create())
            {
                byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
                var sb = new StringBuilder();
                foreach (byte b in bytes)
                {
                    sb.Append(b.ToString("x2"));
                }
                return sb.ToString();
            }
        }

        /// <summary>
        /// Base64编码
        /// </summary>
        /// <param name="input">原始字符串</param>
        /// <returns>Base64编码后的字符串</returns>
        public static string ToBase64(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }

            byte[] bytes = Encoding.UTF8.GetBytes(input);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// Base64解码
        /// </summary>
        /// <param name="input">Base64编码的字符串</param>
        /// <returns>解码后的原始字符串</returns>
        public static string FromBase64(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }

            byte[] bytes = Convert.FromBase64String(input);
            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// 判断字符串是否为空或空白
        /// </summary>
        /// <param name="input">待检查的字符串</param>
        /// <returns>是否为空或空白</returns>
        public static bool IsNullOrWhiteSpace(this string input)
        {
            return string.IsNullOrWhiteSpace(input);
        }

        /// <summary>
        /// 手机号脱敏
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <returns>脱敏后的手机号(中间4位用*替换)</returns>
        public static string MaskPhone(this string phone)
        {
            if (string.IsNullOrEmpty(phone) || phone.Length < 7)
            {
                return phone;
            }

            return phone.Substring(0, 3) + "****" + phone.Substring(phone.Length - 4);
        }

        /// <summary>
        /// 身份证脱敏
        /// </summary>
        /// <param name="idCard">身份证号</param>
        /// <returns>脱敏后的身份证号(保留前3位和后4位)</returns>
        public static string MaskIdCard(this string idCard)
        {
            if (string.IsNullOrEmpty(idCard) || idCard.Length < 7)
            {
                return idCard;
            }

            int length = idCard.Length;
            return idCard.Substring(0, 3) + new string('*', length - 7) + idCard.Substring(length - 4);
        }

        /// <summary>
        /// 正则匹配
        /// </summary>
        /// <param name="input">待匹配的字符串</param>
        /// <param name="pattern">正则表达式</param>
        /// <returns>是否匹配</returns>
        public static bool IsMatchRegex(this string input, string pattern)
        {
            if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(pattern))
            {
                return false;
            }

            return Regex.IsMatch(input, pattern);
        }

        /// <summary>
        /// 判断字符串是否为Null、空
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNull(this string s)
        {
            return string.IsNullOrWhiteSpace(s);
        }

        public static string RemoveDomain(this string str)
        {
            if (str.IsNull()) return str;
            // 匹配域名后的路径部分（包括第一个/）
            return Regex.Replace(str, @"https?://[^/]+/([^""\s<>]*)", "$1");
        }

        public static string AddDomain(this string str, string domainUrl)
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(domainUrl)) return str;

            string pattern = @"src=""([^""]+)""";
            return Regex.Replace(str, pattern, match =>
            {
                string originalUrl = match.Groups[1].Value;
                // 忽略base64图片
                if (originalUrl.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) return match.Value; // 返回原样
                                                                                                             // 如果已经是完整URL则不做处理
                if (Uri.IsWellFormedUriString(originalUrl, UriKind.Absolute)) return match.Value; // 返回原样


                // 处理URL开头可能存在的斜杠
                var trimmedUrl = originalUrl.StartsWith("/") ? originalUrl.Substring(1) : originalUrl;
                var trimmedDomain = domainUrl.EndsWith("/") ? domainUrl : domainUrl + "/";

                string newUrl = $"{trimmedDomain}{trimmedUrl}";
                return $"src=\"{newUrl}\""; // 返回替换后的属性
            });
        }

        public static string ToExtension(this string str)
        {
            return Regex.Match(str, @"(?<=\.)[a-zA-Z0-9]+$").Value;
        }

        public static bool NotNull(this string s)
        {
            return !string.IsNullOrWhiteSpace(s);
        }

        public static List<string> AllUrl(this string str, string url = null)
        {
            if (string.IsNullOrEmpty(str)) return new List<string>();

            string pattern = @"src=""([^""]+)""";

            var matches = Regex.Matches(str, pattern, RegexOptions.IgnoreCase);

            return matches
                .Cast<Match>()
                .Select(m => m.Groups[1].Value)
                .Where(u => !string.IsNullOrEmpty(u) && !u.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) // 排除base64
                .Where(url => !string.IsNullOrEmpty(url) && url.StartsWith(url, StringComparison.OrdinalIgnoreCase))
                //.Where(url => url.StartsWith("https://example.com")) // 二次验证
                .ToList();
        }
    }
}
