using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Ocsp;
using System.Text.Json;
using System.Runtime.InteropServices;
using System.Net;
using System.Threading;
using Microsoft.AspNetCore.Mvc.RazorPages;
using TencentCloud.Soe.V20180724.Models;
using static dodohold.core.ZTOExpress.CreateOrderArgs;
using static Spire.Xls.Core.Spreadsheet.HTMLOptions;
using System.Net.Http.Json;
using System.Text.RegularExpressions;
using System.Text;
using TencentCloud.Oceanus.V20190422.Models;

namespace molilian.api.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class TestController : ControllerBase
    {

        protected IHttpContextAccessor _accessor;
        public TestController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }


        //[HttpGet]
        //public async Task<ActionResult> test(string table = "tk_parse_logs_shop", int count = 100)
        //{
        //    //table = "tk_parse_logs_shop";
        //    //table = "tk_parse_logs_live";
        //    //table = "tk_parse_logs_video";

        //    string filter = "success=0 AND message='放弃转链' AND reason='非标准链接'";

        //    for (int i = 0; i < 100; i++)
        //    {
        //        try
        //        {
        //            var list = new DBContext.Table(table)
        //                .Where(filter, new { })
        //                .Limit(count).Select<TkDataDTO>();
        //            if (!list.Any())
        //            {

        //                return new APIResult(new
        //                {
        //                    success = false,
        //                    message = "所有任务完成"
        //                });

        //            }
        //            foreach (var item in list)
        //            {
        //                TkPoolDTO? account = TkPoolCore.GetOne(TkPoolCore.TkAction.parse);
        //                if (account == null)
        //                {
        //                    return new APIResult(new
        //                    {
        //                        success = false,
        //                        message = "没有工作账号"
        //                    });
        //                }

        //                var result = item.Convert2Json().Convert2Object<TkDataDTO>();

        //                result.accountId = account.id;
        //                result.accountName = account.company;

        //                var alimama = new AlimamaPlus(account);


        //                int timeout = alimama._config.rt_max;
        //                using var cts = new CancellationTokenSource();
        //                cts.CancelAfter(timeout);

        //                result = await alimama.UnionParseAsync(item.content, result);
        //                string reason = "非标准链接".Equals(result.reason) ? "非标准链接ok" : result.reason;

        //                new DBContext.Table(table)
        //                    .Add("linkType", (int)result.link_type)
        //                    .Add("rawContent", result.rawContent)
        //                    .Add("success", result.success)
        //                    .Add("message", result.message)
        //                    .Add("reason", reason)
        //                    .Add("content", result.content)
        //                    .Add("itemId", result.itemId)
        //                    .Add("itemName", result.itemName)
        //                    .Add("pic", result.pic)
        //                    .Add("couponAmount", result.couponAmount)
        //                    .Add("promotionPrice", result.promotionPrice)
        //                    .Add("taoToken", result.taoToken)
        //                    .Add("shortLinkurl", result.shortLinkurl)
        //                    .Add("deeplink_url", result.deeplink_url)
        //                    .Add("num_iid", result.num_iid)
        //                    .Add("elapsedTime", result.elapsedTime)
        //                    .Add("elapsedTime2", result.elapsedTime2)
        //                    .Add("elapsedTime3", result.elapsedTime3)
        //                    .Add("subCode", result.subCode)
        //                    .Where("id=@id", new { item.id })
        //                    .Update();
        //            }
        //        }
        //        catch
        //        {
        //        }
        //    }

        //    return new APIResult(new
        //    {
        //        success = true,
        //        message = "ok"
        //    });


        //}


        [HttpPost]
        public async Task<ActionResult> test([FromForm] string jsonContent, [FromForm] string testText)
        {

            // 用于存储输出结果的StringBuilder
            StringBuilder outputBuilder = new StringBuilder();

            // 解析JSON数据
            JsonDocument jsonDoc = JsonDocument.Parse(jsonContent);

            // 获取根元素
            JsonElement root = jsonDoc.RootElement;

            // 遍历规则
            foreach (JsonElement ruleSet in root.EnumerateArray())
            {

                string platformType = ruleSet.Read("platformType", string.Empty);
                string supplier = ruleSet.Read("supplier", string.Empty);
                outputBuilder.AppendLine($"平台类型: {platformType}, 供应商: {supplier}");

                JsonElement pwdRules = ruleSet.GetProperty("pwdRules");
                int idx = 0;
                foreach (JsonElement patternElement in pwdRules.EnumerateArray())
                {
                    string pattern = patternElement.GetString();
                    try
                    {
                        // 使用Regex类来编译正则表达式
                        Regex compiledPattern = new Regex(pattern);
                        if (compiledPattern.IsMatch(testText))
                        {
                            outputBuilder.AppendLine($"规则 {idx + 1}: 匹配\t{pattern}");
                        }
                        else
                        {
                            outputBuilder.AppendLine($"规则 {idx + 1}: 不匹配");
                        }
                    }
                    catch (Exception e)
                    {
                        outputBuilder.AppendLine($"规则 {idx + 1}: 正则表达式错误 - {e.Message}\t{pattern}");
                    }
                    idx++;
                }
            }

            outputBuilder.AppendLine("测试完成");

            return Content(outputBuilder.ToString());
        }


        [HttpGet]
        public async Task<ActionResult> ip(string ip)
        {

            string result = IP2RegionPlus.Search(ip);

            return new APIResult(new
            {
                success = true,
                message = result
            });
        }


        [HttpPost]
        public async Task<ActionResult> testreg([FromBody] JsonElement form)
        {
            var content = form.Read("s", string.Empty);

            string shortLinkurl = AlimamaPlus.GetTaobaoLink(content);
            bool is_tao_token = AlimamaPlus.MatchRegexes(content, []);
            bool is_other = AlimamaPlus.MatchOtherInfo(content, []);

            return new APIResult(new
            {
                shortLinkurl,
                is_tao_token,
                is_other
            });


        }
        //[HttpGet]
        //public async Task<ActionResult> comparison_tk([FromQuery] int count = 100)
        //{
        //    string cacheKey = ":lock_key:comparison_tk_logs";
        //    int last_id = RedisHelper.Get<int>(cacheKey);

        //    string filter = "id>@last_id";
        //    var result = new DBContext.Table("comparison_tk_logs")
        //        .Where(filter, new { last_id })
        //        .Page(count, 1)
        //        .Order("ID")
        //        .PageList<TkDataDTO>(false);

        //    var ip = "127.0.0.1";
        //    var oaid = "test-comparison_tk_logs";
        //    foreach (var item in result.List)
        //    {
        //        await UnionParseCore.TaobaoParseAsync(item.rawContent, ip, oaid);
        //        RedisHelper.Set(cacheKey, item.id, 10 * 86400);
        //    }
        //    if (result.Count < count)
        //    {
        //        cacheKey = ":lock_key:start_comparison_tk";
        //        RedisHelper.Set(cacheKey, 1, 600);
        //    }
        //    return new APIResult(new
        //    {
        //        success = true,
        //        message = "ok"
        //    });
        //}

        //[HttpGet]
        //public async Task<ActionResult> comparison_tk_raw([FromQuery] int count = 100)
        //{
        //    string cacheKey = ":lock_key:comparison_tk_logs_raw";
        //    int last_id = RedisHelper.Get<int>(cacheKey);

        //    string filter = "id>@last_id";
        //    var result = new DBContext.Table("comparison_tk_logs")
        //        .Where(filter, new { last_id })
        //        .Page(count, 1)
        //        .Order("ID")
        //        .PageList<TkDataDTO>(false);

        //    var ip = "127.0.0.1";
        //    var oaid = "test-comparison_tk_logs_raw";
        //    foreach (var item in result.List)
        //    {
        //        await UnionParseCore.TaobaoParseAsync(item.rawContent, ip, oaid);
        //        RedisHelper.Set(cacheKey, item.id, 10 * 86400);
        //    }
        //    if (result.Count < count)
        //    {
        //        cacheKey = ":lock_key:start_comparison_tk";
        //        RedisHelper.Set(cacheKey, 1, 600);
        //    }
        //    return new APIResult(new
        //    {
        //        success = true,
        //        message = "ok"
        //    });
        //}


        [HttpGet]
        public async Task<ActionResult> testTask()
        {
            string url = "https://www.taobao.com";
            TkDataDTO result = new TkDataDTO();
            result.message = "init";
            result.success = true;


            int timeout = 1000;
            using var cts = new CancellationTokenSource();
            cts.CancelAfter(timeout);


            var requestTask = Task.Run(() => AlimamaPlus.testTaskAsync(result, cts.Token), cts.Token);


            var delayTask = Task.Delay(timeout, cts.Token);
            var completedTask = await Task.WhenAny(requestTask, delayTask);
            if (completedTask == requestTask)
            {
                result = await requestTask;
            }
            else
            {
                cts.Cancel();
                result.success = false;
                result.message = "放弃转链";
                result.reason = "请求超时";
                result.itemName = "点击打开淘宝APP";
            }

            return new APIResult(new
            {
                success = true,
                message = "ok",
                result,
            });
        }

        [HttpGet]
        public async Task<ActionResult> testThread()
        {
            // 查看默认的最小和最大线程数
            ThreadPool.GetMinThreads(out int defaultMinWorker, out int defaultMinIOC);
            ThreadPool.GetMaxThreads(out int defaultMaxWorker, out int defaultMaxIOC);
            string tmp = $"Default Min worker threads: {defaultMinWorker}, Min I/O completion threads: {defaultMinIOC}";
            string tmp2 = $"Default Max worker threads: {defaultMaxWorker}, Max I/O completion threads: {defaultMaxIOC}";



            // 获取当前线程池中可用的工作线程数和 I/O 完成端口线程数
            ThreadPool.GetAvailableThreads(out int availableWorkerThreads, out int availableIOCompletionThreads);
            string tmp3 = $"Current available worker threads: {availableWorkerThreads}, available I/O completion threads: {availableIOCompletionThreads}";

            return new APIResult(new
            {
                tmp,
                tmp2,
                tmp3,
            });
        }

        [HttpPost]
        public async Task<ActionResult> test1([FromBody] JsonElement form)
        {

            NotifyCore.Notify(new NifyMessage
            {
                message = $"【淘宝联盟:test】cookie 掉线",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });


            return new APIResult(new
            {
                success = true,
                message = "ok"
            });
        }

        [HttpGet]
        public async Task<ActionResult> xxx()
        {
            var list = TkPoolCore.List();
            if (list == null) return new APIResult(new { success = false, message = "没有有效账号", });
            string message = string.Empty;
            foreach (var account in list)
            {
                try
                {
                    var alimama = new AlimamaPlus(account);
                    alimama.RenewCookie();
                }
                catch (Exception ex)
                {
                    message = $"【cookie续期】xxxx\n{ex.Message}\n{ex.StackTrace}";
                    NotifyCore.Notify(new NifyMessage
                    {
                        message = message,
                        priority = NifyMessagePriority.high,
                        tags = ["red_circle"]
                    });
                    continue;
                }
            }
            return new APIResult(new { success = true, message = "ok" });
        }



    }
}