using System;
using DG.Tweening;
using UnityEngine;
using Spine.Unity;
using FairyGUI;
using FGUI.ZM_Common_01;
using System.Collections.Generic;
using Random = UnityEngine.Random;
using Newtonsoft.Json;
using FGUI.LG_Common;
using SGModule.Common.Extensions;
using SGModule.Common.Helper;
using FGUI.ZM_Lobby_03;
using System.Net;
// using SGModule.ApplePay;
using SGModule.Net;
using System.IO;
using System.Linq;


namespace RedHotRoast
{
    public class HallUI : BaseUI
    {
        private HallUICtrl ctrl;
        private HallModel model;
        public FGUI.ZM_Lobby_03.com_hall ui;

        public static bool isClosed = false;

        private long userUid;
        public int active_cd = 10;
        private Tweener tweener;

        private SkeletonAnimation anim_ad;
        private SkeletonAnimation anim_banma = null;

        private FGUI.ZM_Common_01.btn_noads btn_noads;
        public HallUI(HallUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.HallUI;
            this.ctrl = ctrl;
        }
        private string jsonstr;

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "ZM_Lobby_03";
            uiInfo.assetName = "com_hall";
            uiInfo.layerType = UILayerType.Normal;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = false;
        }

        #region 生命周期

        protected override void OnInit()
        {
            model = moduleManager.GetModel(ModelConst.HallModel) as HallModel;
            InitData();
        }

        protected override void OnClose()
        {

            HallManager.Instance.UpdateSecondEvent -= UpBtnCoin;
            isClosed = true;
            //关闭时保存cd数据
            PlayerPrefs.SetInt($"active_cd_num_{userUid}", active_cd);
            // HallManager.Instance.countTimes = (int)Time.time;

            CommonHelper.FadeOut(ui);
            tweener?.Kill();
            closeCallback?.Invoke();

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

        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_Lobby_03.com_hall;
        }

