namespace ScrewsMaster
{
    using System;
    using FairyGUI;
    using UnityEngine;
    using DG.Tweening;
    using System.Text;
    using FGUI.G601_Coin;
    using Random = UnityEngine.Random;

    public class CurrencyRewardUI : BaseUI
    {
        private CurrencyRewardUICtrl ctrl;
        private CurrencyRewardModel model;
        private FGUI.G601_Coin.Com_CoinWnd ui;

        public RewardDisplayData data;
        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 CurrencyRewardUI(CurrencyRewardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.CurrencyRewardUI;
            this.ctrl = ctrl;
        }

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

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

                return;
            }

            data?.Update();
        }

        #region 生命周期

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

        protected override void OnClose()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Close);
            data?.EndEvent();
            DOVirtual.DelayedCall(Time.deltaTime, delegate
            {
                data?.UICloseEvent();
                data?.Dispose();
            });
            CloseCb?.Invoke();
        }

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

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

            if (data.isNeedFly)
            {
                if (!data.isSingle)
                {
                    ShowText();
                }

                ui.com_Coins.cont_coin.selectedIndex = !data.isSingle ? com_Coins.Coin_more : com_Coins.Coin_single;
                ui.com_Coins.position = data.rewardSingleData.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;
                    TextureHelper.GetItemIcon(data.rewardSingleData.id, spr => { item.icon.texture = spr; });
                    var def = val;
                    DOVirtual.DelayedCall(0.05f, () =>
                    {
                        item.visible = true;

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

                        item.TweenMove(tar, toSizeAniTime + def);
                        DOTween.To(() => item.size, (e) => item.size = e, Vector2.one, toSizeAniTime + def);
                        item.icon.visible = true;
                        DOVirtual.DelayedCall(toSizeAniTime + def, () =>
                        {
                            var moveTime = moveAniTime;
                            DOTween.To(() => item.icon.alpha, (e) => { item.icon.alpha = e; }, 0.6f, moveTime);
                            item.TweenMove(data.rewardSingleData.endPosition - (Vector2)item.parent.position +
                                           item.parent.size / 2, moveTime);
                            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 (completeSum >= ui.com_Coins.numChildren)
                                {
                                    DOVirtual.DelayedCall(0.2f, CtrlCloseUI);
                                }
                            });
                        });
                    });
                    val += 0.02f;
                }
            }
        }

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

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

        #endregion
    }
}