using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using FairyGUI;
using FGUI.LG_secretAlbums;
using SGModule.Common.Helper;
using SGModule.NetKit;
using UnityEngine;

namespace RedHotRoast
{
    public class SecretAlbumsNextUI : BaseUI
    {
        private SecretAlbumsNextUICtrl ctrl;
        private SecretAlbumsNextModel model;
        private FGUI.LG_secretAlbums.com_scAlbumPreview ui;

        public SecretAlbumsNextUI(SecretAlbumsNextUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.SecretAlbumsNextUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "LG_secretAlbums";
            uiInfo.assetName = "com_scAlbumPreview";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

        #region 生命周期

        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.SecretAlbumsModel) as SecretAlbumsModel;
        }

        protected override void OnClose()
        {
            HallManager.Instance.UpdateSecondEvent -= UpWatchAdsBtn;

            // 清理 Loader 的材质和贴图
            foreach (var loader in loader_list)
            {
                if (loader == null || loader.isDisposed) continue;

                // 释放材质到材质池
                if (loader.material != null)
                {
                    TextureHelper.CancelImageBlur(loader); // 自动返回材质池
                    loader.material = null;
                }

                // 清理 NTexture
                if (loader.texture != null)
                {
                    if (loader.texture.destroyMethod == DestroyMethod.Destroy)
                        loader.texture.Dispose(); // 销毁 NTexture 对象
                    loader.texture = null;
                }
            }
            loader_list.Clear();

            // 强制卸载未使用的资源
            Resources.UnloadUnusedAssets();
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.LG_secretAlbums.com_scAlbumPreview;
        }

        private AlbumPreviewData _albumPreviewData;

