using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;
using Dataoke;
using Google.Protobuf.WellKnownTypes;
using System.Diagnostics;
using System.Text.Json;
using TencentCloud.Tcm.V20210413.Models;
using System.Security.Cryptography;


namespace molilian.core
{
    public partial class PddPoolCore
    {
        private static readonly object _lockObj = new();
        private static IEnumerable<PddPoolDTO> _cached;
        public static PddPoolDTO? GetOne()
        {
            var list = List();
            if (!list.Any()) return null;
            return list.OrderBy(l => Guid.NewGuid()).FirstOrDefault();
        }

        public static IEnumerable<PddPoolDTO> List(bool force = false)
        {
            if (!force && _cached != null) return _cached;

            string cache_key = $"cache:pdd_pool";
            var list = RedisHelper.Get<IEnumerable<PddPoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("pdd_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<PddPoolDTO>();
                    if (list == null) return default;
                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _cached = list;
            return list;
        }
        public static void Refresh()
        {
            _ = List(true);
        }

        public static void Disabled(string name)
        {
            string cache_key = $"cache:pdd_pool:{name}:disabled";
            long count = RedisHelper.IncrBy(cache_key);
            RedisHelper.Expire(cache_key, 10);
            if (count > 1) return;

            new DBContext.Table("pdd_pool")
                .Add("status", 0)
                .Where("name=@name", new { name })
                .Update();
            _ = List(true);

            NotifyCore.Notify(new NifyMessage
            {
                message = $"【多多:{name}】调用异常",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });
        }


        public static Dictionary<string, string> GenerateSignature(PddPoolDTO account, Dictionary<string, string> args)
        {
            if (args.ContainsKey("sign")) args.Remove("sign");
            // 对参数进行ASCII升序排序
            var sortedArgs = args.OrderBy(kv => kv.Key).ToDictionary(kv => kv.Key, kv => kv.Value);

            // 拼接排序后的参数
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var kv in sortedArgs)
            {
                stringBuilder.Append(kv.Key).Append(kv.Value);
            }

            // 在头部和尾部分别拼接client_secret
            string signString = account.app_secret + stringBuilder.ToString() + account.app_secret;
            signString = signString.MD5(false, false);

            if (!args.TryAdd("sign", signString))
            {
                args["sign"] = signString;
            }
            return args;
        }
    }
}
