using System;
using System.Collections.Generic;
using System.Text;
using DG.Tweening;
using FairyGUI;
using FGUI.Coins_101;
using UnityEngine;
using Random = UnityEngine.Random;


namespace ChillConnect
{
    public class RewardAniUI : BaseUI
    {
        private RewardAniUICtrl ctrl;
        private RewardAniModel model;
        private com_coinFly ui;

        public RewardDisplayData data;


        private bool isUpdate;


        private int completeSum;


        private float toSizeAniTime = 0.4f;


        private float moveAniTime = 0.5f;


        private float showAniTime = 0.1f;


        private bool isRiseUI;

        private Action CloseCb;

        private List<Tween> tweenList = new List<Tween>();

        private Tween closeTween;

        public RewardAniUI(RewardAniUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.RewardAniUI;
            this.ctrl = ctrl;
        }

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

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

                return;
            }

            data?.Update();
        }

        #region 生命周期

        protected override void OnInit()
        {
            model = moduleManager.GetModel(ModelConst.RewardAniModel) as RewardAniModel;
        }

        protected override void OnClose()
        {
            foreach (var tween in tweenList)
            {
                if (tween is { active: true })
                {
                    tween.Kill();
                }
            }

            tweenList.Clear();

            data?.EndEvent();

            DOVirtual.DelayedCall(Time.deltaTime, delegate
            {
                data?.UICloseEvent();
                data?.Dispose();
            });
            CloseCb?.Invoke();
        }

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

        protected override void OnOpenBefore(object args)
        {
            if (args is RewardDisplayData displayModel)
            {
                data = displayModel;
            }

            ui.com_coins.visible = false;
            ui.text_Add.visible = false;

            InitView(data);
        }

        private void InitView(RewardDisplayData data)
        {
            if (data.isPlayAudio)
            {
                AudioManager.Instance.PlayDynamicEffect(data.audioName);
            }

            if (data.isNeedFly)
            {
                var comFly = UIPackage.CreateObject("Coins_101", "com_coinFly").asCom as com_coinFly;

                var comFlyCurrency = comFly.com_coins;
                comFlyCurrency.visible = true;
                if (!data.isSingle)
                {
                    var sb = new StringBuilder();
                    sb.Append("+");
                    if (data.rewardSingleData.id == 102 || data.rewardSingleData.id == 106)
                    {
                    }

                    sb.Append(GameHelper.GetNumStr((float)data.rewardSingleData.GetTotalValue(), 2));
                    comFly.text_Add.SetText(sb.ToString());
                    comFly.text_Add.position = data.rewardSingleData.startPosition;
                    // comFly.fx_addSum.Play();
                }

                comFlyCurrency.cont_coin.selectedIndex =
                    !data.isSingle ? com_coins.Coin_more : com_coins.Coin_single;
                comFlyCurrency.position = data.rewardSingleData.startPosition;

                float val = 0f;

                comFly.fx_enter.position = comFlyCurrency.position;


                foreach (var o in comFlyCurrency.GetChildren())
                {
                    var item = (com_coin)o;
                    if (!item.visible)
                    {
                        continue;
                    }

                    item.visible = false;
                    //item.icon.texture = TextureHelper.GetItemIcon(data.rewardSingleData.id);
                    TextureHelper.GetItemIcon(data.rewardSingleData.id, spr => { item.icon.texture = spr; });
                    float def = val;
                    var tween = 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)
                        {
                        }
                        else
                        {
                            toSizeAniTime = 0.2f;
                        }

                        item.TweenMove(tar, toSizeAniTime + def);
                        var moveTween = DOTween.To(() => item.size, e => item.size = e, Vector2.one,
                            toSizeAniTime + def);
                        tweenList.Add(moveTween);

                        item.icon.visible = true;
                        var delayTween = DOVirtual.DelayedCall(toSizeAniTime + def, () =>
                        {
                            var moveTime = moveAniTime;
                            var moveTween2 = DOTween.To(() => item.icon.alpha, e => { item.icon.alpha = e; },
                                0.6f,
                                moveTime);
                            tweenList.Add(moveTween2);

                            if (item != null)
                            {
                                item.TweenMove(data.rewardSingleData.endPosition -
                                               (Vector2)item.parent.position +
                                               item.parent.size / 2, moveTime);
                            }


                            var delayTween2 = DOVirtual.DelayedCall(moveTime, () =>
                            {
                                item.icon.visible = false;
                                completeSum++;
                                var fxPlayData = FxPlayData.Get(Fx_Type.fx_ui_jinbi_click, 1,
                                    item.LocalToRoot(Vector2.zero, GRoot.inst));
                                uiCtrlDispatcher.Dispatch(UICtrlMsg.PlayUIFX, fxPlayData);

                                if (!isUpdate)
                                {
                                    isUpdate = true;
                                }

                                if (data.isSingle)
                                {
                                    if (closeTween is { active: true })
                                    {
                                        closeTween.Kill();
                                    }

                                    closeTween = DOVirtual.DelayedCall(2f, CtrlCloseUI);
                                    tweenList.Add(closeTween);
                                }
                                else
                                {
                                    if (completeSum >= comFly.numChildren)
                                    {
                                        if (closeTween is { active: true })
                                        {
                                            closeTween.Kill();
                                        }

                                        closeTween = DOVirtual.DelayedCall(2f, CtrlCloseUI);
                                        tweenList.Add(closeTween);
                                    }
                                }
                            });
                            tweenList.Add(delayTween2);
                        });
                        tweenList.Add(delayTween);
                    });
                    tweenList.Add(tween);
                    val += 0.02f;
                }

                ui.AddChild(comFly);
            }
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
        }

        protected override void RemoveListener()
        {
        }

        #endregion
    }
}