        protected override void OnOpenBefore(object args)
        {
            if (args == null) return;

            _albumPreviewData = (AlbumPreviewData)args;

            InitView();

            var event_names = ADEventTrack.Property.secret_albums_show + (_albumPreviewData.Index + 1);

            var event_type = _albumPreviewData.PayType == (int)UnlockPayType.Ad ? ADEventTrack.Event : ADEventTrack.MaxPayEvent;
            TrackKit.SendEvent(event_type, event_names);

        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.AddListener(GameMsg.BuyVip, InitView);
        }

        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, InitView);
        }

        #endregion

        void pay_success(object str)
        {
            string type = (string)str;
            string purch_number = "";

            if (type.StartsWith("secret_albnums"))
            {
                int startIndex = "secret_albnums".Length;
                string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符
                int suffix_num = int.Parse(suffix);

                Log.Info("Secret_pay_success", $"index================:{suffix_num}");
                // 判断是否已存在，避免重复添加
                if (!DataMgr.SecretUnlockList.Value.Contains(suffix_num))
                {
                    DataMgr.SecretUnlockList.Value.Add(suffix_num);
                    DataMgr.SecretUnlockList.Save();

                    GameDispatcher.Instance.Dispatch(GameMsg.UnlockSecretSuccess);
                }
                GameHelper.ShowTips("purchase_succ", true);
                InitView();
            }
        }

        private List<string> _secretData;

        private bool is_unlock = false; //当前专辑是否解锁
        private List<GLoader> loader_list = new List<GLoader>();
        //初始化页面逻辑
        private void InitView(object a = null)
        {
            // 先清理上一次的 loader 和任务
            foreach (var l in loader_list)
            {
                if (l != null && !l.isDisposed)
                {
                    TextureHelper.CancelImageBlur(l); // 放回材质池
                    if (l.texture != null)
                    {
                        l.texture.Dispose();
                        l.texture = null;
                    }
                    if (l.material != null) l.material = null;
                }
            }
            loader_list.Clear();
            _tasks.Clear();


            //专辑解锁状态
            is_unlock = DataMgr.SecretUnlockList.Value.Contains(_albumPreviewData.Index);

            UpWatchAdsBtn();

            HallManager.Instance.UpdateSecondEvent += UpWatchAdsBtn;

            ui.btn_close.SetClick(CtrlCloseUI);

            ui.old_price.text = GameHelper.getPrice((decimal)_albumPreviewData.Price);

            ui.btn_pay.title = GameHelper.getPrice((decimal)_albumPreviewData.DiscountPrice);


            _secretData = SplitStringToList(_albumPreviewData.Name2);


            ui.list.itemRenderer = ItemRender;
            ui.list.numItems = _secretData.Count;

            ui.pay_type.selectedIndex = !is_unlock ? _albumPreviewData.PayType : (int)UnlockPayType.None;
            if (is_unlock)
            {
                ui.pay_type.selectedIndex = (int)UnlockPayType.None;
            }
            else
            {
                if (_albumPreviewData.SubscribeUnlock == 1)
                {
                    ui.vip.selectedIndex = 1;
                    if (GameHelper.GetVipLevel() > 0)
                    {
                        ui.has_vip.selectedIndex = 1;
                        ui.btn_vip.x = 540;
                        // ui.btn_vip.y -= 10;
                    }
                    else
                    {
                        ui.has_vip.selectedIndex = 0;
                    }
                }
                else
                {
                    ui.vip.selectedIndex = 0;
                }
                ui.pay_type.selectedIndex = _albumPreviewData.PayType;
            }
            var _type = "secret_albnums" + _albumPreviewData.Index;
            ui.btn_pay.SetClick(() =>
            {
                ApplePayClass maxPayData = new ApplePayClass
                {
                    amount = (int)Math.Round(_albumPreviewData.DiscountPrice * 100),
                    sku = _type,
                    currency = "USD"
                };
                MaxPayManager.Instance.Buy(maxPayData);
            });
            ui.btn_gold.title = _albumPreviewData.GoldCoins.ToString();
            ui.btn_gold.SetClick(() =>
            {
                if (GameHelper.Get101() >= _albumPreviewData.GoldCoins)
                {
                    GameHelper.AddGold(-_albumPreviewData.GoldCoins);
                    GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, _type);

                    string eventName = ADEventTrack.Property.secret_albums_success_ + (_albumPreviewData.Index + 1);
                    TrackKit.SendEvent(ADEventTrack.SecretAlbums, eventName);
                    GameDispatcher.Instance.Dispatch(GameMsg.Update101);
                    TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.unlock_secretAlbums_resources);
                }
                else
                {
                    GameHelper.ShowTips("no_enough_gold", true);

                    uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open);

                }
            });

            var AdCount = DataMgr.SecretUnlockADs.Value.GetValueOrDefault(_albumPreviewData.Index, 0);
            ui.btn_watch.ads.SetVar("ads", AdCount + "/" + _albumPreviewData.AD).FlushVars();
            ui.btn_watch.SetClick(() =>
            {

                if (AdCount >= _albumPreviewData.AD)
                {
                    GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, _type);
                }
                else
                {
                    GameHelper.ShowVideoAd("UnlockSecretAlbums", (isSuccess) =>
                    {
                        if (isSuccess)
                        {
                            var adTimes = Convert.ToInt32(GameHelper.GetNowTime());
                            DataMgr.SecretUnlockCd.Value[_albumPreviewData.Index] = adTimes + _albumPreviewData.CD;
                            DataMgr.SecretUnlockCd.Save();

                            var currentAdCount = DataMgr.SecretUnlockADs.Value.GetValueOrDefault(_albumPreviewData.Index, 0);
                            DataMgr.SecretUnlockADs.Value[_albumPreviewData.Index] = currentAdCount + 1;
                            DataMgr.SecretUnlockADs.Save();

                            string eventName = ADEventTrack.Property.secret_albums_success_ + (_albumPreviewData.Index + 1);
                            TrackKit.SendEvent(ADEventTrack.Event, eventName);

                            InitView();
                        }
                    });
                }
            });
            ui.btn_vip.SetClick(() =>
               {
                   TrackKit.SendEvent(ADEventTrack.SecretAlbums, ADEventTrack.Property.secret_albums_click_ + (_albumPreviewData.Index + 1));
                   if (GameHelper.GetVipLevel() > 0)
                   {
                       GameHelper.isVipUnlock = true;
                       GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, _type);

                       string eventName = ADEventTrack.Property.vip_secret_albums_unclock_ + (_albumPreviewData.Index + 1);
                       TrackKit.SendEvent(ADEventTrack.VipSecretAlbums, eventName);
                   }
                   else
                   {
                       uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open, 2);
                       TrackKit.SendEvent(ADEventTrack.VipSecretAlbums, ADEventTrack.Property.vip_secret_albums_unclock);
                   }
               });
        }

        private List<(GLoader loader, string fileName, Action<NTexture> callback, string folder, string localFolder)> _tasks = new();

        private void ItemRender(int index, GObject obj)
        {
            var item = (item_scAlbumPreview)obj;
            var picture = (GLoader)item.com_pic_in.GetChild("picture");

            if (!loader_list.Contains(picture))
                loader_list.Add(picture);

            var state = GetSafe(_albumPreviewData.State, index);
            item.state.selectedIndex = is_unlock ? 0 : state;

            var task = (picture, _secretData[index], (Action<NTexture>)(s =>
                {
                    if (picture != null && !picture.isDisposed)
                    {
                        if (!is_unlock && state == 1)
                            TextureHelper.SetImageBlur(picture);
                        else
                            TextureHelper.CancelImageBlur(picture);
                    }
                }), $"SecretAlbums/{_albumPreviewData.Name}/", FolderNames.SecretName);

            _tasks.Add(task);

            item.btn_detail.SetClick(() =>
            {
                if (is_unlock)
                {
                    var data = new DetailData
                    {
                        Name = _secretData[index],
                        Name1 = $"SecretAlbums/{_albumPreviewData.Name}/"
                    };
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretDetailUI_Open, data);
                }
                else
                {
                    GameHelper.ShowTips("not_unlocked", true);
                }
            });

            if (index == _secretData.Count - 1)
            {
                TextureHelper.SetImgLoaders(_tasks);
            }
        }



        private void UpWatchAdsBtn()
        {
            DataMgr.SecretUnlockCd.Value.TryGetValue(_albumPreviewData.Index, out var lastTimes);


            if (DataMgr.SecretUnlockADs.Value.TryGetValue(_albumPreviewData.Index, out var unlockAdValue) &&
                   unlockAdValue >= _albumPreviewData.AD)
            {
                ui.btn_watch.can_buy.selectedIndex = 1;
            }
            else
            {
                ui.btn_watch.can_buy.selectedIndex = 0;
                if (GameHelper.GetNowTime() < lastTimes)
                {
                    ui.btn_watch.enabled = false;
                    ui.btn_watch.CD.selectedIndex = 1;
                    ui.btn_watch.watch_cd.text =
                        CommonHelper.TimeFormat(lastTimes - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                }
                else
                {
                    ui.btn_watch.enabled = true;
                    ui.btn_watch.CD.selectedIndex = 0;

                }
            }
        }


        // 拆分字符串为列表
        public static List<string> SplitStringToList(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
                return new List<string>();

            // 支持英文逗号, 中文逗号，空格
            char[] separators = new char[] { ',', '，', ' ' };

            return input
                .Split(separators, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Trim()) // 去掉前后空白
                .ToList();
        }

        /// <summary>
        /// 安全获取列表或数组中的元素，如果越界则返回最后一个元素；如果为空则返回默认值。
        /// </summary>
        public static T GetSafe<T>(IList<T> list, int index, T defaultValue = default)
        {
            if (list == null || list.Count == 0)
                return defaultValue;

            if (index < 0)
                return list[0];

            if (index >= list.Count)
                return list[list.Count - 1];

            return list[index];
        }
    }

    public class DetailData
    {
        public string Name;
        public string Name1;
    }
}