using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using UnityEngine;

namespace RedHotRoast
{
    public static class PreDownloadManager
    {
        #region Live

        public static void InitializeLiveData()
        {
            var liveConfigList = ConfigSystem.GetConfig<Live>();

            Debug.Log($"[预下载视频 数据初始化]-0-----{DataMgr.LiveDataDic.Value.Count}");

            var newData = new Dictionary<int, LiveData>();

            for (var i = 0; i < liveConfigList.Count; i++)
            {
                var oldData = GetLiveDataByIndex(liveConfigList[i], i);

                if (oldData.progress > 0) newData[i] = oldData;
            }

            Debug.Log($"[预下载视频 数据初始化]--1----- {newData.Count}");
            DataMgr.LiveDataDic.Value = newData;
        }

        public static LiveData GetLiveDataByIndex(Live liveConfig, int i)
        {
            DataMgr.LiveDataDic.Value.TryGetValue(i, out var oldData);

            oldData ??= new LiveData
            {
                progress = liveConfig.Progress,
                AD_num = 0,
                Singleprogress = (100 - liveConfig.Progress) / liveConfig.AD
            };

            if (oldData.progress < liveConfig.Progress) oldData.progress = liveConfig.Progress;

            return oldData;
        }

        // 最大同时下载数量
        private const int MaxConcurrentDownloads = 1;

        public static void StartDownload()
        {
            CrazyAsyKit.StartCoroutine(DownloadVideosCoroutine());
        }

        private static IEnumerator DownloadVideosCoroutine()
        {
            var liveConfigList = ConfigSystem.GetConfig<Live>();
            var liveDic = DataMgr.LiveDataDic.Value;

            var downloadNameList = new List<string>();

            // 先加入已有进度的视频
            foreach (var kvp in liveDic)
            {
                var index = kvp.Key;
                var data = kvp.Value;

                if (data.progress > 0 && index < liveConfigList.Count) downloadNameList.Add(liveConfigList[index].Name);
            }

            Debug.Log($"[init down video]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            // 添加不在downloadNameList中的项，最多添加6个
            var addedCount = 0;
            for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++)
                if (!downloadNameList.Contains(liveConfigList[i].Name))
                {
                    downloadNameList.Add(liveConfigList[i].Name);
                    addedCount++;
                }

            Debug.Log($"[init down video]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            // 当前正在下载的协程数量
            var runningCount = 0;
            var currentIndex = 0;

            if (downloadNameList.Count > 0)
            {
                var name = downloadNameList[currentIndex];

                var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.VideoName, name + ".enc");
                Debug.Log($"[预下载 视频 路径]-------localPath===={localPath}");

                if (!File.Exists(localPath))
                {
                    Debug.Log("[开始预下载 视频 ]---------------");
                    runningCount++;
                    CrazyAsyKit.StartCoroutine(DownloadSingleVideoCoroutine(name, () => { runningCount--; }));
                }
            }

            // 等待下一帧再检查
            yield return null;
            Debug.Log("[init down video]---All downloads finished---");
        }


        private static IEnumerator DownloadSingleVideoCoroutine(string name, Action onComplete)
        {
            var isDone = false;

            LiveVideoManager.Instance.GetVideoLocalPath(name, tex =>
            {
                Debug.Log($"[init down video]----------------{name}");
                isDone = true;
            }, false);

            // 等待下载完成
            while (!isDone) yield return null;

            onComplete?.Invoke();
        }

        #endregion


        #region Picture

        public static void StartDownloadSecretPicture()
        {
            var liveConfigList = ConfigSystem.GetConfig<SecretAlbums>();
            var liveList = DataMgr.SecretUnlockList.Value;

            var downloadNameList = new List<string>();

            // 先加入所有可用的图片
            for (var i = 0; i < liveList.Count; i++)
                if (liveConfigList[i] != null && !downloadNameList.Contains(liveConfigList[i].Name))
                    downloadNameList.Add(liveConfigList[i].Name);

            Debug.Log(
                $"[init down picture Secret]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            // 添加不在downloadNameList中的项，最多添加6个
            var addedCount = 0;
            for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++)
                if (!downloadNameList.Contains(liveConfigList[i].Name))
                {
                    downloadNameList.Add(liveConfigList[i].Name);
                    addedCount++;
                }

            Debug.Log(
                $"[init down picture Secret]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            foreach (var name in downloadNameList)
            {
                var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.SecretName, name + ".jpg");
                Debug.Log($"[预下载 Secret 路径]-------localPath===={localPath}");
                if (!File.Exists(localPath))
                {
                    Debug.Log("[开始预下载 Secret ]---------------");
                    TextureHelper.SetImgLoader(null, name,
                        s =>
                        {
                            Debug.Log($"[init down Secret picture]----------------{name}");
                        }, "SecretAlbums/", FolderNames.SecretName, false);
                }
            }
        }

