using FairyGUI;
using DG.Tweening;
using UnityEngine;
using BingoBrain.Core;
using BingoBrain.HotFix;
using FGUI.JBingoPlay;
using System.Collections.Generic;
using DontConfuse;

namespace BingoBrain
{
    public class BingoCardUI : BaseUI
    {
        private BingoCardUICtrl ctrl;
        private BingoCardModel model;
        private com_playcard ui;

        private List<btn_card> btn_Cards = new();
        private List<btn_card> btn_CardLst = new();
        private string tapRewardStr;

        public int ClickNum;
        public int MaxClickNum = 3;
        private bool canClick;
        private Queue<Tween> tweenerQueue = new();
        private List<Vector2> posLst = new();

        public BingoCardUI(BingoCardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.BingoCardUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "JBingoPlay";
            uiInfo.assetName = "com_playcard";
            uiInfo.layerType = UILayerType.Popup;

            uiInfo.isNeedUIMask = true;
        }

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

        protected override void OnClose()
        {
            ui?.FadeOut().OnComplete(() =>
            {
                ui?.fx_show.Stop();
                OnClearTween();
            });
            WebviewManager.Instance.SetDarkThough(true);
        }

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

            btn_Cards.Add(ui.btn_card1);
            btn_Cards.Add(ui.btn_card2);
            btn_Cards.Add(ui.btn_card3);
            btn_Cards.Add(ui.btn_card4);
            btn_Cards.Add(ui.btn_card5);
            btn_Cards.Add(ui.btn_card6);
            btn_Cards.Add(ui.btn_card7);
            btn_Cards.Add(ui.btn_card8);
            btn_Cards.Add(ui.btn_card9);

            ui.fairyBatching = false;

            foreach (var btnCard in btn_Cards)
            {
                posLst.Add(btnCard.position);
            }
        }

        protected override void OnOpenBefore(object args)
        {
            WebviewManager.Instance.SetDarkThough(false);
            InitView();
        }


        private void InitView()
        {
            ui.com_prize.list.touchable = false;
            flop_RewardVOLst.Clear();
            var dataList = GameHelper.GetConfig<FlopModel>().GetDataList();
            foreach (var item in dataList)
            {
                flop_RewardVOLst.Add(item);
            }

            Audio.Instance.PlayDynamicEffect("pop_open");
            ui.cont_state.selectedIndex = com_playcard.State_choose;
            foreach (var item in btn_Cards)
            {
                item.onClick.Set(OnClickCard);
            }

            ClickNum = 0;

            tapRewardStr = ui.text_Num.text;
            ui.text_Num.text = string.Format(tapRewardStr, ClickNum + "/" + MaxClickNum);
            ui.com_prize.list.SetVirtualAndLoop();
            ui.com_prize.list.itemRenderer = RendererTop;
            ui.com_prize.list.numItems = 5;

            ui.btn_collect.onClick.Set(ClickContinueBtn);
            ui.text_no.onClick.Set(ClickContinueBtn);
            ui.btn_video.onClick.Set(ClickVideoBtn);

            var tween = DOVirtual.Float(0, 0.745f, 20, e => { ui.com_prize.list.scrollPane.percX = e; }).SetLoops(-1);
            tweenerQueue.Enqueue(tween);
        }

        private void RendererTop(int index, GObject item)
        {
            var com_Prizeitem = (com_prizeitem)item;

            var val = index % 3;

            switch (val)
            {
                case 0:
                    EyesHarmony.GetItem(101, t => { com_Prizeitem.loader_item.texture = t; });
                    break;
                case 1:
                    EyesHarmony.GetItem(102, t => { com_Prizeitem.loader_item.texture = t; });
                    break;
                case 2:
                    EyesHarmony.GetItem(104, t => { com_Prizeitem.loader_item.texture = t; });
                    break;
                default:
                    com_Prizeitem.loader_item.texture = com_Prizeitem.loader_item.texture;
                    break;
            }
        }

        protected override void OnOpen(object args)
        {
            ui?.FadeIn();
            GameHelper.PlayFGUIFx(ui?.fx_show);

            DOVirtual.DelayedCall(ui.fx_show.totalDuration, () =>
            {
                ui.fx_show.Stop();
                Debug.Log("动画播放完成");
                canClick = true;
                for (var index = 0; index < btn_Cards.Count; index++)
                {
                    var btnCard = btn_Cards[index];
                    btnCard.scale = Vector2.one;
                    btnCard.visible = true;
                    btnCard.position = posLst[index];
                }
            });
        }

        private void ClickVideoBtn(EventContext context)
        {
            if (!canClick)
            {
                return;
            }

            GameHelper.GetVideo("reward_extraFlip", isSuccess =>
            {
                if (isSuccess)
                {
                    var adwardModel = GameHelper.GetConfig<AdRewardModel>();
                    MaxClickNum = Mathf.Clamp(MaxClickNum + adwardModel.GetData("reward_extraFlip").rewardAmount,
                        0, btn_Cards.Count);
                    ui.cont_state.selectedIndex = com_playcard.State_choose;
                    foreach (var item in btn_Cards)
                    {
                        item.onClick.Set(OnClickCard);
                    }

                    ui.text_Num.text = string.Format(tapRewardStr, ClickNum + "/" + MaxClickNum);
                }
            });
        }

