using AutoMapper;

using CloudGaming.Code.AppExtend;
using CloudGaming.Code.DataAccess;
using CloudGaming.DtoModel.Game;

using HuanMeng.DotNetCore.CacheHelper;
using HuanMeng.DotNetCore.CacheHelper.Contract;
using HuanMeng.DotNetCore.Redis;

using Newtonsoft.Json;

using StackExchange.Redis;

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

using static System.Net.Mime.MediaTypeNames;

namespace CloudGaming.Code.Cache.Special
{
    /// <summary>
    /// 图片缓存表
    /// </summary>
    /// <param name="dao"></param>
    /// <param name="appConfig"></param>
    /// <param name="database"></param>
    /// <param name="mapper"></param>
    /// <param name="appRequestConfig"></param>
    public class ImageEntityCache(DAO dao, AppConfig appConfig, IDatabase database, AppRequestConfig appRequestConfig) : ICacheClearData, ICacheReloadData
    {
        public static bool IsLoadImage { get; set; } = false;
        private string key = $"{appConfig.Identifier}:App:Image";
        private string redisKey = $"App:Image";
        ConcurrentDictionary<string, ConcurrentDictionary<int, string>>? ImageData { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="language"></param>
        /// <returns></returns>
        public ConcurrentDictionary<int, string> this[string language]
        {
            get
            {
                if (string.IsNullOrEmpty(language))
                {
                    language = appRequestConfig.Language;
                }
                if (ImageData != null && ImageData.TryGetValue(language, out var images))
                {
                    return images;
                }
                ImageData = MemoryCacheHelper.GetCache<ConcurrentDictionary<string, ConcurrentDictionary<int, string>>>(key);
                if (ImageData == null)
                {
                    ImageData = new ConcurrentDictionary<string, ConcurrentDictionary<int, string>>();

                }
                if (!ImageData.TryGetValue(language, out images))
                {
                    ImageData.TryAdd(language, images = new ConcurrentDictionary<int, string>());
                    MemoryCacheHelper.SetCache(key, ImageData, 60 * 60 * 24);
                }

                return images;



            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="language"></param>
        /// <param name="imageId"></param>
        /// <returns></returns>
        public string this[string language, int imageId]
        {
            get
            {
                if (imageId == 0)
                {
                    return "";
                }
                var _imageData = this[language];
                if (_imageData == null)
                {
                    _imageData = new ConcurrentDictionary<int, string>();
                }
                if (!_imageData.TryGetValue(imageId, out var imageUrl))
                {
                    var imageValue = database.StringGet($"{redisKey}:{language}:{imageId}");
                    if (imageValue.IsNullOrEmpty)
                    {
                        imageValue = database.StringGet($"{redisKey}:default:{imageId}");
                    }
                    if (!IsLoadImage && imageValue.IsNullOrEmpty)
                    {
                        if (!database.KeyExists(redisKey))
                        {
                            ImageData = LoadImage(dao, appConfig);
                            MemoryCacheHelper.SetCache(key, ImageData, 60 * 60 * 24);
                            IsLoadImage = true;
                            _imageData = ImageData[language];
                            if (!_imageData.TryGetValue(imageId, out imageUrl))
                            {
                                imageUrl = "";
                            }
                            return imageUrl;
                        }
                    }
                    imageUrl = imageValue;
                    _imageData.TryAdd(imageId, imageUrl);
                    //if (!_imageData.TryGetValue(imageId, out imageUrl))
                    //{
                    //    if (string.IsNullOrEmpty(imageUrl))
                    //    {
                    //        imageUrl = "";
                    //    }

                    //}//imageValue.ToString();

                    //MemoryCacheHelper.SetCache(key, ImageData, 60 * 60 * 24);

                }
                return imageUrl;
            }
        }

        public ConcurrentDictionary<string, ConcurrentDictionary<int, string>> LoadImage(DAO dao, AppConfig appConfig)
        {
            // 初始化_data字典
            ConcurrentDictionary<string, ConcurrentDictionary<int, string>> _data = new ConcurrentDictionary<string, ConcurrentDictionary<int, string>>();

            // 获取图像列表
            var imageList = dao.DaoExt.Context.T_App_Image
                .Where(it => !string.IsNullOrEmpty(it.Url))
                .AsNoTracking()
                .Select(it => new { it.ImageId, it.Language, it.Url })
                .ToList();

            // 设置默认语言
            if (string.IsNullOrEmpty(appConfig.DefaultLanguage))
            {
                appConfig.DefaultLanguage = "zh";
            }

            // 创建默认语言的图像字典
            var defaultImage = imageList
                .Where(it => it.Language == appConfig.DefaultLanguage)
                .GroupBy(it => it.ImageId)
                .ToDictionary(group => group.Key, group => appConfig.AliyunConfig.ImagePrefix + group.Last().Url);

            // 遍历图像列表，填充_data字典
            foreach (var item in imageList)
            {
                // 尝试获取语言字典，如果不存在则创建
                if (!_data.TryGetValue(item.Language, out var languageImage))
                {
                    languageImage = new ConcurrentDictionary<int, string>();
                    _data[item.Language] = languageImage;
                }

                // 设置图像URL
                languageImage[item.ImageId] = appConfig.AliyunConfig.ImagePrefix + item.Url;

                // 如果默认图像字典中没有此ImageId，加入默认图像字典
                if (!defaultImage.ContainsKey(item.ImageId))
                {
                    defaultImage[item.ImageId] = appConfig.AliyunConfig.ImagePrefix + item.Url;
                }
            }

            // 更新默认语言的图像字典
            _data["default"] = new ConcurrentDictionary<int, string>(defaultImage);
            foreach (var item in _data.Keys)
            {
                foreach (var image in _data[item])
                {
                    string _redisKey = $"{redisKey}:{item}:{image.Key}";
                    database.StringSet(_redisKey, image.Value, TimeSpan.FromDays(1));
                }
            }
            database.StringSet(redisKey, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromDays(1));
            return _data;
        }

        public string this[int imageId]
        {
            get
            {
                var imageUrl = this[appRequestConfig.Language, imageId];
                return imageUrl;
            }
        }

        public bool ClearData()
        {
            throw new NotImplementedException();
        }

        public void ReloadData()
        {
            throw new NotImplementedException();
        }
    }
}
