using System;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using FGUI.G003_play;
using Random = UnityEngine.Random;
using DG.Tweening;
using System.Linq;
using FGUI.A000_common;
using Spine.Unity;
using btn_noads = FGUI.A000_common.btn_noads;

namespace ScrewsMaster
{
    public class SheepPlayUI : BaseUI
    {
        private SheepPlayUICtrl _ctrl;
        private SheepPlayModel _model;
        private sheep_play ui;

        private MakeupTaskData _makeupTaskData;
        private Makeup _makeup;

        private btn_noads _btnNoAds;

        private Action closeCallback;

        private int _adCoolDown = 20;
        private int _adNumbers = 0;
        private int _adTimes = 0;

        public SheepPlayUI(SheepPlayUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.SheepPlayUI;
            _ctrl = ctrl;
        }

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

        private bool is_first_login_go_to_h5;
        #region 生命周期
        protected override void OnInit()
        {

        }

        protected override void OnClose()
        {
          //  HallManager.Instance.UpdateSecondEvent -= GameHelper.addGameTime;
            HallManager.Instance.UpdateSecondEvent -= TimeEvent;
            HallManager.Instance.UpdateSecondEvent -= UpData;
            HallManager.Instance.UpdateEvent -= UpdateEvent;
            closeCallback?.Invoke();
        }

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

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

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


            ui.money.visible = ui.gold.red.visible  = ui.btn_look_ad.visible = GameHelper.IsGiftSwitch();

            ui.btn_menu.touchable = false;
            SetAvatar();

            //  HallManager.Instance.UpdateSecondEvent += GameHelper.addGameTime;
            HallManager.Instance.UpdateSecondEvent += TimeEvent;
            HallManager.Instance.UpdateSecondEvent += UpData;
            HallManager.Instance.UpdateEvent += UpdateEvent;


            InitView();

