using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Hotline.Share.Tools;

/// <summary>
/// Html 转 Word 时，验证图片是否有效
/// </summary>
public class HtmlImageValidator
{
    private readonly HttpClient _httpClient = new HttpClient();

    /// <summary>
    /// Html 转 Word 时，验证图片是否有效
    /// </summary>
    /// <param name="htmlContent"></param>
    /// <returns></returns>
    public string ValidateAndReplaceImagesAsync(string htmlContent)
    {
        string pattern = "<img[^>]+src=\"([^\"]+)\"[^>]*>";
        var matches = Regex.Matches(htmlContent, pattern);

        foreach (Match match in matches)
        {
            string imageUrl = match.Groups[1].Value;
            if (!IsImageAccessible(imageUrl))
            {
                // 将无效链接替换为空白或占位符
                htmlContent = htmlContent.Replace(imageUrl, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAIAAABLixI0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAEXRFWHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AAALiSURBVDiNrZLLaxNRFMZPJneapJ2kHdOIbdJa6cO4GFoDVmwXBbU7QVwIIrqT+gfooms3irioIIJLwY3QhRtxEVpapEgFJ9FUsXnQWtLnmEyTTmYm84qLG27GNJZW/Rju4rtnfve79xzH1NSU/3gnHEWlYj4SiXAcV+ejrlPhofNjR2J9XpwVRTGRSPT397vd7hpLLeu5onF4kAuZADA8PJxKpWKxGMdxDMPgLepIieziOC4QCPA8L0nSQSwXMvEHALqu/wnX19cXDAZ5nhcEAQAQ2dB1naZpAAixDpZxYVOUzKxI4y28Soplx/X29vp8vnQ6rWkaIiC8nvB7WKZWyjJOxYStnG5PVyqVotGonZjP55PJZC0XTdMh1mEHYXmcJg5FjuSGRvbfN5NaQuR2IdbBMs79RSRaLVelGb+GXWpZr+by+9D+RNUiVZVkh25YAEAjSjcsGlGyUqZRfd+qrK2cIsmNe1o2EHksTLSvWJiLSJG4Z9VjqjrsJP/9rNaJPRZAZc0EAMus/AuI8VKR0cH/kIth3N1sBexz31CKIe0aGwDQ4mTpitfT5K4r8LfRAx0IcxD83hGCWJcTy8XoqjJPzEBTmGu9FmwZ9NEB7JzsZDpba381yCUoK3HxzYr8Xq8UKGgmfk5bmxOedkvnTvvGg+6z4Z52OyiTydSzNtXkws6LbS1OQbMdRLSqzP/UMk/GXjK22RYl82M8XWMpmrquxnjxlaB9b0gBAAtkxhmaHH3E2EgbBfixodTueEjQUPulO5F7bW4/MZOb5ezOHu4JAgDLrOxaa3Fx+mDQSMfVm9xdAlJVdW7lg0PvocGLHQoAirqwlH8raMkDQONdt+0gAHjGP3idfvgtP0McJKkFUZlNl2YbUjDoxsD9K+HrxNlVc5MzE5KZBYDl0rtWV/uZpssAgJLZRdncBsPTEORt8d0ambjQdZE4XzNfni88lg2FAj8AyKB8yk0bAd2hVn4BVP1hWBpYCWkAAAAASUVORK5CYII=");
            }
        }

        return htmlContent;
    }

    /// <summary>
    /// 请求图片链接，判断是否有效
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private bool IsImageAccessible(string url)
    {
        try
        {
            var task = _httpClient.GetAsync(url);
            var completedTask = Task.WhenAny(task, Task.Delay(3000)).GetAwaiter().GetResult();

            if (completedTask == task && task.Result.IsSuccessStatusCode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }
}