        protected override void OnOpenBefore(object args)
        {
            bool enterGame = false;
            if (args != null)
            {
                enterGame = (bool)args;
            }

            if (Screen.safeArea.y != 0)
            {
                ui.btn_gold.y += Screen.safeArea.y - 15;
            }
            // ui.com_panel.scrollPane.ScrollRight(12,false);
            // if(GameHelper.IsGiftSwitch())
            // {
            //     ui.com_panel.scrollPane.touchEffect = false;
            // }


            CreateGoldtimeList();

            // var isNew = DataMgr.NoviceGuide.Value;

            // if (!GameHelper.IsGiftSwitch() && !isNew)
            // {
            //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GuideViewUI_Open);
            // }
            GameHelper.IsShowFirstReward();

            isClosed = false;

            btn_noads = (btn_noads)ui.btn_noads;
            var loginModel = GameHelper.GetLoginModel();
            userUid = loginModel.Uid;

            InitView();
            UpBtnCoin();
            setBtntask();

            HallManager.Instance.UpdateSecondEvent += UpBtnCoin;
            ui.btn_album.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AlubumUI_Open);
            });
            if ((GameHelper.GetCommonModel().Live == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().LivePreview))
            {
                ui.btn_live.visible = true;
            }
            if ((GameHelper.GetCommonModel().Secret == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().SecretPreview))
            {
                ui.btn_secret.visible = true;
            }


            int random_ = Random.Range(0, 100);
            //   GameHelper.GetCommonModel().roomGuideRate = 100;//zhushi
            if (!enterGame && GameHelper.IsGiftSwitch() && random_ < GameHelper.GetCommonModel().HomeGuideRate)
            {
                List<int> unlocklist = new List<int>();
                if ((GameHelper.GetCommonModel().Live == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().LivePreview) && (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockLive[1]))
                {
                    if (DataMgr.IsUnlockLive.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockLive.As<int>()))//未解锁。
                    {
                        unlocklist.Add(0);
                    }
                }
                if ((GameHelper.GetCommonModel().Secret == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().SecretPreview) && (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockSecret[1]))
                {
                    if (DataMgr.IsUnlockSecret.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockSecret.As<int>()))//未解锁。
                    {
                        unlocklist.Add(1);
                    }
                }
                if ((GameHelper.GetCommonModel().Assitant == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().AssitantPreview))
                {
                    if (DataMgr.IsUnlockChat.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockAssitant.As<int>()))//未解锁。
                    {
                        unlocklist.Add(2);
                    }
                }
                if (unlocklist.Count > 0)
                {
                    if (GameHelper.IsGiftSwitch())
                    {
                        int random_index = Random.Range(0, unlocklist.Count);
                        if (unlocklist[random_index] == 0)
                        {
                            uiCtrlDispatcher.Dispatch(UICtrlMsg.LiveUnlockUI_Open);
                        }
                        else if (unlocklist[random_index] == 1)
                        {
                            uiCtrlDispatcher.Dispatch(UICtrlMsg.ScAlbumLockUI_Open);
                        }
                        else if (unlocklist[random_index] == 2)
                        {
                            uiCtrlDispatcher.Dispatch(UICtrlMsg.ChatUnlockUI_Open);
                        }
                    }
                }

            }
            // ui.bg_loader;
            Setbg();
            if (GameHelper.IsGiftSwitch() && GameHelper.GetCommonModel().Assitant == 1 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().AssitantPreview)
            {
                ui.btn_chat.visible = true;
                SkeletonAnimation ske_pot = FXManager.Instance.SetFx<SkeletonAnimation>(ui.btn_chat.GetChild("ani_parent") as GGraph, Fx_Type.fx_btnchat, ref closeCallback);
                ske_pot.state.SetAnimation(0, "animation", true);
                ui.btn_chat.SetClick(() =>
                {

                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ChatChooseUI_Open);
                    Log.Info("Hall", $"{GameHelper.GetLevel()}/{GameHelper.GetCommonModel().UnlockSecret[1]}/{DataMgr.IsUnlockSecret.Value}");
                });
            }

        }
        void Setbg(object a = null)
        {
            if (!GameHelper.IsGiftSwitch())
            {
                return;
            }

            if (GameHelper.GetLevel() - 1 < GameHelper.GetCommonModel().MultiModal)
            {
                int level_ = GameHelper.GetLevel() - 2;
                if (level_ <= 0) level_ = 0;
                if (level_ >= ConfigSystem.GetConfig<LevelUnlock>().Count) level_ = ConfigSystem.GetConfig<LevelUnlock>().Count - 1;
                TextureHelper.SetImgLoader(ui.bg_loader, ConfigSystem.GetConfig<LevelUnlock>()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName);
            }
            else
            {
                Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel() - 1);
                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.bg_loader, _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.bg_loader, _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.bg_loader, _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.bg_loader, _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.bg_loader, ConfigSystem.GetConfig<LevelUnlock>()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName);
                }
            }

            if (!loader_list.Contains(ui.bg_loader))
            {
                loader_list.Add(ui.bg_loader);
            }
        }

        private List<GLoader> loader_list = new List<GLoader>();
        float showResurgence()
        {
            // string jsonFilePath = Path.Combine(Application.persistentDataPath, "RainData1.json");
            // string jsonstr = "";
            // if (File.Exists(jsonFilePath))
            // {
            //     jsonstr = File.ReadAllText(jsonFilePath);
            //     //return JsonUtility.FromJson<MyData>(json);
            // }
            // List<List<Card_item>> card_item_list = JsonConvert.DeserializeObject<List<List<Card_item>>>(jsonstr);

            // int surplus_item = 0;
            // for (int i = 0; i < card_item_list.Count; i++)
            // {
            //     for (int j = 0; j < card_item_list[i].Count; j++)
            //     {
            //         //  if (card_item_list[i][j].sheep_card.IsDestroyed() || card_item_list[i][j].sheep_card == null) continue;
            //         surplus_item++;
            //     }
            // }

            var card_item_list = JsonConvert.DeserializeObject<List<List<Card_item>>>(jsonstr);
            var surplus_item = 0;
            for (var i = 0; i < card_item_list.Count; i++)
            {
                for (var j = 0; j < card_item_list[i].Count; j++)
                {
                    surplus_item++;
                }
            }
            return 1 - (float)surplus_item / (SaveData.GetSaveObject().all_card_numbers * 3);

        }

        private void getJsonData()
        {
            var json = DataMgr.LevelData.Value;
            if (!string.IsNullOrEmpty(json))
            {
                jsonstr = json;
            }
        }
        protected override void OnOpen(object args)
        {
            // CommonHelper.FadeIn(ui);
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        public override void OnSwitchLanguage()
        {
            base.OnSwitchLanguage();
            // InitView();
            ui.btn_secret.title = "LV." + GameHelper.GetCommonModel().UnlockSecret[1];
            ui.btn_play.text_lv.text = Language.GetContentParams("level", GameHelper.GetLevel());
            ui.btn_play_1.text_lv.text = Language.GetContentParams("level", GameHelper.GetLevel());
            SetName(ui.text_name);
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            HallManager.Instance.AddChangeGiftSwitch(InitView);

            PreferencesDispatcher<int>.Instance.AddListener(DataMsg.playerAvatarId, UpdataAvatar);
            PreferencesDispatcher<string>.Instance.AddListener(DataMsg.playerName, OnChangeName);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, Chang101);
            GameDispatcher.Instance.AddListener(GameMsg.UpdateNoads, SetBtnAds);
            UICtrlDispatcher.Instance.AddListener(UICtrlMsg.AlubumUI_Close, Setbg);
            GameDispatcher.Instance.AddListener(GameMsg.Update101, Chang101);
        }

        protected override void RemoveListener()
        {
            HallManager.Instance.RemoveChangeGiftSwitch(InitView);
            PreferencesDispatcher<int>.Instance.RemoveListener(DataMsg.playerAvatarId, UpdataAvatar);
            PreferencesDispatcher<string>.Instance.RemoveListener(DataMsg.playerName, OnChangeName);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, Chang101);
            GameDispatcher.Instance.RemoveListener(GameMsg.UpdateNoads, SetBtnAds);
            UICtrlDispatcher.Instance.RemoveListener(UICtrlMsg.AlubumUI_Close, Setbg);
            GameDispatcher.Instance.RemoveListener(GameMsg.Update101, Chang101);
        }
        #endregion
        private List<Paidcoins> Paidcoins_list = ConfigSystem.GetConfig<Paidcoins>();

        private int time_count = 11;

        void CreateGoldtimeList()
        {
            // 获取保存对象
            var saveObject = SaveData.GetSaveObject();

            // 检查_goldtime是否为null或者长度与Paidcoins_list.Count不相等
            if (saveObject._goldtime == null || saveObject._goldtime.Length != Paidcoins_list.Count)
            {
                // 重置_goldtime，并创建一个新的数组，长度为Paidcoins_list.Count
                saveObject._goldtime = new int[Paidcoins_list.Count];
            }
        }

        void setBtntask()
        {
            ui.btn_pass.number_text.text = "Lv." + GameHelper.GetBattleLv();
            if (GameHelper.GetBattleLv() >= ConfigSystem.GetConfig<Passportrewards>().Count)
            {
                ui.btn_pass.pass_pro.value = 100;
            }
            else
            {
                ui.btn_pass.pass_pro.value =
                 ((float)GameHelper.GetGameExp() / ConfigSystem.GetConfig<Passportrewards>()[GameHelper.GetBattleLv()].Eliminating_quantity) * 100;
            }
        }
        private void UpBtnCoin()
        {

            com_gold btn_gold = ui.btn_gold as com_gold;
            btn_gold.state.selectedIndex = 1;
            for (int i = 0; i < Paidcoins_list.Count; i++)
            {
                if (!Paidcoins_list[i].is_paid)
                {
                    int time = SaveData.GetSaveObject()._goldtime[i];
                    if (time + Paidcoins_list[i].receive_CD < GameHelper.GetNowTime())
                    {
                        btn_gold.state.selectedIndex = 2;
                    }
                }
            }
            // checkThreeGift();
            var head = ui.btn_head as btn_head;
            if (head != null)
            {
                var vipLevel = GameHelper.GetVipLevel();
                if (vipLevel > 0)
                {
                    head.vip_loader.visible = true;
                    head.vip_loader.url = $"ui://LG_Common/vip_{vipLevel}";
                }
                else
                {
                    head.vip_loader.visible = false;
                }
            }

            int eggTime = SaveData.GetSaveObject().crush_egg_time;
            if (eggTime > GameHelper.GetNowTime())
            {
                ui.btn_egg.GetChild("times").visible = true;
                ui.btn_egg.GetChild("times").text = CommonHelper.TimeFormat(eggTime - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Minute);
            }
            else
            {
                ui.btn_egg.GetChild("times").visible = false;
            }
        }


        private void InitData()
        {
            model.showCoin = DataMgr.Coin.Value;
            model.showDollar = DataMgr.Ticket.Value;
        }

        private Action closeCallback;

        private void InitView()
        {

            Set101();

            SetName(ui.text_name);

            RefreshRed();

            SetBtnAds();


            var btnSecret = ui.btn_secret as btn_secret;
            var btnSecretAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnSecret.anim, Fx_Type.fx_btn_secret, ref closeCallback);
            btnSecretAnim.state.SetAnimation(0, "animation", true);

            var btnVip = ui.btn_vip as btn_vip;
            var btnVipAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnVip.anim, Fx_Type.fx_btn_vip, ref closeCallback);
            btnVipAnim.state.SetAnimation(0, "animation", true);

            var btnAlbum = ui.btn_album as btn_albums;
            var btnAlbumAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnAlbum.anim, Fx_Type.fx_btn_album, ref closeCallback);
            btnAlbumAnim.state.SetAnimation(0, "animation", true);

            var btnLive = ui.btn_live as btn_live;
            var btnLiveAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnLive.anim, Fx_Type.fx_btn_live, ref closeCallback);
            btnLiveAnim.state.SetAnimation(0, "animation", true);

            ui.btn_play.text_lv.text = Language.GetContentParams("level", GameHelper.GetLevel());
            ui.btn_play.SetClick(OnClickPlay);
            ui.btn_play_1.text_lv.text = Language.GetContentParams("level", GameHelper.GetLevel());
            ui.btn_play_1.SetClick(OnClickPlay);

            ui.btn_wheel.SetClick(OnClickLuckySpin);
            ui.btn_sign.SetClick(OnClickSign);
            ui.btn_setting.SetClick(OnClickSetting);
            ui.btn_shop.SetClick(OnClickShop);
            //   ui.btn_secret.SetClick(OnClickSecretAlbums);
            ui.btn_vip.SetClick(onClickVip);

            ui.btn_egg.SetClick(OnClickEgg);
            btn_noads.SetClick(() =>
            {
                if (!SaveData.GetSaveObject().is_get_packreward && !SaveData.GetSaveObject().is_get_removead)
                {
                    if (btn_noads.img_ad.visible)
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open, true);
                    }
                    else
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open);
                    }

                }
                else if (SaveData.GetSaveObject().is_get_packreward)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open, true);
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open);
                }
            });

            ui.btn_live.SetClick(() =>
            {

                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LiveUI_Open);

            });
            ui.btn_secret.title = "LV." + GameHelper.GetCommonModel().UnlockSecret[1];
            ui.btn_secret.SetClick(() =>
            {
                if (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockSecret[1])
                {
                    Log.Info("Hall", $"{GameHelper.GetLevel()}/{GameHelper.GetCommonModel().UnlockSecret[1]}/{DataMgr.IsUnlockSecret.Value}");

                    if (DataMgr.IsUnlockSecret.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockSecret.As<int>()))//未解锁。
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretUnlockUI_Open);
                    }
                    else
                    {
                        if (DataMgr.IsUnlockSecret.Value == 0)
                        {
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockTipsUI_Open, 1);
                        }
                        else
                        {
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretAlbumsUI_Open);
                        }
                    }
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretAlbumsUI_Open);
                }

            });

            // ui.btn_task_times.SetClick(() => { OnClickTask(false); });

            ui.btn_task.SetClick(() => { OnClickTask(false); });
            ui.btn_record.SetClick(OpenRecord);

            //ui.broadcast.visible = GameHelper.IsGiftSwitch();

            ui.btn_pass.SetClick(OnClickPass);
            // if (GameHelper.IsGiftSwitch() || (ConfigSystem.GetConfig<CommonModel>().WVswitch == 1))
            // {
            //     ui.btn_h5.visible = false;
            // }

            var btnCoin = ui.btn_gold as com_gold;
            btnCoin.text_gold.text = $"{DataMgr.Coin.Value:N0}";
            btnCoin.SetClick(OnClickShop);

            ui.btn_head.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PersonViewUI_Open); });


            if (HallManager.Instance.enterHallTimes == 1)
            {
                reCreatPur();
            }


            if (!GameHelper.IsGiftSwitch())
            {

            }


            ui.state.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0;
            ui.btn_three_day.SetClick(() =>
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            });
            for (int i = 0; i < BtnNum; i++)
            {
                var btnItemPlay = ui.GetChild($"btn_play{i + 1}") as btn_item_play;

                list_play.Add(btnItemPlay);
            }
            UpdataAvatar();
            InitBtn();
            ui.btn_task.SetClick(() => { OnClickTask(false); });
            ui.btn_restore.SetClick(() =>
            {
                // ApplePayManager.Instance.AppleRestore((success, message) =>
                // {
                //     Debug.Log($"[barry] restore success message: {message}---- {JsonConvert.SerializeObject(message)}");
                //     if (success)
                //     {
                //         Debug.Log("[barry] restore success: " + success);
                //         GameHelper.ShowTips("Restore_pur", true);
                //         SaveData.GetSaveObject().have_slot = success;
                //         DataMgr.VipLevel.Value = 3;
                //         DataMgr.VipExpirationTime.Value = ServerClock.GetCurrentServerTime() + 7 * 24 * 60 * 60;
                //     }
                //     else
                //     {
                //         GameHelper.ShowTips("recoverable_tips", true);
                //     }
                // });
            });

            Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<ApplePay>()));
        }
        private void checkThreeGift(object obj = null)
        {
            // if (SaveData.GetSaveObject().is_get_ThreeDaysGift) {
            var isToday = GameHelper.InToday(SaveData.GetSaveObject().last_got_three_gift_time, 0, true);
            int three_gift_got_index = SaveData.GetSaveObject().three_gift_got_index;
            if (three_gift_got_index > (int)rewardState.day3)
            {
                ui.btn_three_day.visible = false;
            }
            else if (!isToday)
            {
                ui.btn_three_day.GetChild("red").visible = true;
            }
            else
            {
                ui.btn_three_day.GetChild("red").visible = false;
            }
            // }
        }
        void reCreatPur(object a = null)
        {
        }

        void SetBtnAds(object a = null)
        {
            if (!SaveData.GetSaveObject().is_get_removead && !SaveData.GetSaveObject().is_get_packreward)
            {
                btn_noads.t0.Play(-1, 0, null);
            }
            else if (SaveData.GetSaveObject().is_get_removead && SaveData.GetSaveObject().is_get_packreward)
            {
                btn_noads.t0.Stop();
                // btn_noads.visible = false;
                btn_noads.img_pack.visible = false;
                btn_noads.img_ad.visible = true;
            }

            else if (SaveData.GetSaveObject().is_get_packreward)
            {
                btn_noads.t0.Stop();
                btn_noads.t1.Play();
                btn_noads.img_pack.visible = false;
                btn_noads.img_ad.visible = true;

            }
            else if (SaveData.GetSaveObject().is_get_removead)
            {
                btn_noads.t0.Stop();
                btn_noads.t1.Play();
                btn_noads.img_pack.visible = true;
                btn_noads.img_ad.visible = false;
            }

        }

        private void RefreshRed(object isShow = null)
        {
            ui.btn_pass.red.visible = SaveData.battlepassred();
            ui.btn_task.GetChild("red").visible = SaveData.timetaskred() || SaveData.passtaskred() || SaveData.AdTaskred();
            ui.btn_sign.red.visible = SignRed();
            ui.btn_chat.GetChild("red").visible = ChatHelper.GetChatRed();
        }

        private bool SignRed()
        {
            // sk.SetActive(false);
            for (int i = 0; i < 7; i++)
            {
                var signDays = DataMgr.SignState.Value.Count;
                var isToday = true;
                if (signDays > 0)
                    isToday = GameHelper.InToday(DataMgr.SignState.Value[signDays - 1], 0, true);

                else if (i == signDays)
                {
                    if (signDays > 0 && isToday)
                    {
                        continue;
                    }

                    return true;
                }
            }
            return false;
        }
        private void OnClickLuckySpin()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.WheelUI_Open);
        }

        private void OnClickTask(bool isLevel)
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Open, isLevel);
        }
        private void OpenRecord()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RecordViewUI_Open);
        }
        private void OnClickSign()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SignInUI_Open);
        }
        private void OnClickShop()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open, true);
        }
        private void OnClickSetting()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open, 0);
        }
        private void OnClickPass()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassViewUI_Open);
        }
        public int BtnNum = 10;
        private List<btn_item_play> list_play = new List<btn_item_play>();
        private void InitBtn(int avaterid = -1)
        {
            Debug.Log("?????????kkkkkkkkk");
            Debug.Log(DataMgr.PlayerAvatarId.Value);
            int level_ = GameHelper.GetLevel();
            int stage_ = (level_ - 1) / BtnNum;
            for (int i = 0; i < BtnNum; i++)
            {
                int lv = stage_ * BtnNum + 1 + i;

                list_play[i].level.text = lv.ToString();
                list_play[i].level1.text = lv.ToString();


                list_play[i].title = lv.ToString();
                if (lv < level_)
                {

                    list_play[i].state.selectedIndex = 0;

                }
                else if ((stage_ * BtnNum + 1 + i) == level_)
                {
                    list_play[i].state.selectedIndex = 1;
                    list_play[i].SetClick(OnClickPlay);

                    var anim = FXManager.Instance.SetFx<SkeletonAnimation>(list_play[i].anim, Fx_Type.fx_play_button, ref closeCallback);
                    anim.state.SetAnimation(0, "animation", true);
                }
                else
                {
                    list_play[i].state.selectedIndex = 2;
                }
            }
        }
        
        private void OnClickEgg()
        {
            if (ui.btn_egg.GetChild("times").visible)
            {
                GameHelper.ShowTips("Waiting_cd", true);
                return;
            }
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.EggUI_Open);
        }
        private void onClickVip()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.VipClubViewUI_Open);
        }

        private void OnClickPlay()
        {
            if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal || !GameHelper.IsGiftSwitch())
            {
                GameHelper.gameType = 0;
                GameDispatcher.Instance.Dispatch(GameMsg.OpenGame);
            }
            else
            {
                if (!DataMgr.LevelUnlockListNew.Value.Any(x => x.level_ == GameHelper.GetLevel()))
                {
                    uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelNewUI_Open, true);
                }
                else
                {
                    GameHelper.gameType = 0;
                    GameDispatcher.Instance.Dispatch(GameMsg.OpenGame);
                }
            }

        }


        public void OnUpdate101(object obj = null)
        {
            if (obj != null)
            {
                var changeValue = (decimal)obj;
                model.showCoin += changeValue;
                Set101(model.showCoin);
            }
        }

        public void OnUpdate102(object obj = null)
        {
            if (obj != null)
            {
                var changeValue = (decimal)obj;
                model.showDollar += changeValue;
            }
        }
        private void UpdataAvatar(object obj = null)
        {
            var headId = DataMgr.PlayerAvatarId.Value;
            if (obj != null)
            {
                headId = obj.As<ChangeValue<int>>().newValue;
            }
            var head = ui.btn_head as btn_head;
            if (head != null)
            {
                var vipLevel = GameHelper.GetVipLevel();
                if (vipLevel > 0)
                {
                    head.vip_loader.visible = true;
                    head.vip_loader.url = $"ui://LG_Common/vip_{vipLevel}";
                }
                else
                {
                    head.vip_loader.visible = false;
                }
                GameHelper.SetSelfAvatar(head.head.load_avatar, headId);
            }

            InitBtn(headId);
        }

        public void Set101(decimal coin = -1)
        {
            if (coin < 0)
            {
                coin = DataMgr.Coin.Value;
            }

            var btnCoin = ui.btn_gold as com_gold;
            btnCoin.text_gold.text = $"{coin:N0}";
        }
        public void Chang101(object a = null)
        {

            int coin = DataMgr.Coin.Value;


            var btnCoin = ui.btn_gold as com_gold;
            btnCoin.text_gold.text = $"{coin:N0}";
        }
        private void OnChangeName(ChangeValue<string> obj)
        {
            var name = obj.newValue;
            GameHelper.SetName(ui.text_name, name);
        }

        private void SetName(GTextField gTextField)
        {
            var name = DataMgr.PlayerName.Value;

            GameHelper.SetName(gTextField, name);
        }
    }
}
