
using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using FGUI.A000_common;
using UnityEngine;
using FairyGUI;
using FGUI.G003_play;
using FGUI.G018_GameHome;
using btn_noads = FGUI.A000_common.btn_noads;
using Random = UnityEngine.Random;
using Unity.VisualScripting;
using Newtonsoft.Json;
using System.IO;
using Spine.Unity;

namespace ScrewsMaster
{
    public class GameHomeUI : BaseUI
    {
        private GameHomeUICtrl ctrl;
        private GameHomeModel model;
        private GameHome ui;

        private MakeupTaskData _makeupTaskData;
        private Makeup _makeup;

        private bool is_first_login_go_to_h5;
        private btn_noads _btnNoAds;

        public GameHomeUI(GameHomeUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.GameHomeUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期
        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.GameHomeModel) as GameHomeModel;
        }

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

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

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

            HallManager.Instance.UpdateSecondEvent += UpData;

            AudioManager.Instance.PlayBGM(AudioConst.MainBg);
            InitView();
            UpData();

            var loginModel = GameHelper.GetLoginModel();
            is_first_login_go_to_h5 = CommonHelper.GetBoolByChance(ConfigSystem.GetConfig<CommonModel>().loginhallrate / 100f);
            is_first_login_go_to_h5 = false;
            GameHelper.is_first_login = loginModel.new_player;