        private void OnClickCard(EventContext context)
        {
            if (!canClick)
            {
                return;
            }

            var btn = context.sender as btn_card;

            if (btn.cont_button.selectedIndex == btn_card.Button_front)
            {
                return;
            }

            canClick = false;

            Audio.Instance.PlayDynamicEffect("flip");
            ClickNum++;
            ui.AddChild(btn);
            btn_CardLst.Add(btn);
            btn.onClick.Clear();
            btn.cont_button.selectedIndex = btn_card.Button_front;
            SetCardData(btn);
            ui.text_Num.text = string.Format(tapRewardStr, ClickNum + "/" + MaxClickNum);

            if (ClickNum >= MaxClickNum)
            {
                // 全部翻完
                foreach (var item in btn_Cards)
                {
                    item.onClick.Clear();
                }

                if (MaxClickNum >= btn_Cards.Count)
                {
                    ui.cont_state.selectedIndex = com_playcard.State_collect;
                }
                else
                {
                    ui.cont_state.selectedIndex = com_playcard.State_video;
                    var tw = GameHelper.DelayedShowGObject(this, ui.text_no);
                    tweenerQueue.Enqueue(tw);
                }
            }
        }

        private void ClickContinueBtn()
        {
            OpenAll();
        }

        private List<Flop> flop_RewardVOLst = new();

        private Flop GetRananVO()
        {
            if (flop_RewardVOLst.Count <= 0)
            {
                return null;
            }

            var index = Random.Range(0, flop_RewardVOLst.Count);
            var val = flop_RewardVOLst[index];
            flop_RewardVOLst.RemoveAt(index);
            if (!GameHelper.IsGiftSwitch() && val.itemID == 122)
            {
                val = GameHelper.GetConfig<FlopModel>().GetData(6);
            }

            return val;
        }

        private void OpenAll()
        {
            // 表现
            ui.cont_state.selectedIndex = com_playcard.State_none;

            float time = 0;
            var sum = 0;
            foreach (var item in btn_Cards)
            {
                if (item.cont_button.selectedIndex == btn_card.Button_front)
                {
                    continue;
                }

                var delay = time;
                var item1 = item;
                var tw = DOVirtual.DelayedCall(delay, () =>
                {
                    item1.cont_button.selectedIndex = btn_card.Button_front;
                    var vo = GetRananVO();
                    EyesHarmony.GetItem(vo.itemID, tx => { item1.loader_reward.texture = tx; });
                    item1.text_num.text = vo.itemID == 102
                        ? $"{GameHelper.Get102Str((decimal)vo.quantity[0])}"
                        : GameHelper.GetNoDecimalUnitStr(vo.quantity[0]);
                });
                tweenerQueue.Enqueue(tw);
                time += 0.1f;
                sum += 1;
            }

            var tew = DOVirtual.DelayedCall(sum * 0.25f,
                () => { uiCtrlDispatcher.Dispatch(SkinInfo.BingoCardUI_Close); });
            tweenerQueue.Enqueue(tew);
        }

        private void SetCardData(btn_card btn)
        {
            var vo = GetRananVO();
            var id = vo.itemID;
            var val = vo.quantity[GameHelper.GetDynamicIndex(id)];

            EyesHarmony.GetItem(id, tx => { btn.loader_reward.texture = tx; });
            btn.text_num.text = id == 102 ? GameHelper.Get102Str((decimal)val) : GameHelper.GetNoDecimalUnitStr(val);

            var startPosition = btn.position + (Vector3)btn.size / 2;
            if (vo.isMulti)
            {
                var tw = DOVirtual.DelayedCall(0.7f, () =>
                {
                    GameHelper.GetRewardExtra(id, (decimal)val, vo.cont_index, isCompleted =>
                    {
                        var tw1 = DOVirtual.DelayedCall(0.3f, () => { canClick = true; });
                        tweenerQueue.Enqueue(tw1);
                    }, startPosition);
                });
                tweenerQueue.Enqueue(tw);
            }
            else
            {
                if (id == 102)
                {
                    var rewardData = new RewardData();

                    var rewardSingleData = new Goda(102, (decimal)val, RewardOrigin.Slot)
                    {
                        startPosition = startPosition
                    };
                    rewardData.AddReward(rewardSingleData);
                    rewardData.AddCompleted(isSuccess =>
                    {
                        var tw1 = DOVirtual.DelayedCall(0.3f, () => { canClick = true; });
                        tweenerQueue.Enqueue(tw1);
                    });
                    rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
                    GameDispatcher.Instance.Dispatch(BingoInfo.GetReward, rewardData);
                }
                else
                {
                    GameHelper.GetRewardOnly1(id, (decimal)val, RewardOrigin.PlayCard, isSuccess =>
                    {
                        var tw1 = DOVirtual.DelayedCall(0.3f, () => { canClick = true; });
                        tweenerQueue.Enqueue(tw1);
                    }, startPosition);
                }
            }
        }

        private void OnClearTween()
        {
            while (tweenerQueue.Count > 0)
            {
                var tw = tweenerQueue.Dequeue();
                if (tw is { active: true })
                {
                    tw.Kill();
                }
            }
        }
    }
}