using FairyGUI;
using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;

using UnityEngine.Events;
using System.Collections;
using UnityEngine.Networking;
using ChillConnect;
using SGModule.Net;

public class TextureHelper
{
    private static Dictionary<string, NTexture> nTexturesDic = new();
    private static Dictionary<int, NTexture> avatarNTexturesDic = new();
    private static Dictionary<int, NTexture> galleryNTexturesDic = new Dictionary<int, NTexture>();

    public static void GetNTexture(string path, string name, UnityAction<NTexture> action)
    {
        if (!nTexturesDic.TryGetValue(path + name, out NTexture spr))
        {
            try
            {
                LoadKit.Instance.LoadSprite(path, name, sprite =>
                {
                    if (sprite != null)
                    {
                        spr = new NTexture(sprite);
                        action?.Invoke(spr);
                        nTexturesDic.TryAdd(path + name, spr);
                    }
                });
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        else
        {
            action?.Invoke(spr);
        }
    }

    #region 加载Texture

    private static IEnumerator GetLocalTexture(string imagePath, Action<Texture> action)
    {
        var file = $"{CommonHelper.GetAppSavePath()}/{imagePath}";
        var fileInfo = new FileInfo(file);
        if (!fileInfo.Exists)
        {
            action?.Invoke(null);
            yield break;
        }

        var avatarPath = $"file://{file}";
        var uwr = UnityWebRequestTexture.GetTexture(avatarPath);
        yield return uwr.SendWebRequest();
        if (uwr.result is UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError)
        {
            action?.Invoke(null);
            yield break;
        }

        var texture2D = DownloadHandlerTexture.GetContent(uwr);

        action?.Invoke(texture2D);
    }

    public static void GetCardIcon(bool isLogo = false, UnityAction<NTexture> action = null)
    {
        var cardIconPath = "logo_default";
        // var paymentTypeVo = GameHelper.GetPaymentTypeVO();
        // if (isLogo)
        // {
        //     cardIconPath = paymentTypeVo.logo_id;
        // }
        // else
        // {
        //     cardIconPath = paymentTypeVo.card_name;
        // }


        GetNTexture("Atlas.Pay", cardIconPath, action);
    }

    private static IEnumerator GetTextureFromNet(string type, int imgId, string imgUrl, Action<bool> action = null)
    {
        string imagePath = $"{CommonHelper.GetAppSavePath()}/{type}/{imgId}.jpg";
        FileInfo fileInfo = new FileInfo(imagePath);
        if (fileInfo.Exists)
        {
            action?.Invoke(true);
            yield break;
        }

        var avatarRequest = UnityWebRequest.Get(imgUrl);
        yield return avatarRequest.SendWebRequest();
        if (avatarRequest.result == UnityWebRequest.Result.ConnectionError ||
            avatarRequest.result == UnityWebRequest.Result.ProtocolError)
        {
            action?.Invoke(false);
        }
        else
        {
            var avatarData = avatarRequest.downloadHandler.data;
            var dirPath = Path.GetDirectoryName(imagePath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            if (fileInfo.Exists) yield break;
            Stream stream = fileInfo.Create();
            stream.Write(avatarData, 0, avatarData.Length);
            stream.Close();
            stream.Dispose();
            action?.Invoke(true);
        }
    }

    #endregion


    public static void GetItemIcon(int itemId, UnityAction<NTexture> action = null)
    {
        var itemIconPath = "Atlas.Item";
        string name = itemId.ToString();
        if (!true)
        {
            if (itemId is 101 or 111)
            {
                name = "102";
            }
        }
        else
        {
            if (itemId is 102 or 106)
            {
                name += "_normal";
            }
        }

        GetNTexture(itemIconPath, name, action);
    }

    #region 头像相关

    public static void SetAvatarToLoader(int avatarId, GLoader _GLoader, bool IsNeedDefAvatar = true)
    {
        if (!avatarNTexturesDic.TryGetValue(avatarId, out NTexture spr))
        {
            try
            {
                Sprite sprite = null;
                if (avatarId == 0)
                {
                    if (!PlayerPrefsKit.ReadBool("IsLogin"))
                    {
                        avatarId = 1;
                        SetAvatarToLoader(avatarId, _GLoader);
                        return;
                    }
                    else
                    {
                        if (PlayerPrefsKit.ReadString("AvatarUrl").IsNullOrWhiteSpace())
                        {
                            _GLoader.url = "ui://pmf3wbjicxrg4";
                            return;
                        }
                        else
                        {
                            GetSelfFaceBookAvatar(texture =>
                            {
                                if (_GLoader != null)
                                {
                                    if (texture != null)
                                    {
                                        _GLoader.texture = texture;
                                    }
                                    else
                                    {
                                        _GLoader.url = "ui://pmf3wbjicxrg4";
                                    }
                                }
                            });
                            return;
                        }
                    }
                }
                else if (avatarId > 100)
                {
                    if (IsNeedDefAvatar)
                    {
                        _GLoader.url = "ui://pmf3wbjicxrg4";
                    }

                    GetFaceBookAvatar(avatarId, (e) =>
                    {
                        if (_GLoader != null)
                        {
                            if (e == null)
                            {
                                _GLoader.url = "ui://pmf3wbjicxrg4";
                            }
                            else
                            {
                                _GLoader.texture = e;
                            }
                        }
                    });
                    return;
                }
                else
                {
                    LoadKit.Instance.LoadSprite("Atlas.Avatar", avatarId.ToString(), (spr) =>
                    {
                        sprite = spr;
                        var spr1 = new NTexture(sprite);
                        _GLoader.texture = spr1;
                        avatarNTexturesDic.Add(avatarId, spr1);
                    });
                }
            }
            catch (System.Exception e)
            {
                UnityEngine.Debug.LogError(e);
            }
        }
        else
        {
            _GLoader.texture = spr;
        }
    }


    private static IEnumerator GetAvatarLocal(int avatarId, Action<Texture> action)
    {
        yield return GetLocalTexture($"Avatar/{avatarId}.jpg", action);
    }

    #endregion

    #region FaceBook头像相关

    public static void GetFaceBookAvatar(int avatarId, Action<NTexture> action)
    {
        if (!avatarNTexturesDic.TryGetValue(avatarId, out NTexture spr))
        {
            HallManager.Instance.StartCoroutine(GetAvatarLocal(avatarId, texture =>
            {
                if (texture == null)
                {
                    action?.Invoke(null);
                    return;
                }

                spr = new NTexture(texture);
                if (avatarNTexturesDic.ContainsKey(avatarId))
                {
                    avatarNTexturesDic.Add(avatarId, spr);
                }

                action?.Invoke(spr);
            }));
        }
        else
        {
            action?.Invoke(spr);
        }
    }


    public static void GetSelfFaceBookAvatar(Action<NTexture> action)
    {
        if (!avatarNTexturesDic.TryGetValue(0, out NTexture spr))
        {
        }
        else
        {
            action?.Invoke(spr);
        }
    }

    #endregion


    //public static IEnumerator GetGalleryFromNet(int imageID, Action<bool> action = null)
    //{
        // if (imageID == 0)
        // {
        //     action?.Invoke(true);
        // }
        // else
        // {
        //     string picInfoUrl = $"{NetworkKit.Instance.GetLoginModel().CdnURL}gallery/{imageID}.jpg";
        //     yield return GetTextureFromNet("Gallery", imageID, picInfoUrl, action);
        // }
    //}

    public static string GetBankIconUrl(string icon_name)
    {
        return string.Format("ui://G002_main/{0}", icon_name);
    }

    public static void GetGalleryLocal(int imageID, Action<NTexture> action)
    {
        // if (!galleryNTexturesDic.TryGetValue(imageID, out NTexture spr))
        // {
        //     var path = $"Gallery/{imageID}";
        //     var asset = Resources.Load($"Atlas/{path}");
        //     if (asset)
        //     {
        //     }
        //     else
        //     {
        //         CrazyAsyKit.StartCoroutine(GetGalleryFromNet(imageID, (bool isSuccess) =>
        //         {
        //             if (isSuccess)
        //             {
        //                 CrazyAsyKit.StartCoroutine(GetLocalTexture($"{path}.jpg", texture =>
        //                 {
        //                     if (texture == null)
        //                     {
        //                         action?.Invoke(null);

        //                         return;
        //                     }

        //                     var spr1 = new NTexture(texture);
        //                     galleryNTexturesDic.TryAdd(imageID, spr1);
        //                     action?.Invoke(spr1);
        //                 }));
        //             }
        //             else
        //             {
        //                 action?.Invoke(null);
        //             }
        //         }));
        //     }
        // }
        // else
        // {
        //     action?.Invoke(spr);
        // }
    }
}
