using Spine;
using System;
using FairyGUI;
using DG.Tweening;
using UnityEngine;
using Spine.Unity;
using BingoBrain.Core;
using BingoBrain.HotFix;
using FGUI.JMain;
using System.Collections.Generic;
using Random = UnityEngine.Random;
using FGUI.ACommon;
using System.Linq;
using Newtonsoft.Json;

namespace BingoBrain
{
    public class BingoHallUI : BaseUI
    {
        private BingoHallUICtrl ctrl;
        private BingoHallModel model;
        public com_main ui;

        private float moveTime = 3;
        private bool isLeft = true;
        private Tween waitTween;
        private string RadioStr = "[color=#00FF00]{0} [/color]sent to [color=#FF0000]{1}[/color]";

        private Queue<GTweener> gtweenerQueue = new();
        private Queue<Tween> tweenerQueue = new();

        bool IsBallonCD => GameHelper.GetNowTime() < PreferencesMgr.Instance.BallonCdTime;

        public BingoHallUI(BingoHallUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.BingoHallUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期

        protected override void OnInit()
        {
            model = ModuleBoardk.GetModel(ModelConst.BingoHallModel) as BingoHallModel;
        }

        protected override void OnClose()
        {
            OnClearTween();
            Hall.Instance.UpdateSecondEvent -= UpdateSecond;
        }

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

        protected override void OnOpenBefore(object args)
        {
            InitView();
            // if (!GameHelper.IsGiftSwitch() && (ConfigSystem.GetConfig<CommonModel>().WVswitch == 1))
            // {
            //     ui.btn_h5.visible = true;
            //     ui.btn_h5.GetChild("number_text").visible=false;
            // }
            //   ui.btn_h5.SetClick(() =>
            // {
            //     UICtrlDispatcher.Instance.Dispatch(SkinInfo.H5UI_Open);
            // });

        }

        protected override void OnOpen(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            Hall.Instance.AddChangeGiftSwitch(InitView);
            PreferencesDispatcher<int>.Instance.AddListener(PreferencesMsg.cardBoardSum, CardBoardSumChange);
            GameDispatcher.Instance.AddListener(BingoInfo.RefreshMakeupData, SetMakeup);
        }

        protected override void RemoveListener()
        {
            Hall.Instance.RemoveChangeGiftSwitch(InitView);
            PreferencesDispatcher<int>.Instance.RemoveListener(PreferencesMsg.cardBoardSum, CardBoardSumChange);
            GameDispatcher.Instance.RemoveListener(BingoInfo.RefreshMakeupData, SetMakeup);
        }

        #endregion

        private void InitView()
        {
            if (GameHelper.IsGiftSwitch())
            {
                ui.gift.selectedIndex = 1;
                (ui.btn_ballon as btn_balloon).gift.selectedIndex = 1;
            }
            ;
#if !UNITY_EDITOR
               ui.btn_admin.visible=false;
#endif
            if (Screen.safeArea.y != 0)
            {//刘海屏
                ui.com_cards.y += Screen.safeArea.y;
            }
            InitSpine();
            ui.btn_play.SetClick(OnClickPlay);

            ui.com_cardnum.cont_state.onChanged.Set(() => { OnCardNumChange(null); });

            ui.com_cardnum.btn_add.SetClick(OnBtnAddClick);
            ui.com_cardnum.btn_add.cont_button.selectedIndex = PlayerPrefs.GetInt("FirstGame", 0) == 1
                ? ui.com_cardnum.btn_add._Button_light
                : ui.com_cardnum.btn_add._Button_dark;
            ui.com_cardnum.btn_add.touchable = PlayerPrefs.GetInt("FirstGame", 0) == 1;
            ui.com_cardnum.btn_minus.SetClick(OnBtnMinusClick);

            OnCardNumChange(null);
            ui.com_cardnum.cont_state.selectedIndex = model.CardBoardCountIndex;
            ui.com_cardplay.cont_text.selectedIndex = model.CardBoardCountIndex;
            ui.type.selectedIndex = model.CardBoardCountIndex;
            ui.btn_ballon.visible = !IsBallonCD;
            (ui.btn_ballon as btn_balloon).cash_text.text = $" {GameHelper.GetDynamicReward(102, GameHelper.GetCommonModel().ballonReward102):N}";
            ui.btn_ballon.SetClick(OnClickBalloon);
            ui.btn_ballon.sortingOrder = 100;

            MoveToOtherSide();
            Hall.Instance.UpdateSecondEvent += UpdateSecond;
            CardBoardSumChange(null);
            UpdateNextCardBoardTime();
            ui.com_cards.SetClick(() =>
            {
                if (PreferencesMgr.Instance.CardBoardSum == 0)
                {
                    uiCtrlDispatcher.Dispatch(SkinInfo.MoreCardUI_Open);
                }
            });
            ui.fairyBatching = false;
            SetMakeup();
            ui.btn_admin.SetClick(() =>
            {
                // MakeupTaskData makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                // makeupTaskData.videoCount = 999999;
                // PreferencesMgr.Instance.MakeupTaskH5Time = 99999;
                // PreferencesMgr.Instance.Currency102 = 99999;
                // PreferencesMgr.Instance.Currency101 = 99999999;
                // GameDispatcher.Instance.Dispatch(BingoInfo.RefreshMakeupData);

                // makeupTaskData = PreferencesMgr.Instance.CoinMakeupTaskHistory.Last();
                // makeupTaskData.videoCount = 99999;
                // PreferencesMgr.Instance.CoinMakeupTaskH5Time = 99999;

            });
            ui.btn_set.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(SkinInfo.JThinkUI_Open);
            });
            ui.btn_question.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(SkinInfo.FaqUIUI_Open);
            });
            // ui.btn_cashout.SetClick(() =>
            // {
            //     var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
            //     var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);
            //     //DataMgr.Ticket.Value=99999;
            //     //makeupTaskData.videoCount = 50;
            //     if (vo == null)
            //     {
            //         return;
            //     }
            //     UICtrlDispatcher.Instance.Dispatch(SkinInfo.MakeupConfirmUI_Open, makeupTaskData);
            // });
            ui.btn_saveingpot.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(SkinInfo.SaveingPotUI_Open);
            });
            ui.btn_petty.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(SkinInfo.PettyAwardUI_Open);
            });
            ui.btn_wb.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(SkinInfo.H5UI_Open);
            });
            if (SaveData.GetSaveobject().PettyState == 0 && GameHelper.IsGiftSwitch()) UICtrlDispatcher.Instance.Dispatch(SkinInfo.PettyAwardUI_Open);
            if (GameHelper.IsGiftSwitch() || (ConfigSystem.GetConfig<CommonModel>().WVswitch == 1))
            {
                ui.btn_wb.visible = true;
            }
            if (GameHelper.GetCommonModel().PiggyBankSwitch != 1) ui.btn_saveingpot.visible = false;
            Debug.Log(JsonConvert.SerializeObject(GameHelper.GetConfig<AdRewardModel>().dataList));
            ui.btn_pal.SetClick(() =>
            {
                  UICtrlDispatcher.Instance.Dispatch(SkinInfo.PalUI_Open);
            });
        }

        private void UpdateNextCardBoardTime()
        {
            if (ui.com_cards.text_time.visible)
            {
                ui.com_cards.text_time.text = $"New card in {model.NextCardBoardTimeStr}s";
            }
        }

        private void CardBoardSumChange(object obj)
        {
            if (PreferencesMgr.Instance.CardBoardSum >= model.MaxCardBoardSum)
            {
                ui.com_cards.cont_cardleft.selectedIndex = com_playnum.Cardleft_full;
            }
            else if (PreferencesMgr.Instance.CardBoardSum == 0)
            {
                ui.com_cards.cont_cardleft.selectedIndex = com_playnum.Cardleft_none;
            }
            else
            {
                ui.com_cards.cont_cardleft.selectedIndex = com_playnum.Cardleft_left;
            }

            ui.com_cards.text_num.text = GameHelper.GetNoDecimalUnitStr(PreferencesMgr.Instance.CardBoardSum);
        }


        private bool isMoveFinish = true;
        private Vector2 StartPos = new(9, 647);
        private Vector2 FinalPos = new(925, 539);

        void MoveToOtherSide()
        {
            if (waitTween != null)
            {
                return;
            }

            isLeft = !isLeft;
            if (!ui.btn_ballon.visible)
            {
                return;
            }

            if (!isMoveFinish)
            {
                return;
            }

            var targetPos = isLeft ? StartPos : FinalPos;
            float offset = 300;
            targetPos.y = Random.Range(BingoCell.CenterUIPos.y - offset, BingoCell.CenterUIPos.y + offset);
            isMoveFinish = false;
            var tw = ui.btn_ballon.TweenMove(targetPos, moveTime).OnComplete(() =>
            {
                isMoveFinish = true;
                ui.btn_ballon.InvalidateBatchingState();
                float waitTime = Random.Range(5, 11);
                waitTween = DOVirtual.DelayedCall(waitTime, () =>
                {
                    waitTween = null;
                    MoveToOtherSide();
                });
                tweenerQueue.Enqueue(waitTween);
            });
            gtweenerQueue.Enqueue(tw);
        }

        private void UpdateSecond()
        {
            if (!Hall.Instance.IsGaming())
            {
                if (ui != null && ui.btn_ballon != null)
                {
                    if (ui.btn_ballon.visible != !IsBallonCD)
                    {
                        ui.btn_ballon.visible = !IsBallonCD;
                        // 开始移动
                        if (ui.btn_ballon.visible)
                        {
                            MoveToOtherSide();
                            (ui.btn_ballon as btn_balloon).cash_text.text = $" {GameHelper.GetDynamicReward(102, GameHelper.GetCommonModel().ballonReward102):N}";
                        }
                    }
                }
            }

            UpdateNextCardBoardTime();
        }


        private void OnClickBalloon()
        {
            if (BingoCell.isProcedure || BingoCell.IsGuiding)
            {
                return;
            }

            Audio.Instance.PlayDynamicEffect("button");

            GameHelper.GetVideo("reward_flyballoon", isSuccess =>
            {
                if (isSuccess)
                {
                    ui.btn_ballon.touchable = false;
                    var rewardType = GameHelper.GetCommonModel().ballonRewardType[0];
                    double rewardCount = 0;
                    if (rewardType == 102)
                    {
                        rewardCount = GameHelper.GetDynamicReward(102, GameHelper.GetCommonModel().ballonReward102);
                    }

                    ui.btn_ballon.visible = false;
                    PreferencesMgr.Instance.BallonCdTime =
                        (int)(GameHelper.GetNowTime() + GameHelper.GetCommonModel().ballonCD);
                    GameHelper.GetRewardOnly(rewardType, (decimal)rewardCount, RewardOrigin.Ballon,
                        isSuccess =>
                        {
                            ui.btn_ballon.touchable = true;
                            GameDispatcher.Instance.Dispatch(BingoInfo.RefreshMakeupData);
                        }, ui.btn_ballon);
                }
            });
        }

        private void OnBtnMinusClick()
        {
            model.CardBoardCountIndex--;
            ui.com_cardnum.cont_state.selectedIndex = model.CardBoardCountIndex;
            ui.com_cardplay.cont_text.selectedIndex = model.CardBoardCountIndex;
            Debug.Log(model.CardBoardCountIndex);
            ui.type.selectedIndex = model.CardBoardCountIndex;
            // var animName = model.CardBoardCountIndex switch
            // {
            //     0 => "2_1",
            //     1 => "4_2",
            //     _ => ""
            // };
            //  NAAVsa.PlayAnim(cardSpine, animName);
        }

        private void OnBtnAddClick()
        {
            model.CardBoardCountIndex++;
            ui.com_cardnum.cont_state.selectedIndex = model.CardBoardCountIndex;
            ui.com_cardplay.cont_text.selectedIndex = model.CardBoardCountIndex;
            ui.type.selectedIndex = model.CardBoardCountIndex;
            // var animName = model.CardBoardCountIndex switch
            // {
            //     1 => "1_2",
            //     2 => "2_4",
            //     _ => ""
            // };

            // NAAVsa.PlayAnim(cardSpine, animName);
        }

        private void OnCardNumChange(EventContext context)
        {
            switch (model.CardBoardCountIndex)
            {
                case 0:
                    ui.com_cardnum.btn_minus.cont_button.selectedIndex = ui.com_cardnum.btn_minus._Button_dark;
                    ui.com_cardnum.btn_add.cont_button.selectedIndex = ui.com_cardnum.btn_add._Button_light;
                    ui.com_cardnum.btn_minus.touchable = false;
                    ui.com_cardnum.btn_add.touchable = true;
                    break;
                case 2:
                    ui.com_cardnum.btn_minus.cont_button.selectedIndex = ui.com_cardnum.btn_minus._Button_light;
                    ui.com_cardnum.btn_add.cont_button.selectedIndex = ui.com_cardnum.btn_add._Button_dark;
                    ui.com_cardnum.btn_minus.touchable = true;
                    ui.com_cardnum.btn_add.touchable = false;
                    break;
                default:
                    ui.com_cardnum.btn_minus.cont_button.selectedIndex = ui.com_cardnum.btn_minus._Button_light;
                    ui.com_cardnum.btn_add.cont_button.selectedIndex = ui.com_cardnum.btn_add._Button_light;
                    ui.com_cardnum.btn_minus.touchable = true;
                    ui.com_cardnum.btn_add.touchable = true;
                    break;
            }
        }

        private SkeletonAnimation cardSpine;
        private Action CloseCb;

        private void InitSpine()
        {
            if (cardSpine != null)
            {
                return;
            }
            // if (GameHelper.IsGiftSwitch())
            // {
            //     FX.Instance.SetFx<SkeletonAnimation>(ui.gp_fx, Fx_Type.spine_choice_card_b, sk =>
            //     {
            //         cardSpine = sk;

            //         NAAVsa.AddCompleteEvent(cardSpine, OnChangeCardFinish);
            //         OnChangeCardFinish(null);
            //     }, CloseCb);
            // }
            // else
            // {
            //     FX.Instance.SetFx<SkeletonAnimation>(ui.gp_fx, Fx_Type.spine_choice_card, sk =>
            //     {
            //         cardSpine = sk;

            //         NAAVsa.AddCompleteEvent(cardSpine, OnChangeCardFinish);
            //         OnChangeCardFinish(null);
            //     }, CloseCb);
            // }


        }

        private void OnChangeCardFinish(TrackEntry trackEntry)
        {
            if (trackEntry != null && trackEntry.Animation.Name.Contains("animation"))
            {
                return;
            }

            var idleName = model.CardBoardCountIndex switch
            {
                0 => "animation1",
                1 => "animation2",
                _ => "animation4"
            };

            NAAVsa.PlayAnim(cardSpine, idleName, true);
        }

        private void OnClickPlay()
        {
            if (PreferencesMgr.Instance.CardBoardSum >= BingoCell.CardBoardCount)
            {
                PreferencesMgr.Instance.CardBoardSum -= BingoCell.CardBoardCount;
                ui.com_cards.text_fx.text = $"-{BingoCell.CardBoardCount}";
                ui.touchable = false;
                ui.com_cards.fx_num.Play();
                DOVirtual.DelayedCall(ui.com_cards.fx_num.totalDuration / 2, () =>
                {
                    uiCtrlDispatcher.Dispatch(SkinInfo.SmailUI_Close);
                    GameDispatcher.Instance.Dispatch(BingoInfo.StartBingoGame);
                });
            }
            else
            {
                uiCtrlDispatcher.Dispatch(SkinInfo.MoreCardUI_Open);
            }

        }

        private void OnClearTween()
        {
            while (gtweenerQueue.Count > 0)
            {
                var tw = gtweenerQueue.Dequeue();
                tw?.Kill();
            }

            while (tweenerQueue.Count > 0)
            {
                var tw = tweenerQueue.Dequeue();
                if (tw is { active: true })
                {
                    tw.Kill();
                }
            }
        }
        void SetMakeup(object a = null)
        {
            return;
            // var com_box = ui.com_box;
            // com_box.cont_white.selectedIndex =
            //     GameHelper.IsGiftSwitch() ? com_box._White_none : com_box._White_white;
            // if (!GameHelper.IsGiftSwitch())
            // {
            //     ui.text_uid.SetVar("uid", loginModel.uid.ToString()).FlushVars();
            // }


            // GameHelper.SetSelfCountryFlag(ui.com_box.btn_menu.loader_flag);
            // SetAvatar();
            // SetName();

            // com_box.text_num.text = GameHelper.Get101Str(PreferencesMgr.Instance.Currency101);

            // DOVirtual.Float(0, (float)PreferencesMgr.Instance.Currency101, 1,
            //     value => { com_box.text_num.text = GameHelper.Get101Str((decimal)value); });



            if (GameHelper.IsGiftSwitch())
            {


                // var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                // Debug.Log(PreferencesMgr.Instance.MakeupTaskHistory.Count);
                // Debug.Log(JsonConvert.SerializeObject(makeupTaskData));
                // Debug.Log(ConfigSystem.GetConfig<MakeupModel>().GetCount());
                // Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<MakeupModel>()));

                makeup vo = null;

                // foreach (makeup item in ConfigSystem.GetConfig<MakeupModel>().dataList)
                // {
                //     Debug.Log(JsonConvert.SerializeObject(item));
                //     if (item.id == makeupTaskData.tableId) vo = item;
                // }
                //  Debug.Log(ConfigSystem.GetConfig<MakeupModel>().GetData(0));
                // Debug.Log(ConfigSystem.GetConfig<MakeupModel>().GetData(1));
                // Debug.Log(ConfigSystem.GetConfig<MakeupModel>().GetData(2));
                // if (vo == null)
                // {
                //     return;
                // }
    //             DOVirtual.Float(0, (float)PreferencesMgr.Instance.Currency102, 1,
    // value => { ui.makeup.cash_text.text = value.ToString("0.00"); });

    //             ui.makeup.cash_progress_text.text = PreferencesMgr.Instance.Currency102 + "/" + vo.item_need;
    //             ui.makeup.cash_progress.value = ((float)PreferencesMgr.Instance.Currency102 * 100) / vo.item_need;
                // var leftCash = (double)Math.Max(vo.item_need - PreferencesMgr.Instance.Currency101, 0);
                // com_box.text_more.SetVar("left", GameHelper.Get101Str((decimal)leftCash)).FlushVars();
                // com_box.pb_num.max = vo.item_need;
                // com_box.pb_num.value = vo.item_need - leftCash;
                // pbTxt.text =
                //     $"{GameHelper.Get101Str((decimal)(vo.item_need - leftCash))}/{GameHelper.Get101Str((decimal)com_box.pb_num.max)}";

                // ui.makeup.btn_cash.SetClick(() =>
                //   {
                //       Debug.Log("999999999999999");
                //       //   if (GameHelper.CanGuide() && !GuideCtrl.Instance.IsFinishGuide(1))
                //       //   {
                //       //       GuideCtrl.Instance.Dispatch("ClickButton");
                //       //       ui.com_box.finger_place.visible = false;
                //       //   }

                //       uiCtrlDispatcher.Dispatch(SkinInfo.MakeupConfirmUI_Open, makeupTaskData);
                //   });
            }

            {
                // if (PreferencesMgr.Instance.CoinMakeupTaskHistory.Count == 0)
                // {

                //     BingoDataSystem.CheckCoinMakeupTaskData();
                //     //PreferencesMgr.Instance.MakeupTaskHistory.Add(new MakeupTaskData());
                //     //Debug.Log(PreferencesMgr.Instance.MakeupTaskHistory.Count);
                // }

                //             var makeupTaskData = PreferencesMgr.Instance.CoinMakeupTaskHistory.Last();
                //             var vo = ConfigSystem.GetConfig<CardRedeemNewModel>().dataList
                // .FirstOrDefault(cardNew => cardNew.id == makeupTaskData.tableId);
                //             Debug.Log(JsonConvert.SerializeObject(vo));
                //             DOVirtual.Float(0, PreferencesMgr.Instance.Currency101, 1,
                //                 value => { ui.makeup.gold_text.text = ((int)value).ToString(); });
                //             ui.makeup.gold_progress_text.text = PreferencesMgr.Instance.Currency101 + "/" + vo.item_need;
                //             ui.makeup.gold_progress.value = ((float)PreferencesMgr.Instance.Currency101 * 100) / vo.item_need;
                //             Debug.Log(((float)PreferencesMgr.Instance.Currency101) / vo.item_need);
                //             ui.makeup.coin_cash.text = "$" + vo.redeem_num;
                //             ui.makeup.btn_goldout.SetClick(() =>
                //             {
                //                 Debug.Log(PreferencesMgr.Instance.Currency101);
                //                 Debug.Log(vo.item_need);
                //                 if (makeupTaskData.status == MakeupTaskStatus.None)
                //                 {
                //                     if (PreferencesMgr.Instance.Currency101 >= vo.item_need)
                //                     {
                //                         uiCtrlDispatcher.Dispatch(SkinInfo.MakeupConfirmUI_Open, makeupTaskData);
                //                     }
                //                     else
                //                     {
                //                         GameHelper.ShowTips("Not enough", true);
                //                     }
                //                 }
                //                 else
                //                 {
                //                     uiCtrlDispatcher.Dispatch(SkinInfo.MakeupConfirmUI_Open, makeupTaskData);
                //                 }
                //             });
            }
            (ui.btn_ballon as btn_balloon).cash_text.text = GameHelper.GetDynamicReward(102, GameHelper.GetCommonModel().ballonReward102).ToString("0.00");
        }
    }
}