            if (GameHelper.IsGiftSwitch() && !loginModel.new_player && is_first_login_go_to_h5)
            {
                GotoH5();
            }
            else if (GameHelper.IsGiftSwitch() && loginModel.new_player)
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.FirstRewardUI_Open);
                loginModel.new_player = false;
            }
            RefreshSaveingPot();
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }
        #endregion

        #region 消息
        protected override void AddListener()
        {
            PreferencesDispatcher<int>.Instance.AddListener(PreferencesMsg.playerAvatarId, OnChangeAvatar);
            GameDispatcher.Instance.AddListener(GameMsg.BattleLevelUp, OnBattleLevelUp);
            GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, SetTopCurr);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, SetMoneyCurr);
            GameDispatcher.Instance.AddListener(GameMsg.BuyPack, OnBuyPack);
            GameDispatcher.Instance.AddListener(GameMsg.BuyRemoveAdPack, OnBuyPack);

            HallManager.Instance.UpdateSecondEvent += TimeEvent;
            HallManager.Instance.UpdateEvent += UpdateEvent;
        }
        protected override void RemoveListener()
        {
            PreferencesDispatcher<int>.Instance.RemoveListener(PreferencesMsg.playerAvatarId, OnChangeAvatar);
            GameDispatcher.Instance.RemoveListener(GameMsg.BattleLevelUp, OnBattleLevelUp);
            GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshMakeupData, SetMoneyCurr);
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyPack, OnBuyPack);
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyRemoveAdPack, OnBuyPack);

            HallManager.Instance.UpdateSecondEvent -= TimeEvent;
            HallManager.Instance.UpdateEvent -= UpdateEvent;
        }


        private void OnBuyPack(object args)
        {
            SetBtnAds();
        }
        #endregion

        //初始化页面逻辑
        private void InitView()
        {
            // ShowScrews.Instance.gameMode = GameHome.Mode_simple;
            ui.switchgift.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0;

            var showH5Btn = false;
            if (GameHelper.IsGiftSwitch())
            {
                showH5Btn = true;
            }
            else
            {
                showH5Btn = GameHelper.GetCommonModel().WVswitch != 0;
                // if (showH5Btn)
                // {
                //     var uiBtnH5 = ui.btn_h5 as btn_hall;
                //     if (uiBtnH5 != null) uiBtnH5.t0.Stop();
                // }
            }
            ///   ui.btn_h5.visible = showH5Btn;


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

            _btnNoAds = ui.NoAdsBtn as btn_noads;
            InitButtons();

            SetAvatar();
            SetTopCurr();
            SetMoneyCurr();
            SetBtnTask();
            SetBtnAds();


            int level = GameHelper.GetLevel();
            ui.PlayBtn.text = "Level " + level;
            if (GameHelper.IsGiftSwitch())
            {
                ui.Mode.selectedIndex = 1;
                ui.PlayBtn.text = "Level " + level;
            }
            else
            {
                ui.Mode.selectedIndex = ShowScrews.Instance.gameMode;
            }
            checkThreeGift();
        }

        void SetTopCurr(object a = null)
        {
            ui.gold.number_text.text = GameHelper.GetGoldNumber().ToString();
        }

        private List<Paidcoins> _paidcoinsList;
        void UpData()
        {
            _paidcoinsList ??= ConfigSystem.GetConfig<PaidcoinsModel>().dataList;

            int time = SaveData.GetSaveobject()._goldtime0;
            if (time + _paidcoinsList[0].receive_CD < GameHelper.GetNowTime())
            {
                ui.gold.state.selectedIndex = 2;
                ui.gold.red.visible = true;
            }
            else
            {
                ui.gold.state.selectedIndex = 1;
            }


            ui.BattleBtn.red.visible = SaveData.getRed();
            ui.SignInBtn.red.visible = CheckSignState();
        }

        private bool CheckSignState()
        {
            var signDays = PreferencesMgr.Instance.SignState.Count;
            if (signDays == 0)
            {
                return true;
            }

            var isToday = false;
            if (signDays > 0)
                isToday = GameHelper.InToday(PreferencesMgr.Instance.SignState[signDays - 1], 0, true);

            return !isToday;
        }

        private int _timeCount = 11;
        private com_broadcast_text1 _textUI;
        void TimeEvent()
        {

            if (!GameHelper.IsGiftSwitch()) return;

            RefreshSaveingPot();
            checkThreeGift();
            // _timeCount++;
            // if (_timeCount > 10)
            // {
            //     ui.broadcast.visible = false;
            // }
            // var exBrPoolModel = ConfigSystem.GetConfig<exBrPoolModel>();
            // var configNameList = exBrPoolModel.config_name_list;
            // var configMoneyList = exBrPoolModel.config_money_list;
            // var nameIndex = Random.Range(0, configNameList.Count);
            // var moneyIndex = Random.Range(0, configMoneyList.Count);

            // if (_timeCount > 30)
            // {
            //     _timeCount = 0;
            //     ui.broadcast.visible = true;

            //     _textUI ??= ui.broadcast.GetChild("broad_cast_text") as com_broadcast_text1;
            //     if (_textUI != null)
            //     {
            //         _textUI.cast_text.text = String.Format(_textUI.show_text.text,
            //             configNameList[nameIndex],
            //             configMoneyList[moneyIndex],
            //             DateTimeManager.Instance.GetCurrDateTime());
            //         _textUI.t0.Play(() => { ui.broadcast.visible = false; });
            //     }
            // }

        }

        public void SetMoneyCurr(object a = null)
        {
            ui.money.visible = GameHelper.IsGiftSwitch();
            ui.money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102());

            if (GameHelper.IsGiftSwitch())
            {
                if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0)
                {
                    return;
                }

                _makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                _makeup = ConfigSystem.GetConfig<MakeupModel>().GetData(_makeupTaskData.tableId);
            }
        }

        private void OnChangeAvatar(ChangeValue<int> obj)
        {
            SetAvatar();
        }

        private void SetAvatar()
        {
            GameHelper.SetSelfAvatar((ui.btn_menu.GetChild("loader_avatar") as GComponent).GetChild("loader_avatar") as GLoader);
        }

        private void OnBattleLevelUp(object obj = null)
        {
            SetBtnTask();
        }

        void SetBtnTask()
        {
            ui.BattleBtn.number_text.text = "Lv." + GameHelper.GetBattleLv();
            if (GameHelper.GetBattleLv() >= ConfigSystem.GetConfig<PassportrewardsModel>().dataList.Count)
            {
                ui.BattleBtn.progress.width = 135;
            }
            else
            {
                ui.BattleBtn.progress.width =
                    Mathf.Min((float)GameHelper.GetGameExp() / ConfigSystem.GetConfig<PassportrewardsModel>().dataList[GameHelper.GetBattleLv()].Eliminating_quantity, 1) * 135;
            }

        }

        void SetBtnAds()
        {
            if (!SaveData.GetSaveobject().is_get_removead && !SaveData.GetSaveobject().is_get_packreward)
            {
                _btnNoAds.t0.Play(-1, 0, null);
            }
            else if (SaveData.GetSaveobject().is_get_removead && SaveData.GetSaveobject().is_get_packreward)
            {
                _btnNoAds.t0.Stop();
                _btnNoAds.visible = false;
            }
            else if (SaveData.GetSaveobject().is_get_packreward)
            {
                _btnNoAds.t0.Stop();
                _btnNoAds.t1.Play();
                _btnNoAds.img_pack.visible = false;
                _btnNoAds.img_ad.visible = true;

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

        }

        void GotoH5(object obj = null)
        {

            uiCtrlDispatcher.Dispatch(UICtrlMsg.H5UI_Open);
            GameHelper.showGameUI = false;
        }

        private void InitButtons()
        {
            ui.LeftBtn.SetClick(OnClickLeftBtn);
            ui.RightBtn.SetClick(OnClickRightBtn);
            ui.LuckySpinBtn.SetClick(OnLuckySpinBtn);
            ui.btn_menu.SetClick(OnClickMenuBtn);
            ui.btn_setting.SetClick(OnClickSetBtn);
            ui.SignInBtn.SetClick(OnClickSignInBtn);
            ui.BattleBtn.SetClick(OnClickBattleBtn);
            ui.PlayBtn.SetClick(OnClickPlayBtn);
            ui.RankBtn.SetClick(OnClickRankBtn);
            ui.btn_restore.SetClick(() =>
            {
                PurchasingManager.Instance.IosRestore((success, message) =>
                {
                    // Debug.Log("[barry] restore success message: " + message);
                    if (success)
                    {
                        // Debug.Log("[barry] restore success: " + success);
                        GameHelper.ShowTips("Restore Purchases Success!");
                        SaveData.GetSaveobject().is_get_removead = success;
                        SaveData.GetSaveobject().is_get_battlepass = success;
                        SaveData.GetSaveobject().have_slot = success;
                        GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack);
                        GameDispatcher.Instance.Dispatch(GameMsg.BuyPack);
                        GameHelper.SetPayBox1(true);
                        GameHelper.SetPayBox2(true);
                        SaveData.saveDataFunc();
                    }
                    else
                    {
                        // Debug.Log("[barry] restore failed: " + success);
                        GameHelper.ShowTips("There are no recoverable transactions");
                    }
                });
            });
            // ui.money.btn_cashout.SetClickDownEffect(0.8f, 1);
            ui.money.GetChild("btn_cashout").SetClick(() =>
            {
                if (!GameHelper.IsGiftSwitch()) return;
                uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData);
            });
            // ui.btn_h5.SetClick(() =>
            // {
            //     GotoH5();
            // });
            ui.gold.btn_buygold.SetClick(() =>
            {

                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open);
                GameHelper.showGameUI = false;
            });

            ui.NoAdsBtn.SetClick(() =>
            {
                if (!SaveData.GetSaveobject().is_get_packreward && !SaveData.GetSaveobject().is_get_removead)
                {
                    if (_btnNoAds.img_ad.visible)
                    {
                        PackRewardData param = new PackRewardData();
                        param.isAutoPop = false;
                        param.isNeedScroll = true;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param);
                    }
                    else
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open);
                    }

                }
                else if (SaveData.GetSaveobject().is_get_packreward)
                {
                    PackRewardData param = new PackRewardData();
                    param.isAutoPop = false;
                    param.isNeedScroll = true;
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param);
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open);
                }
                GameHelper.showGameUI = false;
            });
            ui.btn_three_day.SetClick(() =>
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            });
            ui.btn_failpack.SetClick(() =>
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.ResurgenceUI_Open);
            });
            if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 0 || !GameHelper.IsGiftSwitch())
            {
                ui.btn_saveingpot.visible = false;
            }
            ui.btn_saveingpot.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open); });

            var ske_pot = FXManager.Instance.SetFx<SkeletonAnimation>((ui.btn_saveingpot as btn_saveingpot).ani_parent, Fx_Type.fx_savepot_icon, ref closeCallback);
            ske_pot.state.SetAnimation(0, "animation", true);
            if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch())
            {
                Debug.Log(PlayerPrefs.GetInt("pot_day", 0));
                Debug.Log(DateTime.Now.Day);
                if (PlayerPrefs.GetInt("pot_day", 0) == 0)
                {
                    uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open);
                    PlayerPrefs.SetInt("pot_day", DateTime.Now.Day);
                }
                else
                {
                    if (DateTime.Now.Day != PlayerPrefs.GetInt("pot_day", 0))
                    {
                        uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open);
                        PlayerPrefs.SetInt("pot_day", DateTime.Now.Day);
                    }
                }
                Debug.Log(PlayerPrefs.GetInt("pot_day", 0));
            }
        }
        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 UpdateEvent()
        {
            long t = SaveData.GetSaveobject().failed_pack_time;

            if (SaveData.GetSaveobject().failed_pack_time > GameHelper.GetNowTime())
            {
                ui.btn_failpack.visible = true;
                long time_ = t * 1000 - GameHelper.getNowTimeByMillisecond();
                DateTime oldDate = new DateTime(1970, 1, 1);
                oldDate = oldDate.AddMilliseconds(time_);
                ui.btn_failpack.GetChild("lab_time").text = DateTimeManager.Instance.DateTimeToFFFString(oldDate);
            }
            else
            {
                ui.btn_failpack.visible = false;
            }


        }
        private void RefreshSaveingPot(object isShow = null)
        {
            (ui.btn_saveingpot as btn_saveingpot).text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash);
        }

        private Action closeCallback;
        private void OnClickLeftBtn()
        {
            ShowScrews.Instance.gameMode = GameHome.Mode_simple;
            ui.Mode.selectedIndex = ShowScrews.Instance.gameMode;

            // int level = GameHelper.GetLevel();
            // ui.PlayBtn.text = "Level " + level;
        }

        private void OnClickRightBtn()
        {
            ShowScrews.Instance.gameMode = GameHome.Mode_difficult;
            ui.Mode.selectedIndex = ShowScrews.Instance.gameMode;
        }

        private void OnLuckySpinBtn()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrizeWheelUI_Open);
        }

        private void OnClickMenuBtn()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open);
        }

        private void OnClickSetBtn()
        {
            int mode = 0;
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open, mode);
        }

        private void OnClickSignInBtn()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SignInUI_Open);
        }

        private void OnClickBattleBtn()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Open);
        }

        private void OnClickPlayBtn()
        {
            CtrlCloseUI();
            // var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? ShowScrews.Instance.GetCurMaxLevel() :  GameHelper.GetLevel();;
            var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ;
            ShowScrews.Instance.InitLogic(level);

            AudioManager.Instance.PlayBGM(AudioConst.PlayingBg);

        }

        private void OnClickRankBtn()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RankUI_Open);
        }

        //     private void OpenFailPack()
        //     {
        //         var grade = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel();




        //         Debug.Log(grade);

        //         var index = grade - 1;

        //         var levelDataModel = ConfigSystem.GetConfig<LevelDataModel>();
        //         var _levelDataList = levelDataModel.dataList;
        //         index = index < _levelDataList.Count ? index : _levelDataList.Count - 1;
        //         var levelData = _levelDataList[index];
        //         var screwCount = levelData.screwCount;
        //         var _screwCountForLevel = screwCount;
        //         var _pendingScrewCount = _screwCountForLevel;




        //         var _screwBoxCount = _pendingScrewCount / 3;
        //         var _curScrewBoxCount = _screwBoxCount;

        //         _screwBoxCount = _pendingScrewCount / 3;

        //         var progress = (float)(_screwBoxCount - _curScrewBoxCount) / _screwBoxCount;
        //                 Debug.Log(_screwBoxCount);
        //                    Debug.Log(_curScrewBoxCount);
        //                     Debug.Log(progress);
        //         progress = Mathf.Clamp(progress, 0, 1);
        //         var endNum = Mathf.RoundToInt(progress * 100);
        //         Debug.Log(endNum);
        //         //gameProgressText.text = $"{endNum}%";
        //     }


    }
}