        public static void StartDownloadAlbumsPicture()
        {
            int Free_Alubum_0 = PlayerPrefs.GetInt("Free_Alubum_0", -1);
            int Free_Alubum_1 = PlayerPrefs.GetInt("Free_Alubum_1", -1);
            int AD_Alubum = PlayerPrefs.GetInt("AD_Alubum", -1);
            int Spec_Alubum = PlayerPrefs.GetInt("Spec_Alubum", -1);
            int Vip_Alubum = PlayerPrefs.GetInt("Vip_Alubum", -1);

            if (Free_Alubum_0 >= 0) return;

            var FreeImageLibrary_ = ConfigSystem.GetConfig<FreeImageLibrary>();
            var ADImageLibrary_ = ConfigSystem.GetConfig<ADImageLibrary>();
            var SpecialImageLibrary_ = ConfigSystem.GetConfig<SpecialImageLibrary>();
            var VIPImageLibrary_ = ConfigSystem.GetConfig<VIPImageLibrary>();

            List<int> free_level_list = new List<int>();
            List<int> ad_level_list = new List<int>();
            List<int> special_level_list = new List<int>();
            List<int> vip_level_list = new List<int>();
            for (int i = 0; i < DataMgr.LevelUnlockListNew.Value.Count; i++)
            {
                if (DataMgr.LevelUnlockListNew.Value[i].type == 0) free_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index);
                else if (DataMgr.LevelUnlockListNew.Value[i].type == 1) ad_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index);
                else if (DataMgr.LevelUnlockListNew.Value[i].type == 2) special_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index);
                else if (DataMgr.LevelUnlockListNew.Value[i].type == 3) vip_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index);
            }


            if (Free_Alubum_0 < 0)
            {
                HashSet<int> levelIds = new HashSet<int>(free_level_list);
                List<FreeImageLibrary> filtered = ConfigSystem.GetConfig<FreeImageLibrary>().Where(x => !levelIds.Contains(x.id)).ToList();
                if (filtered.Count > 0)
                {
                    Free_Alubum_0 = filtered[UnityEngine.Random.Range(0, filtered.Count)].id;
                }
                else
                {
                    Free_Alubum_0 = ConfigSystem.GetConfig<FreeImageLibrary>()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig<FreeImageLibrary>().Count)].id;
                }
                free_level_list.Add(Free_Alubum_0);
                Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,");
            }
            if (Free_Alubum_1 < 0)
            {
                HashSet<int> levelIds = new HashSet<int>(free_level_list);
                List<FreeImageLibrary> filtered = ConfigSystem.GetConfig<FreeImageLibrary>().Where(x => !levelIds.Contains(x.id)).ToList();
                if (filtered.Count > 0)
                {
                    Free_Alubum_1 = filtered[UnityEngine.Random.Range(0, filtered.Count)].id;
                }
                else
                {
                    Free_Alubum_1 = ConfigSystem.GetConfig<FreeImageLibrary>()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig<FreeImageLibrary>().Count)].id;
                }
                Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,");
            }


            if (AD_Alubum < 0)
            {
                HashSet<int> levelIds = new HashSet<int>(ad_level_list);
                List<ADImageLibrary> filtered = ConfigSystem.GetConfig<ADImageLibrary>().Where(x => !levelIds.Contains(x.id)).ToList();
                if (filtered.Count > 0)
                {
                    AD_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id;
                }
                else
                {
                    AD_Alubum = ConfigSystem.GetConfig<ADImageLibrary>()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig<ADImageLibrary>().Count)].id;
                }
                Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,");
            }

            if (Spec_Alubum < 0)
            {
                HashSet<int> levelIds = new HashSet<int>(special_level_list);
                List<SpecialImageLibrary> filtered = ConfigSystem.GetConfig<SpecialImageLibrary>().Where(x => !levelIds.Contains(x.id)).ToList();
                if (filtered.Count > 0)
                {
                    Spec_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id;
                }
                else
                {
                    Spec_Alubum = ConfigSystem.GetConfig<SpecialImageLibrary>()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig<SpecialImageLibrary>().Count)].id;
                }
                Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,");
            }

            if (Vip_Alubum < 0)
            {
                HashSet<int> levelIds = new HashSet<int>(vip_level_list);
                List<VIPImageLibrary> filtered = ConfigSystem.GetConfig<VIPImageLibrary>().Where(x => !levelIds.Contains(x.id)).ToList();
                if (filtered.Count > 0)
                {
                    Vip_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id;
                }
                else
                {
                    Vip_Alubum = ConfigSystem.GetConfig<VIPImageLibrary>()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig<VIPImageLibrary>().Count)].id;
                }
                Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,");
            }
            PlayerPrefs.SetInt("Free_Alubum_0", Free_Alubum_0);
            PlayerPrefs.SetInt("Free_Alubum_1", Free_Alubum_1);
            PlayerPrefs.SetInt("AD_Alubum", AD_Alubum);
            PlayerPrefs.SetInt("Spec_Alubum", Spec_Alubum);
            PlayerPrefs.SetInt("Vip_Alubum", Vip_Alubum);

            var downloadNameList = new List<string>
            {
                FreeImageLibrary_[Free_Alubum_0].Name,
                FreeImageLibrary_[Free_Alubum_1].Name,
                ADImageLibrary_[AD_Alubum].Name,
                SpecialImageLibrary_[Spec_Alubum].Name,
                VIPImageLibrary_[Vip_Alubum].Name
            };

            Debug.Log(
                $"[init down picture Album]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            // 添加不在downloadNameList中的项，最多添加12个
            // var addedCount = 0;
            // for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++)
            //     if (!downloadNameList.Contains(liveConfigList[i].Name))
            //     {
            //         downloadNameList.Add(liveConfigList[i].Name);
            //         addedCount++;
            //     }

            Debug.Log(
                $"[init down picture Album]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            // int centerIndex = GameHelper.GetLevel();
            // int totalCount = downloadNameList.Count;

            // // 计算起始索引和实际要取的数量
            // int rangeStart = Math.Max(0, centerIndex - 5);
            // int rangeEnd = Math.Min(totalCount, centerIndex + 5);
            // int rangeCount = rangeEnd - rangeStart;

            // // 获取范围内元素并反转
            // var segment = downloadNameList.GetRange(rangeStart, rangeCount);
            // segment.Reverse();

            // // 移除原始位置的元素
            // downloadNameList.RemoveRange(rangeStart, rangeCount);

            // // 插入反转后的元素到最前面
            // downloadNameList.InsertRange(0, segment);


            Debug.Log(
                $"[init down picture Album]---3---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            foreach (var name in downloadNameList)
            {
                var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.AlbumName, name + ".jpg");
                Debug.Log($"[预下载 Albums 路径]-------localPath===={localPath}");
                if (!File.Exists(localPath))
                {
                    Debug.Log($"[开始预下载 Albums ]--------------name-{name}");
                    TextureHelper.SetImgLoader(null, name,
                        s =>
                        {
                            Debug.Log($"[init down Album picture]----------------{name}");
                        }, "LevelAlbums/", FolderNames.AlbumName, false);
                }
            }
        }

        public static void StartDownloadLivePicture()
        {
            var liveConfigList = ConfigSystem.GetConfig<Live>();
            var liveList = DataMgr.SecretUnlockList.Value;

            var downloadNameList = new List<string>();

            // 先加入所有可用的图片
            for (var i = 0; i < liveConfigList.Count; i++)
                if (liveConfigList[i] != null && !downloadNameList.Contains(liveConfigList[i].Name))
                    downloadNameList.Add(liveConfigList[i].Name);

            Debug.Log(
                $"[init down picture LiveCover]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}");

            // 添加不在downloadNameList中的项，最多添加6个

            foreach (var name in downloadNameList)
            {
                var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.VideoCoversName, name + "_cover" + ".jpg");
                Debug.Log($"[预下载 Secret 路径]-------localPath===={localPath}");
                if (!File.Exists(localPath))
                {
                    Debug.Log("[开始预下载 Secret ]---------------");
                    TextureHelper.SetImgLoader(null, name + "_cover",
                        s =>
                        {
                            Debug.Log($"[init down VideoCovers picture]----------------{name}");
                        }, "LiveAlbums/", FolderNames.VideoCoversName, false);
                }
            }
        }

        #endregion
    }
}