            if (GameHelper.getGameday() != DateTime.Now.Day)
            {
                PlayerPrefs.SetInt("_time", 0);
                SaveData.GetSaveobject().time_task_record = new List<int>();
                GameHelper.setGameday();
            }
        }


        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, SetMakeup);
            GameDispatcher.Instance.AddListener(GameMsg.Ad_success, ad_success);
            GameDispatcher.Instance.AddListener(GameMsg.GotoH5, GotoH5);
            GameDispatcher.Instance.AddListener(GameMsg.FlyGold, OnChangeGold);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshLookAd, OnChangeLookAd);
            GameDispatcher.Instance.AddListener(GameMsg.BuyPack, OnBuyPack);
            GameDispatcher.Instance.AddListener(GameMsg.BuyRemoveAdPack, OnBuyPack);
            GameDispatcher.Instance.AddListener(GameMsg.ThreeDaysGiftUIClose, checkThreeGift);
            // MainThreadDispatcher.Instance.AddListener(MainThreadMsg.App_Focus_True, backGame);

        }
        protected override void RemoveListener()
        {
            PreferencesDispatcher<int>.Instance.RemoveListener(PreferencesMsg.playerAvatarId, OnChangeAvatar);
            GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshMakeupData, SetMakeup);
            GameDispatcher.Instance.RemoveListener(GameMsg.GotoH5, GotoH5);
            GameDispatcher.Instance.RemoveListener(GameMsg.FlyGold, OnChangeGold);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshLookAd, OnChangeGold);
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyPack, OnBuyPack);
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyRemoveAdPack, OnBuyPack);
            GameDispatcher.Instance.RemoveListener(GameMsg.ThreeDaysGiftUIClose, checkThreeGift);
        }

        private void OnBuyPack(object args)
        {
            SetBtnAds();
        }
        #endregion
        //初始化页面逻辑
        private void InitView()
        {
            var reqData = new RespLoginFunnelData
            {
                type = "enterHall",
                payload = ""
            };
            NetworkKit.PostFunnelLogin(reqData);

            ui.fairyBatching = true;
            int level = GameHelper.GetLevel();
            ui.level_text.text = "Level " + level;

            _adCoolDown = ConfigSystem.GetConfig<CommonModel>().lobbyrewrdtime * 60;
            _adTimes = PlayerPrefs.GetInt("ad_time", 0);
            _adNumbers = PlayerPrefs.GetInt("ad_number", 1);
            _btnNoAds = ui.btn_noads as btn_noads;

            ui.broadcast.visible = false;
            SetTopCurr();
            SetMakeup();
            SetBtnTask();

            if (SaveData.GetSaveobject().is_autopack_show_day != DateTime.Now.Day)
            {
                SaveData.GetSaveobject().is_autopack_show = false;
            }


            if (SaveData.GetSaveobject().start_time == 0) SaveData.GetSaveobject().start_time = GameHelper.GetNowTime();
            SetBtnAds();

            if ((SaveData.GetSaveobject().battle_pass_time + ConfigSystem.GetConfig<PassportrewardsModel>().dataList[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime())
            {
                SaveData.GetSaveobject().battle_pass_time = (int)GameHelper.GetNowTime();
                GameHelper.ResetGameExp();
                SaveData.GetSaveobject().battle_pass_freelist.Clear();
                SaveData.GetSaveobject().battle_pass_paylist.Clear();
                SaveData.GetSaveobject().is_get_battlepass = false;
            }

            InitLookAdBtn();
            InitButtons();
            ui.btn_failpack.SetClick(() =>
            {
                // float complte_progress = showResurgence();
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, 0.5f);
            });
            checkThreeGift();
            ui.btn_three_day.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            });
        }
        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 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;
                }
            }
        }
        private void InitButtons()
        {
            ui.btn_menu.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open);
                GameHelper.showGameUI = false;
            });
            ui.btn_setting.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open);
                GameHelper.showGameUI = false;
            });

            ui.money.btn_cashout.SetClickDownEffect(0.8f, 1);
            ui.money.btn_cashout.SetClick(OnClickMoneyBtn);

            ui.btn_task.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Open); GameHelper.showGameUI = false;
            });

            ui.gold.btn_buygold.SetClick(() =>
            {

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

            ui.Btn_SignIn.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SignInUI_Open);
                GameHelper.showGameUI = false;
            });

            // ui.btn_h5.SetClick(() =>
            // {
            //     GotoH5();
            // });

            ui.btn_noads.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;
            });
            if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 0 || !GameHelper.IsGiftSwitch())
            {
                ui.btn_saveingpot.visible = false;
            }
            ui.btn_saveingpot.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open); });
            (ui.btn_saveingpot as btn_saveingpot).text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash);
            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);
        }
        private void SetSaveingPotBtn(object a = null)
        {
            (ui.btn_saveingpot as btn_saveingpot).text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash);

        }
        private void OnClickMoneyBtn()
        {
            if (_makeupTaskData == null || _makeup == null)
            {
                return;
            }
            GameHelper.showGameUI = false;
            uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData);
        }

        private void InitLookAdBtn()
        {
            var sk = FXManager.Instance.SetFx<SkeletonAnimation>(ui.btn_look_ad.gp, Fx_Type.fx_main_ad, ref closeCallback);
            sk.state.SetAnimation(0, "animation", true);
            ui.btn_look_ad.SetClick(LookAd);
            ui.btn_look_ad.visible = false;
        }

        void LookAd()
        {

            //PlayerPrefs .SetInt("adCoolDownTime",Convert.ToInt32( GameHelper.GetNowTime()));
            if (_adNumbers >= 3 && (GameHelper.GetNowTime() <= PlayerPrefs.GetInt("ad_time") + _adCoolDown))
            {
                return;

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

            GameHelper.ShowVideoAd("reward_lobby", isSuccess =>
            {
                if (isSuccess)
                {
                    float[] cash_array = GameHelper.GetRewardValue(2);
                    GameDispatcher.Instance.Dispatch(GameMsg.Ad_success, cash_array[0]);
                }
            });
            ui.btn_look_ad.visible = false;
        }

        void GotoH5(object obj = null)
        {
            //CreatSheepCard.instance.SetCameraVisible(false);

         //   CtrlDispatcher.Instance.Dispatch(CtrlMsg.Webview_StateChange, WebUIType.H5);

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

        }
        public 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;
            }

        }

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

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

        }

        void SetMakeup(object a = null)
        {
            ui.money.number_text.text = GameHelper.Get102Str(GameHelper.Get102());

            DOVirtual.Float(0, (float)GameHelper.Get102(), 1,
                value => { ui.money.number_text.text = GameHelper.Get102Str((decimal)value); });

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

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

        void SetTopCurr(object a = null)
        {
            ui.gold.number_text.text = GameHelper.GetGoldNumber().ToString();
            // ui.gold.state.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0;

        }

        public void SetMoneyCurr(object a = null)
        {
            ui.money.number_text.text = GameHelper.Get102Str(GameHelper.Get102());
        }


        void OnChangeGold(object args)
        {
            if (!GameHelper.IsGiftSwitch()) return;

            var probability = GameHelper.GetCommonModel().Smallrewardsrate;
            var range = Random.Range(0, 101);
            if (range > probability) return;

            reward_data temp = args as reward_data;

            var rewardValue = GameHelper.GetRewardValue(0);
            var end = GameHelper.GetUICenterPosition(ui.money.GetChild("number_text"));

            if (temp != null)
            {
                temp.end = end;
                temp.change = rewardValue[0];
                temp.type = 111;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
            }

            GameHelper.AddMoney(rewardValue[0]);
            DOVirtual.DelayedCall(1, () =>
            {
                var startNum = (float)GameHelper.Get102() - rewardValue[0];

                DOVirtual.Float(startNum, (float)GameHelper.Get102(), 1f,
    value => { (ui.money.GetChild("number_text") as GTextField).text = GameHelper.Get102Str((decimal)value); });
            });
        }

        void OnChangeLookAd(object args = null)
        {
            if (GameHelper.IsGiftSwitch() && (Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().roomrewardrate) && !ui.btn_look_ad.visible)
            {
                ui.btn_look_ad.visible = true;
                _btnLookAdShowTime = 0;

            }
        }

        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);
        }

        void ad_success(object a = null)
        {
            var start = GameHelper.GetUICenterPosition(ui.btn_look_ad);
            var end = GameHelper.GetUICenterPosition(ui.money.number_text);

            if (a != null)
            {
                float cash = (float)a;
                reward_data temp = new reward_data() { start = start, end = end, change = cash, type = 111 };
                if (!GameHelper.IsGiftSwitch())
                {
                    temp.type = 101;
                    temp.end = GameHelper.GetUICenterPosition(ui.gold.number_text);
                    GameHelper.AddGoldNumber(3);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
                    DOVirtual.DelayedCall(1, () =>
                    {
                        DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1,
                            value => { ui.gold.number_text.text = ((int)value).ToString(); });
                    });
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
                    GameHelper.AddMoney(cash);
                    DOVirtual.DelayedCall(1, () =>
                    {
                        DOVirtual.Float(0, (float)GameHelper.Get102(), 1,
                            value => { ui.money.number_text.text = GameHelper.Get102Str((decimal)value); });
                    });
                }
            }

            ui.btn_look_ad.visible = false;

        }

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

            // _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; });
            //     }
            // }
            if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI))
            {
                GameHelper.addGameTime();
                GameHelper.SetGameTimes();
                //Debug.Log("zengjiashijian");
                makeupTaskData_saveing = SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1];
                if (makeupTaskData_saveing.status == SaveingPotTaskStatus.None)
                {
                    if (PreferencesMgr.Instance.ExchangeAccount != null)
                    {
                        makeupTaskData_saveing.H5Time += 1;
                    }
                }

                if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0)
                {
                    var taskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                    if (taskData != null)
                    {
                        PreferencesMgr.Instance.MakeupTaskH5Time += 1;
                    }
                }
            }


            if (!GameHelper.IsGiftSwitch()) return;


            _btnLookAdShowTime++;
            if (_btnLookAdShowTime > 15) ui.btn_look_ad.visible = false;
            SetSaveingPotBtn();


        }
        private SaveingPotClass makeupTaskData_saveing;
        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.btn_task.red.visible = SaveData.getRed();
            if (!GameHelper.IsGiftSwitch()) return;
            // if ((!SaveData.GetSaveobject().is_get_packreward || !SaveData.GetSaveobject().is_get_removead) && !SaveData.GetSaveobject().is_autopack_show
            //     && GameHelper.showGameUI && (Time.time > (ConfigSystem.GetConfig<CommonModel>().Activetimes * 60)))
            // {

            //     PackRewardData param = new PackRewardData();
            //     param.isAutoPop = true;
            //     param.isNeedScroll = false;
            //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param);
            //     SaveData.GetSaveobject().is_autopack_show = true;
            //     SaveData.GetSaveobject().is_autopack_show_day = DateTime.Now.Day;
            //     SaveData.saveDataFunc();
            // }
        }
    }
}