using System;
using System.Collections.Generic;
using FairyGUI;
using UnityEngine;
using System.Text;
using DG.Tweening;
using FGUI.JCoin;
using Random = UnityEngine.Random;
using BingoBrain.Core;
using BingoBrain.HotFix;

namespace BingoBrain
{
    public class GodPleAcUI : BaseUI
    {
        private GodPleAcUICtrl ctrl;
        private GodPleAcModel model;
        private FGUI.JCoin.Com_CoinWnd ui;

        public GodDa data;

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


        private bool isUpdate = false;


        private int completeSum = 0;


        private float toSizeAniTime = 0.4f;


        private float moveAniTime = 0.5f;


        private float showAniTime = 0.1f;


        private bool isRiseUI;

        private Action CloseCb;

        public GodPleAcUI(GodPleAcUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.GodPleAcUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "JCoin";
            uiInfo.assetName = "Com_CoinWnd";
            uiInfo.layerType = UILayerType.Animation;
            uiInfo.isTickUpdate = true;
        }

        public override void OnUpdate()
        {
            if (!isUpdate)
            {
                if (isRiseUI)
                {
                    if (data.Goda.id == 101 || data.Goda.id == 104)
                    {
                        GameHelper.OnRiseUIRecover(data.Goda.id, UILayerType.Normal);
                        isRiseUI = false;
                    }
                }

                return;
            }

            data?.Update();
        }

        #region 生命周期

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

        protected override void OnClose()
        {
            UICtrlDispatcher.Instance.Dispatch(SkinInfo.MaskUI_Close);
            data?.EndEvent();
            var tw = DOVirtual.DelayedCall(Time.deltaTime, delegate
            {
                data?.UICloseEvent();
                data?.Dispose();
            });
            CloseCb?.Invoke();
            tweenQueue.Enqueue(tw);
            OnClearTween();
        }

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

        protected override void OnOpenBefore(object args)
        {
            UICtrlDispatcher.Instance.Dispatch(SkinInfo.MaskUI_Open);
            if (args is GodDa displayModel)
            {
                data = displayModel;
                if (data.isPlayAudio)
                {
                    Audio.Instance.PlayDynamicEffect(data.audioName);
                }
            }

            if (data.isNeedFly)
            {
                ShowText();
                ui.com_Coins.position = data.Goda.startPosition;
                var val = 0f;
                ui.fx_enter.position = ui.com_Coins.position;
                foreach (var o in ui.com_Coins.GetChildren())
                {
                    var item = (com_Coin)o;
                    if (!item.visible)
                    {
                        continue;
                    }

                    item.visible = false;
                    //Debug.Log(tx);
                    EyesHarmony.GetItem(data.Goda.id, tx => { item.icon.texture = tx; });
                    var def = val;
                    var tw = DOVirtual.DelayedCall(0.05f, () =>
                    {
                        item.visible = true;

                        Vector2 tar = new Vector2(Random.Range(0, item.parent.size.x / (!data.isSingle ? 1 : 2)),
                            Random.Range(0, item.parent.size.y / (!data.isSingle ? 1 : 2)));
                        item.size = Vector2.zero;
                        item.position = new Vector2(item.parent.width / 2, item.parent.height / 2);

                        if (data.isSingle)
                        {
                            toSizeAniTime = 0.2f;
                        }

                        DOTween.To(() => item.position, (e) => item.position = e, new Vector3(tar.x, tar.y),
                            toSizeAniTime + def).SetEase(Ease.OutQuint);


                        var tw1 = DOTween.To(() => item.size, (e) => item.size = e, Vector2.one, toSizeAniTime + def);
                        tweenQueue.Enqueue(tw1);
                        item.icon.visible = true;
                        var tw2 = DOVirtual.DelayedCall(toSizeAniTime + def, () =>
                        {
                            var moveTime = moveAniTime;
                            var tw3 = DOTween.To(() => item.icon.alpha, (e) => { item.icon.alpha = e; }, 0.6f,
                                moveTime);
                            tweenQueue.Enqueue(tw3);

                            var tmp = data.Goda.endPosition - (Vector2)item.parent.position +
                                      item.parent.size / 2;
                            var localPos = GameHelper.FguiToUnityLocalPot(tmp);
                            item.displayObject.gameObject.transform.DOLocalMove(localPos, moveTime)
                                .SetEase(Ease.Linear);


                            var tw5 = DOVirtual.DelayedCall(moveTime, () =>
                            {
                                if (item is { icon: not null })
                                {
                                    item.icon.visible = false;
                                    completeSum++;
                                    var fxPlayData = FxPlayData.Get(Fx_Type.fx_ui_jinbi_click, 1,
                                        item.LocalToRoot(Vector2.zero, GRoot.inst));
                                    uiCtrlDispatcher.Dispatch(SkinInfo.PlayUIFX, fxPlayData);
                                }

                                if (!isUpdate)
                                {
                                    isUpdate = true;
                                }

                                if (completeSum >= ui.com_Coins.numChildren)
                                {
                                    var tw6 = DOVirtual.DelayedCall(0.2f, CtrlCloseUI);
                                    tweenQueue.Enqueue(tw6);
                                }
                            });
                            tweenQueue.Enqueue(tw5);
                        });
                        tweenQueue.Enqueue(tw2);
                    });
                    tweenQueue.Enqueue(tw);
                    val += 0.02f;
                }
            }
        }

        private void ShowText()
        {
            var sb = new StringBuilder();
            sb.Append("+");
            sb.Append(data.Goda.id == 102
                ? data.Goda.GetTotalValue().ToString("N")
                : data.Goda.GetTotalValue().ToString("N0"));

            ui.text_Add.SetText(sb.ToString());
            ui.text_Add.position = data.Goda.startPosition;
            ui.fx_addSum.Play();
        }

        protected override void OnOpen(object args)
        {
        }

        #endregion


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

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