using System;
using DG.Tweening;
using BingoBrain.Core;
using UnityEngine;
using System.Collections.Generic;
using FGUI.JBingoPlay;
using Random = UnityEngine.Random;

namespace BingoBrain
{
    public class ChestUI : BaseUI
    {
        private ChestUICtrl ctrl;
        private ChestModel model;
        private com_pickBox ui;
        List<btn_box> btnList = new();
        Gsss _gsss = new();
        List<Vector2> posList = new();
        private bool isAniming;
        private int rewardCount;
        private float lastRewardCount;

        private QBLOX LastReward => GameHelper.GetConfig<QBLOXModel>().GetLast();

        public ChestUI(ChestUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.ChestUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "JBingoPlay";
            uiInfo.assetName = "com_pickBox";
            uiInfo.layerType = UILayerType.Normal;
            uiInfo.isNeedOpenAnim = true;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

        #region 生命周期

        protected override void OnInit()
        {
        }

        protected override void OnClose()
        {
        }

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

        protected override void OnOpenBefore(object args)
        {
            ui?.FadeIn();
            InitView();
        }

        protected override void OnOpen(object args)
        {
            Audio.Instance.PlayDynamicEffect("pickbox_enter");
        }

        #endregion

        private void InitView()
        {
            if (BingoCell.isFirstGame && PreferencesMgr.Instance.IsFirstBox)
            {
                PreferencesMgr.Instance.IsFirstBox = false;
            }
            if (GameHelper.IsGiftSwitch()) ui.com_boxdown.gift.selectedIndex = 1;

            ui.closeButton.SetClick(CtrlCloseUI);
            GameHelper.DelayedShowGObject(this, ui.closeButton);

            btnList.Add(ui.box1);
            btnList.Add(ui.box2);
            btnList.Add(ui.box3);
            btnList.Add(ui.box4);

            lastRewardCount = LastReward.quantity[GameHelper.GetDynamicVersion_Cash().id - 1];
            RefreshBoxDown();
            var indexList = new List<int>();

            for (var i = 0; i < 4; i++)
            {
                indexList.Add(i);
            }

            isAniming = true;
            indexList = GlobalHarmony.GetRandomList(indexList, 4);

            /*foreach (var id in indexList)
            {
                Debug.Log(id);
            }*/

            for (var i = 0; i < indexList.Count; i++)
            {
                var index = i;
                var btn = btnList[index];
                if (GameHelper.IsGiftSwitch()) btn.gift.selectedIndex = 1;
                btn.sortingOrder = index + 1;
                posList.Add(btn.position);
                // btn.pivotAsAnchor = true;
                btn.cont_box.selectedIndex = btn._Box_front;
                btn.cont_first.selectedIndex = BingoCell.isFirstGame ? btn._First_isFirst : btn._First_none;

                var pickBoxVo = GameHelper.GetConfig<QBLOXModel>().GetDataByIndex(index);
                var reward = pickBoxVo.isCoin
                    ? pickBoxVo.quantity[GameHelper.GetDynamicVersion_Coin().id - 1]
                    : pickBoxVo.quantity[GameHelper.GetDynamicVersion_Cash().id - 1];

                btn.cont_type.selectedIndex = pickBoxVo.isCoin ? btn._Type_coin : btn._Type_cash;
                btn.text_num.text = GameHelper.GetItemSum(pickBoxVo.itemId, (decimal)reward);
                btn.SetClick(() => { OnBtnBoxClick(btn, pickBoxVo, reward); });
            }

            _gsss.Add(0.6f, (obj) =>
            {
                var duration = 0.5f;
                foreach (var btn in btnList)
                {
                    btn.fx_fronttoback.invalidateBatchingEveryFrame = true;
                    btn.fx_fronttoback.timeScale = 2;
                    btn.fx_fronttoback.Play();
                    btn.cont_box.selectedIndex = btn._Box_back;
                }

                DOVirtual.DelayedCall(duration, obj.InvokeComplete);
            });
            Vector2 center = BingoCell.CenterUIPos - ui.box1.size / 2;
            _gsss.Add((obj) =>
            {
                var duration = 0.5f;
                foreach (var btn in btnList)
                {
                    var originPos = btn.position;
                    btn.TweenMove(center, 0.5f);
                    var btn1 = btn;
                    DOVirtual.Float(0, 1, duration, prg =>
                    {
                        btn1.InvalidateBatchingState();
                        btn1.position = Vector2.Lerp(originPos, center, prg);
                    });
                }

                DOVirtual.DelayedCall(duration, obj.InvokeComplete);
            });

            _gsss.Add((obj) =>
            {
                var count = 0;
                foreach (var btn in btnList)
                {
                    var seq = new Gsss();
                    for (var j = 0; j < 6; j++)
                    {
                        float distance = Random.Range(100, 200);

                        var time = Random.Range(0.1f, 0.3f);
                        Vector2 targetPos;
                        if (j % 2 == 0)
                        {
                            var dir = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
                            dir.Normalize();
                            targetPos = center + dir * distance;
                        }
                        else
                        {
                            targetPos = center;
                        }

                        var btn1 = btn;
                        seq.Add(tmp =>
                        {
                            btn1.InvalidateBatchingState();
                            btn1.TweenMove(targetPos, time);
                            DOVirtual.DelayedCall(time, tmp.InvokeComplete);
                        });
                    }

                    seq.onFinish = delegate
                    {
                        count++;
                        if (count == btnList.Count)
                        {
                            obj.InvokeComplete();
                        }
                    };

                    seq.Run();
                }
            });

            _gsss.Add((obj) =>
            {
                var duration = 0.2f;
                for (var i = 0; i < indexList.Count; i++)
                {
                    var index = indexList[i];
                    var btn = btnList[i];
                    Debug.Log($"{i}:{index}");
                    btn.TweenMove(posList[index], duration);
                }

                DOVirtual.DelayedCall(duration, obj.InvokeComplete);
            });
            _gsss.onFinish = delegate { isAniming = false; };
            _gsss.Run();
        }


        private void OnBtnBoxClick(btn_box box, QBLOX vo, float reward)
        {
            if (isAniming)
            {
                return;
            }

            if (box.cont_box.selectedIndex == box._Box_front)
            {
                return;
            }

            Action<bool> cb = delegate
            {
                box.fx_backtofront.timeScale = 2;
                box.fx_backtofront.invalidateBatchingEveryFrame = true;
                box.fx_backtofront.Play();
                DOVirtual.DelayedCall(box.fx_backtofront.totalDuration, delegate
                {
                    GameHelper.GetRewardOnly(vo.itemId, (decimal)reward, RewardOrigin.PickBox, null, box);
                    rewardCount++;
                    RefreshBoxDown();
                    if (rewardCount == 4)
                    {
                        GameHelper.GetRewardOnly(LastReward.itemId, (decimal)lastRewardCount, RewardOrigin.PickBox,
                            isSuccess => { CtrlCloseUI(); }, ui.com_boxdown.icon_102);
                    }
                });
                box.cont_box.selectedIndex = box._Box_front;
            };


            if (BingoCell.isFirstGame)
            {
                cb(true);
            }
            else
            {
                GameHelper.GetVideo("reward_PickBox", isSuccess =>
            {
                if (isSuccess)
                {
                    cb(true);
                }
            });
            }
        }

        private void RefreshBoxDown()
        {
            ui.com_boxdown.pb_box.TweenValue(rewardCount, 0.5f);
            ui.com_boxdown.text_aNum.text = GameHelper.GetItemSum(LastReward.itemId, (decimal)lastRewardCount);
        }
    }
}