using System;
using System.Collections.Generic;
using DG.Tweening;
using FairyGUI;
using FGUI.LG_Common;
using FGUI.LG_End;
using FGUI.ZM_Common_01;
using Newtonsoft.Json;
using Spine.Unity;
using UnityEngine;
using btn_claim = FGUI.LG_Common.btn_claim;
using SGModule.Common.Extensions;
using System.Linq;
using SGModule.NetKit;
namespace RedHotRoast
{
    public class NewEndUI : BaseUI
    {
        private readonly List<GLoader> loader_list = new();
        private readonly List<int> rate_list = new();
        private Action closeCallback;
        private NewEndUICtrl ctrl;


        private List<item_wheel> list_1;
        private NewEndModel model;
        private int next_level;
        private int rate_idnex = 3;
        private int scroll_number;
        private int scroll_type = 1;
        private com_newend ui;

        public NewEndUI(NewEndUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.NewEndUI;
            this.ctrl = ctrl;
        }

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

        private void UnlockLevelsuccess(object a = null)
        {
            CtrlCloseUI();
        }

        private void endClose()
        {
            var lv = GameHelper.GetCommonModel().MultiModal;
            if (GameHelper.GetLevel() >= GameHelper.GetCommonModel().MultiModal)
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelNewUI_Open);
                is_unlock_level = true;
            }
            CtrlCloseUI();
        }

        //初始化页面逻辑
        private void InitView()
        {
            if (GameHelper.IsGiftSwitch())
            {
                if (!loader_list.Contains(ui.loader_bgimg)) loader_list.Add(ui.loader_bgimg);

                // TextureHelper.SetImgLoader(ui.loader_bgimg, LevelData.Name, null, "LevelAlbums/");
                if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal)
                {
                    int level_ = GameHelper.GetLevel() - 1;
                    if (level_ < 0) level_ = 0;
                    if (level_ >= ConfigSystem.GetConfig<LevelUnlock>().Count) level_ = ConfigSystem.GetConfig<LevelUnlock>().Count - 1;
                    TextureHelper.SetImgLoader(ui.loader_bgimg, ConfigSystem.GetConfig<LevelUnlock>()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName);
                }
                else
                {
                    Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel());
                    if (levelunlock_ != null)
                    {
                        if (levelunlock_.type == 0)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<FreeImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<FreeImageLibrary>().Count - 1;
                            FreeImageLibrary _leveldata = ConfigSystem.GetConfig<FreeImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                        }
                        else if (levelunlock_.type == 1)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<ADImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<ADImageLibrary>().Count - 1;
                            ADImageLibrary _leveldata = ConfigSystem.GetConfig<ADImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                        }
                        else if (levelunlock_.type == 2)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<SpecialImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<SpecialImageLibrary>().Count - 1;
                            SpecialImageLibrary _leveldata = ConfigSystem.GetConfig<SpecialImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                        }
                        else if (levelunlock_.type == 3)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<VIPImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<VIPImageLibrary>().Count - 1;
                            VIPImageLibrary _leveldata = ConfigSystem.GetConfig<VIPImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                        }
                    }
                    else
                    {
                        int level_ = GameHelper.GetLevel() - 1;
                        if (level_ < 0) level_ = 0;
                        if (level_ >= ConfigSystem.GetConfig<LevelUnlock>().Count) level_ = ConfigSystem.GetConfig<LevelUnlock>().Count - 1;
                        TextureHelper.SetImgLoader(ui.loader_bgimg, ConfigSystem.GetConfig<LevelUnlock>()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName);
                    }
                }
            }

            ui.tetx_level.text = Language.GetContentParams("level", successData_.level);
            ui.text_award.text = successData_.ch_number.ToString();
            Debug.Log(JsonConvert.SerializeObject(successData_) + "/////////////////");
            Debug.Log("/////////////////4");

            // if (!successData_.IsWin) ui.text_award.text = DataMgr.Coin.Value.ToString();
            Debug.Log(GetNextSpecialLevel());
            next_level = GetNextSpecialLevel();

            var levelUnlock_ = ConfigSystem.GetConfig<LevelUnlock>()[next_level];
            if (levelUnlock_.LeveType == 1)
                ui.text_levelType.text = "Special level";
            else if (levelUnlock_.LeveType == 2) ui.text_levelType.text = "VIP level";
            ui.progress_level.max = next_level;
            ui.progress_level.value = successData_.level;
            // if (successData_.IsLevelSuccess && successData_.level == next_level)
            //     //打开解锁界面
            //     ui.btn_continue.SetClick(() =>
            //     {
            //         uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelUI_Open, next_level);
            //     });
            // else
            ui.btn_continue.SetClick(() =>
            {
                endClose();
            });
            ((btn_claim4)ui.btn_claim).title = $"{successData_.ch_number}";

            var delayTime = successData_.IsLevelSuccess ? 1f : 0f;
            if (!successData_.IsWin)
            {
                delayTime = 0f;
                ui.win_lose.selectedIndex = 0;
            }
            else
            {
                ui.win_lose.selectedIndex = 1;
            }
            if (!GameHelper.IsGiftSwitch()) delayTime = 0;
            ui.step.selectedIndex = !successData_.IsLevelSuccess || !successData_.IsWin ? 1 : 0;
            Debug.Log("/////////////////5");
            DOVirtual.DelayedCall(delayTime, () =>
            {
                Debug.Log(delayTime);
                Debug.Log("/////////////////6");
                ui.step.selectedIndex = 1;
                // var anim_bg = FXManager.Instance.SetFx<SkeletonAnimation>(ui.GetChild("bg_parent") as GGraph, Fx_Type.fx_end_bg, ref closeCallback);
                if (successData_.IsWin)
                {
                    // anim_bg.state.SetAnimation(0, "win", false);
                    // anim_bg.state.Complete += (trackEntry) =>
                    // {
                    //     anim_bg.state.SetAnimation(0, "win_stop", true);
                    // };
                    var fireworks = FXManager.Instance.SetFx<SkeletonAnimation>(ui.GetChild("congra_parent") as GGraph, Fx_Type.fx_win, ref closeCallback);
                    fireworks.state.SetAnimation(0, "out", true);

                    // var coin = FXManager.Instance.SetFx<SkeletonAnimation>(ui.GetChild("coin_parent") as GGraph, Fx_Type.fx_wins, ref closeCallback);
                    // coin.state.SetAnimation(0, "animation", true);
                    // coin.state.Complete += (trackEntry) =>
                    // {
                    //     coin.state.SetAnimation(0, "animation2", true);
                    // };

                    if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetCommonConf().FreeClaims)
                        ((btn_claim3)ui.btn_mult).state.selectedIndex = 1;
                    else ((btn_claim3)ui.btn_mult).state.selectedIndex = 0;
                    ui.btn_mult.SetClick(() =>
                    {
                        if (!GameHelper.GetCloseResult()) return;
                        if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetCommonConf().FreeClaims)
                        {
                            ui.btn_mult.touchable = ui.btn_claim.touchable = false;
                            SaveData.SaveDataFunc();
                            StartScroll();
                        }
                        else
                        {
                            GameHelper.ShowVideoAd("GameEnd", isSuccess =>
                            {
                                if (isSuccess)
                                {
                                    ui.btn_mult.touchable = ui.btn_claim.touchable = false;
                                    StartScroll();
                                }
                            });
                        }
                    });
                    ui.btn_claim.SetClick(() =>
                    {
                        if (!GameHelper.GetCloseResult()) return;
                        ui.btn_mult.touchable = ui.btn_claim.touchable = false;
                        DOVirtual.DelayedCall(2f, () => { GameHelper.addInterAdnumber(); });
                        GetReward(successData_.ch_number);
                    });

                    AudioManager.Instance.PlayDynamicEffect(AudioConst.Victoriously);
                }
                else
                {
                    // anim_bg.state.SetAnimation(0, "lose", false);
                    // anim_bg.state.Complete += (trackEntry) =>
                    // {
                    //     anim_bg.state.SetAnimation(0, "lose_stop", true);
                    // };

                    ui.btn_restart.SetClick(() =>
                    {
                        if (!GameHelper.GetCloseResult()) return;

                        GameHelper.addInterAdnumber();
                        if (!successData_.IsWin) GameHelper.SetLevelstate(3);
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Close);
                    });
                }
            });
            if (GameHelper.GetVipPrivilege(Subscription.DoubleLevelReward.As<int>())) ((wheel)ui.wheel).have_vip.selectedIndex = 1;
            if (successData_.boost_array != null)
            {
                ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll);
                ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() =>
                {
                    rate_idnex++;
                    ui.btn_mult.title =
                        GameHelper.Get101Str((decimal)successData_.ch_number *
                                             successData_.boost_array[rate_idnex % 5]);
                });
                ui.btn_mult.title =
                    GameHelper.Get101Str((decimal)successData_.ch_number * successData_.boost_array[rate_idnex]);

                list_1 = new List<item_wheel>
                {
                    ((wheel_)ui.wheel.GetChild("wheel_")).item_0, ((wheel_)ui.wheel.GetChild("wheel_")).item_1,
                    (ui.wheel.GetChild("wheel_") as wheel_).item_2, (ui.wheel.GetChild("wheel_") as wheel_).item_3,
                    (ui.wheel.GetChild("wheel_") as wheel_).item_4, (ui.wheel.GetChild("wheel_") as wheel_).item_5,
                    (ui.wheel.GetChild("wheel_") as wheel_).item_6, (ui.wheel.GetChild("wheel_") as wheel_).item_7
                };
                //  list_1[2].img_light.visible = true;

                for (var i = 0; i < list_1.Count; i++)
                {
                    list_1[i].type.selectedIndex = (i + scroll_number) % 3;
                    list_1[i].text_rate.text = "X" + successData_.boost_array[i % successData_.boost_array.Length];
                }
            }
        }

        private void StartScroll()
        {
            ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale =
                ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = 5.0f;
            scroll_type = 2;
        }

        private void Scroll()
        {
            if (scroll_type == 1)
            {
                scroll_number++;
                rate_list.Clear();
                for (var i = 0; i < 8; i++)
                    rate_list.Add(successData_.boost_array[(scroll_number + i) % successData_.boost_array.Length]);
                for (var i = 0; i < list_1.Count; i++)
                {
                    list_1[i].type.selectedIndex = (i + scroll_number) % 3;
                    list_1[i].text_rate.text = "X" + rate_list[i];
                }

                ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() =>
                {
                    rate_idnex++;
                    ui.btn_mult.title = GameHelper.Get101Str((decimal)successData_.ch_number *
                                                             successData_.boost_array[
                                                                 rate_idnex % successData_.boost_array.Length]);
                });

                ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll);
            }
            else
            {
                scroll_number++;

                rate_list.Clear();
                for (var i = 0; i < 8; i++)
                    rate_list.Add(successData_.boost_array[(scroll_number + i) % successData_.boost_array.Length]);

                // bool need_return = false;
                if (((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale < 2.2f &&
                    list_1[4].text_rate.text == "X" + successData_.rate)
                {
                    //开始领取
                    var reward = successData_.ch_number * successData_.rate;
                    if (GameHelper.GetVipPrivilege(Subscription.DoubleLevelReward.As<int>())) reward *= 2;
                    GetReward(reward);

                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
                    SaveData.GetSaveObject().LargeRewardNum++;
                    SaveData.SaveDataFunc();
                    return;
                }

                for (var i = 0; i < list_1.Count; i++)
                {
                    list_1[i].type.selectedIndex = (i + scroll_number) % 3;
                    list_1[i].text_rate.text = "X" + rate_list[i];
                }

                // if (need_return)
                // {
                //     (ui.wheel.GetChild("wheel_") as wheel_).t0.timeScale = 0;
                //     return;
                // }

                ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() =>
                {
                    rate_idnex++;
                    ui.btn_mult.title = GameHelper.Get101Str((decimal)successData_.ch_number *
                                                             successData_.boost_array[
                                                                 rate_idnex % successData_.boost_array.Length]);
                });

                ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll);
                ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale =
                    ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale - 0.3f;
            }
        }

        private void GetReward(float awardNum)
        {
            var startObj = ui.btn_mult;
            var endObj = ui.btn_gold;

            var pos = GameHelper.GetUICenterPosition(endObj);

            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(101, (decimal)awardNum, RewardOrigin.Play)
            {
                startPosition = GameHelper.GetUICenterPosition(startObj),
                endPosition = new Vector2(pos.x, pos.y)
            };

            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted(success =>
            {
                if (success)
                {
                    RefreshAwardNum((decimal)awardNum, 101);

                    if (successData_.IsLevelSuccess)
                    {
                        if (!loader_list.Contains(ui.com_loader.GetChild("loader") as GLoader))
                            loader_list.Add(ui.com_loader.GetChild("loader") as GLoader);

                        GameDispatcher.Instance.Dispatch(GameMsg.reset_game);


                        if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal)
                        {
                            TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                            var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload;
                            ui.btn_download_coin.SetClick(() =>
                            {
                                if (GameHelper.Get101() >= downloadCoinNum)
                                {
                                    GameHelper.AddGold(-downloadCoinNum);
                                    ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";
                                    TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName);
                                    TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download);
                                    endClose();
                                }
                                else
                                {
                                    GameHelper.ShowTips("no_enough_gold", true);
                                    uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open);
                                }
                            });

                            ui.btn_download.SetClick(() =>
                            {
                                if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As<int>()))
                                {
                                    TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName);
                                    endClose();
                                }
                                else
                                    GameHelper.ShowVideoAd("DownloadImage", isSuccess =>
                                    {
                                        if (isSuccess)
                                        {
                                            TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName);
                                            endClose();
                                        }
                                    });
                            });

                        }
                        else
                        {
                            Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel());
                            string file_name = "";
                            if (levelunlock_ != null)
                            {
                                if (levelunlock_.type == 0)
                                {
                                    if (levelunlock_.config_index >= ConfigSystem.GetConfig<FreeImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<FreeImageLibrary>().Count - 1;
                                    FreeImageLibrary _leveldata = ConfigSystem.GetConfig<FreeImageLibrary>()[levelunlock_.config_index];
                                    TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                                    file_name = _leveldata.Name;
                                }
                                else if (levelunlock_.type == 1)
                                {
                                    if (levelunlock_.config_index >= ConfigSystem.GetConfig<ADImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<ADImageLibrary>().Count - 1;
                                    ADImageLibrary _leveldata = ConfigSystem.GetConfig<ADImageLibrary>()[levelunlock_.config_index];
                                    TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                                    file_name = _leveldata.Name;
                                }
                                else if (levelunlock_.type == 2)
                                {
                                    if (levelunlock_.config_index >= ConfigSystem.GetConfig<SpecialImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<SpecialImageLibrary>().Count - 1;
                                    SpecialImageLibrary _leveldata = ConfigSystem.GetConfig<SpecialImageLibrary>()[levelunlock_.config_index];
                                    TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                                    file_name = _leveldata.Name;
                                }
                                else if (levelunlock_.type == 3)
                                {
                                    if (levelunlock_.config_index >= ConfigSystem.GetConfig<VIPImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<VIPImageLibrary>().Count - 1;
                                    VIPImageLibrary _leveldata = ConfigSystem.GetConfig<VIPImageLibrary>()[levelunlock_.config_index];
                                    TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName);
                                    file_name = _leveldata.Name;
                                }
                            }
                            else
                            {
                                TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null,
                                    "LevelAlbums/", FolderNames.AlbumName);
                            }
                            var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload;
                            ui.btn_download_coin.SetClick(() =>
                            {
                                if (GameHelper.Get101() >= downloadCoinNum)
                                {
                                    GameHelper.AddGold(-downloadCoinNum);
                                    ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";
                                    TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName);
                                    TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download);
                                    endClose();
                                }
                                else
                                {
                                    GameHelper.ShowTips("no_enough_gold", true);
                                    uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open);
                                }
                            });

                            ui.btn_download.SetClick(() =>
                            {
                                if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As<int>()))
                                {
                                    TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName);
                                    endClose();
                                }
                                else
                                    GameHelper.ShowVideoAd("DownloadImage", isSuccess =>
                                    {
                                        if (isSuccess)
                                        {
                                            TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName);
                                            endClose();
                                        }
                                    });
                            });
                        }
                        // TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null,
                        //     "LevelAlbums/");


                        GameHelper.SetLevel(GameHelper.GetLevel() + 1);
                        DOVirtual.DelayedCall(1.5f, () =>
                        {
                            if (GameHelper.IsGiftSwitch())
                            {
                                ui.step.selectedIndex = 2;
                            }
                            else
                            {
                                CtrlCloseUI();
                            }


                        });
                    }
                    else
                    {
                        CtrlCloseUI();
                    }
                }
            });

            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
        }

        private void RefreshAwardNum(decimal num = -1, int id = 102)
        {
            if (num < 0) num = DataMgr.Coin.Value;
            var btnCoin = ui.btn_gold as com_gold;


            var gTextField = btnCoin.text_gold;
            CommonHelper.ShowNumAnim(gTextField, num, id);
        }

        #region 生命周期

        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.NewEndModel) as NewEndModel;
        }
        private bool is_unlock_level = false;
        protected override void OnClose()
        {
            GameHelper.SetCloseResult(false);
            closeCallback?.Invoke();
            if (!is_unlock_level)
            {
                if (successData_.IsLevelSuccess && !GameHelper.is_first_login)
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, successData_.IsWin);
                else
                    GameDispatcher.Instance.Dispatch(GameMsg.CheckEnd);
            }


            foreach (var t in loader_list)
                if (t != null && !t.isDisposed && t.texture != null)
                {
                    t.texture.Dispose();
                    t.texture = null;
                }

            loader_list.Clear();

            MemoryManager.CleanMemoryMonitor();
        }

        protected override void OnBind()
        {
            ui = baseUI as com_newend;
        }

        private LevelUnlock LevelData;

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0) ui.btn_gold.y += 68;

            Debug.Log("//////////////////////0");
            Debug.Log(JsonConvert.SerializeObject(args));
            successData_ = (SuccessData)args;
            successData_.ch_number = (int)successData_.ch_number;

            // 修改后的代码
            var levelDataList = ConfigSystem.GetConfig<LevelUnlock>();
            var levelIndex = successData_.level - 1;

            // 确保索引不超出范围，如果超出则使用最后一个元素
            if (levelDataList is { Count: > 0 })
            {
                if (levelIndex >= 0 && levelIndex < levelDataList.Count)
                    LevelData = levelDataList[levelIndex];
                else
                    // 超出范围后，使用最后一个元素
                    LevelData = levelDataList[^1];
            }
            else
            {
                Debug.LogError("LevelUnlockModel DataList is null or empty");
            }
            var btnDownCoin = ((btn_unlock_1)ui.btn_download_coin);
            var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload;
            btnDownCoin.title = downloadCoinNum.ToString();
            ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";
            if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As<int>()))
            {
                ((btn_claim)ui.btn_download).have_vip.selectedIndex = 1;
                ui.is_vip.selectedIndex = 1;
            }
            else
            {
                ui.is_vip.selectedIndex = 0;
                btnDownCoin.down_load.selectedIndex = 1;
            }


            if (GameHelper.IsGiftSwitch() && successData_.IsLevelSuccess)
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Open);

                GameHelper.PlayGameTimeEvent(1, () => { GameHelper.RequestGameConfig(); });
            }
            else
            {
                GameHelper.SetCloseResult(true);
            }

            Debug.Log("//////////////////////3");
            InitView();
        }

        private int GetNextSpecialLevel()
        {
            var now_level = successData_.level;
            var list_ = ConfigSystem.GetConfig<LevelUnlock>();
            for (var i = now_level; i < list_.Count; i++)
                if (list_[i].LeveType != 0)
                    return i;
            return 0;
        }

        private SuccessData successData_;

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息
        public void OnUpdate101(object a = null)
        {
            com_gold btn_gold = ui.btn_gold as com_gold;
            btn_gold.text_gold.text = $"{DataMgr.Coin.Value:N0}";
        }
        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.UnlockLevelsuccess, UnlockLevelsuccess);
            GameDispatcher.Instance.AddListener(GameMsg.Update101, OnUpdate101);
        }

        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.UnlockLevelsuccess, UnlockLevelsuccess);
            GameDispatcher.Instance.RemoveListener(GameMsg.Update101, OnUpdate101);
        }

        #endregion
    }
}