using Atomx.Data;
using Microsoft.Extensions.Caching.Distributed;
using System.Text;
using System.Text.Json;

namespace Atomx.Data.CacheServices
{
    public partial interface ICacheService
    {
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">缓存时间，默认8小时</param>
        /// <returns></returns>
        Task SetCacheAsync<T>(string key, T value, double time = 8);

        /// <summary>
        /// 根据指定KEY获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        Task<T?> GetCacheAsync<T>(string key);

        /// <summary>
        /// 获取指定 key 的缓存List数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        Task<List<T>> GetCacheList<T>(string key);

        /// <summary>
        /// 清除指定 key 的缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        Task Remove(string key);


    }

    public partial class CacheService : ICacheService
    {
        readonly DataContext _dbContext;
        readonly IDistributedCache _cache;

        public CacheService(DataContext dataContext, IDistributedCache distributedCache)
        {
            _dbContext = dataContext;
            _cache = distributedCache;
        }


        public Task Remove(string key)
        {
            _cache.Remove(key);
            return Task.CompletedTask;
        }


        public T? GetCache<T>(string key)
        {
            try
            {
                var cacheData = _cache.GetString(key);
                if (cacheData != null)
                {
                    try
                    {
                        return JsonSerializer.Deserialize<T>(cacheData);
                    }
                    catch
                    {
                        return default;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine($"无法链接缓存服务，读取缓存数据失败，错误信息：{ex.Message}");
                Console.ResetColor();
            }
            return default;
        }

        public async Task<T?> GetCacheAsync<T>(string key)
        {
            try
            {
                var cacheData = await _cache.GetStringAsync(key);
                if (cacheData != null)
                {
                    try
                    {
                        return JsonSerializer.Deserialize<T>(cacheData);
                    }
                    catch
                    {
                        return default;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine($"无法链接缓存服务，读取缓存数据失败，错误信息：{ex.Message}");
                Console.ResetColor();
            }
            return default;
        }

        public async Task<List<T>> GetCacheList<T>(string key)
        {
            var cacheData = await _cache.GetStringAsync(key);
            if (cacheData != null)
            {
                try
                {
                    var data = JsonSerializer.Deserialize<List<T>>(cacheData);
                    if (data != null)
                    {
                        return data;
                    }
                }
                catch
                {
                    return new List<T>();
                }
            }
            return new List<T>();
        }

        public void SetCache<T>(string key, T value, double time = 8)
        {
            var options = new DistributedCacheEntryOptions();
            var minute = time * 60;
            var timspace = TimeSpan.FromMinutes(minute);
            options.SetSlidingExpiration(timspace);

            try
            {
                _cache.SetString(key, JsonSerializer.Serialize(value), options);
            }
            catch (Exception ex)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine($"无法链接缓存服务，写入缓存数据失败，错误信息：{ex.Message}");
                Console.ResetColor();
            }
        }

        public async Task SetCacheAsync<T>(string key, T value, double time = 8)
        {
            var options = new DistributedCacheEntryOptions();
            var minute = time * 60;
            var timspace = TimeSpan.FromMinutes(minute);
            options.SetSlidingExpiration(timspace);

            try
            {
                await _cache.SetStringAsync(key, JsonSerializer.Serialize(value), options);
            }
            catch (Exception ex)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine($"无法链接缓存服务，写入缓存数据失败，错误信息：{ex.Message}");
                Console.ResetColor();
            }
        }
    }
}