/// #pkgName FGUI包名
/// #panelName UIPanel名字
/// #UIName = $"{#pkgName}{#panelName}" UIKey名字
/// 该脚本由模板创建
/// created by cb 2024


using FairyGUI;
using FL.Data;
using Spine.Unity;
using System.Collections.Generic;
using UnityEngine;
using XGame.Database;
using XGame.Framework.FGUI;
using XGame.Framework.Time;
using XGame.Framework.UI;

namespace FL.FGUI
{
    /// <summary>
    /// UI逻辑处理类
    /// </summary>
    /// <typeparam name=""></typeparam>
    public partial class DragonEggBoxCtrl : UIController<DragonEggBoxVM>
    {
        private int _addSocre;// 选择的品质龙蛋增加的积分;
        private ITimer _autoTimer;// 自动定时器
        private ITimer _openBoxTimer;
        private Vector3 _startPos;
        private Vector3 _endPos;
        private Vector3 _scoreEndPos;
        private HashSet<DragonEggFlyIconView> _flyingList;
        private List<GButton> _dragonBtnList;
        private Dictionary<EAttributeType, string> _attributeDescMap;
        private const int _costDragonEggNum = 10; // 每次消耗的龙蛋数量

        protected override void OnEnable(object intent)
        {
            AddUIListenres();
            VM.MenusBtnCtrl.onChanged.Add(OnMenusBtnCtrlChange);
            EventSingle.Instance.AddListener(EventDefine.AttributeChange, OnChangeAttribute); // 角色属性变化
            Init();
        }
        protected override void OnDisable()
        {
            RemoveUIListenres();
            ClearAutoTimer();
            ClearOpenTimer();
            EventSingle.Instance.RemoveListener(EventDefine.AttributeChange, OnChangeAttribute); // 角色属性变化
            VM.MenusBtnCtrl.onChanged.Remove(OnMenusBtnCtrlChange);
            if (_flyingList != null)
            {
                foreach (var flying in _flyingList)
                {
                    Context.Asset.Recycle(flying);
                }
                _flyingList.Clear();
                _flyingList = null;
            }
            if (_attributeDescMap != null)
            {
                _attributeDescMap.Clear();
                _attributeDescMap = null;
            }
            if (_dragonBtnList != null)
            {
                _dragonBtnList.Clear();
                _dragonBtnList = null;
            }
            VM.DragonSpine.url = string.Empty;
        }
        #region UI事件
        private void AddUIListenres()
        {
            VM.AutoBtn.onClick.Add(OnClickAutoBtn);
            VM.NextBtn.onClick.Add(OnClickNextBtn);
            VM.LastBtn.onClick.Add(OnClickLastBtn);
            VM.BagBtn.onClick.Add(OnClickBagBtn);
            VM.BoxAwardBtn.onClick.Add(OnClickBoxAwardBtn);
            VM.DragonSpineBtn.onClick.Add(OnclickDragonSpineBtn);
        }
        private void RemoveUIListenres()
        {
            VM.AutoBtn.onClick.Remove(OnClickAutoBtn);
            VM.NextBtn.onClick.Remove(OnClickNextBtn);
            VM.LastBtn.onClick.Remove(OnClickLastBtn);
            VM.BagBtn.onClick.Remove(OnClickBagBtn);
            VM.BoxAwardBtn.onClick.Remove(OnClickBoxAwardBtn);
            VM.DragonSpineBtn.onClick.Remove(OnclickDragonSpineBtn);

        }
        private void OnClickAutoBtn(EventContext context)
        {
            if (_autoTimer == null)
            {
                if (IsEmptyBox())
                {
                    return;
                }
                OpenDragonEggBoxAni(true);
                _autoTimer = Context.Time.AddLooperTimer(500, (int dt) =>
                {
                    if (IsEmptyBox(false))
                    {
                        ClearAutoTimer(true);
                        return;
                    }
                    PlayDropAni();
                });
            }
            else
            {
                ClearAutoTimer(true);
            }
        }
        private void OnClickNextBtn(EventContext context)
        {
            OnSelectDragon(VM.MenusBtnCtrl.selectedIndex + 1);
        }
        private void OnClickLastBtn(EventContext context)
        {
            OnSelectDragon(VM.MenusBtnCtrl.selectedIndex - 1);
        }

        /// <summary>
        /// 点击背包按钮
        /// </summary>
        /// <param name="context"></param>
        private void OnClickBagBtn(EventContext context)
        {
            XGame.Log.Debug("打开背包");
            // 测试装备掉落
            DragonEggService.Instance.MakeEquip();
        }

        /// <summary>
        /// 积分进度条满值可领取对应的宝箱奖励
        /// </summary>
        /// <param name="context"></param>
        private void OnClickBoxAwardBtn(EventContext context)
        {
            OnChangeDrangonEggScore();
        }

        private void OnclickDragonSpineBtn(EventContext context)
        {
            ClearAutoTimer(true);
            if (IsEmptyBox()) return;
            OpenDragonEggBoxAni(false);
            PlayDropAni();
        }
        #endregion


        private void Init()
        {
            _startPos = VM.DragonSpineBtn.displayObject.LocalToWorld(new Vector3(VM.DragonSpineBtn.width / 3, VM.DragonSpineBtn.height / 2, 0));
            _endPos = VM.BagBtn.displayObject.LocalToWorld(new Vector3(VM.BagBtn.width / 10, VM.BagBtn.height / 8, 0));
            _scoreEndPos = VM.EggPointBar.displayObject.LocalToWorld(new Vector3(VM.EggPointBar.width / 2, VM.EggPointBar.height / 2, 0));
            InitDrangonBoxUI();
            InitAttributeDescMap();
            ShowAttributeUI();
            ShowDragonEggScoreUI(0);
        }
        /// <summary>
        /// 加载龙的spine
        /// </summary>
        /// <param name="spineName"></param>
        private void LoadDragonSpine(string spineName)
        {
            VM.DragonSpine.LoadSpine(spineName, "box_idle", true);
        }

        /// <summary>
        /// 龙蛋积分变化
        /// </summary>
        /// <param name="addScore"></param>
        /// <param name="bTweenValue"></param>
        private void ShowDragonEggScoreUI(int addScore, bool bTweenValue = false)
        {
            if (addScore != 0) DragonEggData.Instance.DragonEggSocre += addScore;
            VM.EggPointBar.max = DragonEggData.Instance.MaxDragonEggSocre;
            if (bTweenValue)
                VM.EggPointBar.TweenValue(DragonEggData.Instance.DragonEggSocre, 0.5f);
            else
                VM.EggPointBar.value = DragonEggData.Instance.DragonEggSocre;
            OnchangeAwardState(DragonEggData.Instance.DragonEggSocre >= DragonEggData.Instance.MaxDragonEggSocre);
        }
        private void InitDrangonBoxUI()
        {
            if (_dragonBtnList == null) _dragonBtnList = new List<GButton>() { VM.DragonBtn1, VM.DragonBtn2, VM.DragonBtn3, VM.DragonBtn4, VM.DragonBtn5 };

            int index = -1;
            for (int i = 0; i < 5; i++)
            {
                int num = DragonEggData.Instance.GetDragonEgg((EQualityLevel)i);
                ShowDragonBoxNum(i, num);
                if (num > 0 && index == -1) index = i;
            }
            OnSelectDragon(index == -1 ? 0 : index);
        }

        /// <summary>
        /// 判断龙裔宝卵数量是否
        /// </summary>
        /// <returns></returns>
        private bool IsEmptyBox(bool bShowTip = true)
        {
            var quality = (EQualityLevel)VM.MenusBtnCtrl.selectedIndex;
            var boxNum = DragonEggData.Instance.GetDragonEgg(quality);
            if (boxNum == 0)
            {
                if (bShowTip)
                {
                    EventSingle.Instance.Notify(EventDefine.ShowTips, StringDefine.dragonEggsEmpty);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 龙蛋品质宝箱数量
        /// </summary>
        /// <param name="index"></param>
        /// <param name="num"></param>
        private void ShowDragonBoxNum(int index, int num)
        {
            if (_dragonBtnList[index]?.title != null) _dragonBtnList[index].title = $"X{num}";
        }

        private void ShowFlyIconView(int i, bool bScore)
        {
            var flyParam = new FlyingIconParam()
            {
                iconName = i < 6 ? $"itemicon_{i + 1}" : $"itemicon_{99}",
                startPos = _startPos,
                bScore = bScore,
                endPos = _endPos,
            };

            if (_flyingList == null) _flyingList = new HashSet<DragonEggFlyIconView>();

            var loadAsync = Context.Asset.LoadFguiNested(UINestedKeys.DragonEggFlyIcon, VM.DragonSpineBtn);
            loadAsync.On(_ =>
            {
                var flyView = loadAsync.Result as DragonEggFlyIconView;
                if (flyView != null)
                {
                    flyParam.callback = (bScore) =>
                    {
                        FlyingCallback(flyView, bScore);
                    };
                    flyView.Ctrl.ShowUI(flyParam);
                    _flyingList.Add(flyView);
                }
            });
        }

        private void FlyingCallback(DragonEggFlyIconView flyView, bool bScore)
        {
            _flyingList.Remove(flyView);
            Context.Asset.Recycle(flyView);
            if (_flyingList.Count == 0) OnchangBagState(false);
            if (bScore)
            {
                ShowDragonEggScoreUI(_addSocre, true);
            }
        }
        private void OnchangBagState(bool bOpen)
        {
            VM.BagBtn.GetController("State").selectedIndex = bOpen ? 1 : 0;
        }

        /// <summary>
        /// 开龙蛋宝箱的掉落动画
        /// </summary>
        private void PlayDropAni()
        {
            var quality = (EQualityLevel)VM.MenusBtnCtrl.selectedIndex;
            var boxNum = DragonEggData.Instance.GetDragonEgg(quality);
            int num = boxNum < _costDragonEggNum ? boxNum : _costDragonEggNum;
            DragonEggService.Instance.OnchangeDragonEgg(quality, -num);
            ShowDragonBoxNum((int)quality, DragonEggData.Instance.GetDragonEgg(quality));

            _addSocre = (VM.MenusBtnCtrl.selectedIndex + 1) * num;
            OnchangBagState(true);
            //ShowFlyIconView(0, true);
            for (int i = 0; i < num; i++)
            {
                ShowFlyIconView(i, i == num - 1);
            }
        }

        /// <summary>
        /// 宝箱按钮领取状态
        /// </summary>
        /// <param name="bGray"></param>
        private void OnchangeAwardState(bool bAward)
        {
            VM.AwardState.selectedIndex = bAward ? 1 : 0;
        }

        private void OnSelectDragon(int index)
        {
            VM.MenusBtnCtrl.selectedIndex = index;
            ShowSelectDragonUI();
        }

        /// <summary>
        /// 当前选中的龙蛋
        /// </summary>
        private void ShowSelectDragonUI()
        {
            ClearAutoTimer(true);
            int selectedIndex = VM.MenusBtnCtrl.selectedIndex;
            ShowDragonName(selectedIndex);
            // 获取龙的spine

            LoadDragonSpine("box_skeletondata");
        }

        /// <summary>
        /// 龙蛋按钮菜单栏变化
        /// </summary>
        /// <param name="context"></param>
        private void OnMenusBtnCtrlChange(EventContext context)
        {
            ShowSelectDragonUI();
        }
        private void ShowDragonName(int selectedIndex)
        {
            VM.LastBtn.visible = selectedIndex != 0;
            VM.NextBtn.visible = selectedIndex != 4;
            VM.DragonLabel.text = $"品质{selectedIndex + 1}钻石龙";
            VM.DragonLabel.color = ColorDefine.ToEquipNameColor((EQualityLevel)(selectedIndex + 1));
        }

        /// <summary>
        /// 领取龙蛋积分宝箱后龙蛋进度条积分变化
        /// </summary>
        private void OnChangeDrangonEggScore()
        {
            int addSocre = -DragonEggData.Instance.MaxDragonEggSocre;
            DragonEggData.Instance.MaxDragonEggSocre += 10;
            ShowDragonEggScoreUI(addSocre);
        }

        private void InitAttributeDescMap()
        {
            if (_attributeDescMap == null)
            {
                _attributeDescMap = new Dictionary<EAttributeType, string>()
                {
                    {EAttributeType.Atk, GetAttributeDesc(EAttributeType.Atk)},
                    {EAttributeType.Hp, GetAttributeDesc(EAttributeType.Hp)},
                    {EAttributeType.Def, GetAttributeDesc(EAttributeType.Def)}
                };
            }
        }
        private string GetAttributeDesc(EAttributeType attrType)
        {
            var attrInfo = AttrDescTableRepo.Get((int)attrType);
            return attrInfo?.ShowName ?? string.Empty;
        }
        /// <summary>
        /// 显示角色属性UI(攻击|生命|防御)
        /// </summary>
        private void ShowAttributeUI()
        {
            ShowAtrributeVal(VM.AttackLabel, EAttributeType.Atk);
            ShowAtrributeVal(VM.HpLabel, EAttributeType.Hp);
            ShowAtrributeVal(VM.DefenseLabel, EAttributeType.Def);
        }
        private void ShowAtrributeVal(GTextField attrLabel, EAttributeType attrType)
        {
            attrLabel.text = $"{_attributeDescMap[attrType]}:{PlayerData.Instance.Attr.GetValue(attrType)}";
        }

        /// <summary>
        /// 角色属性变化
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="args"></param>
        private void OnChangeAttribute(int eventId, object args)
        {
            EAttributeType attrType = (EAttributeType)args;
            if (attrType == EAttributeType.Atk)
            {
                ShowAtrributeVal(VM.AttackLabel, EAttributeType.Atk);
            }
            else if (attrType == EAttributeType.Hp)
            {
                ShowAtrributeVal(VM.HpLabel, EAttributeType.Hp);
            }
            else if (attrType == EAttributeType.Def)
            {
                ShowAtrributeVal(VM.DefenseLabel, EAttributeType.Def);
            }
        }

        /// <summary>
        /// 龙蛋开箱动画
        /// </summary>
        private void OpenDragonEggBoxAni(bool bLoop)
        {
            if (VM.DragonSpine.Play("box_open", bLoop))
            {
                if (!bLoop)
                {
                    ClearOpenTimer();
                    _openBoxTimer = Context.Time.AddDelayTimer(VM.DragonSpine.spineAnimation.GetDurationMS(), () =>
                    {
                        VM.DragonSpine.Play("box_idle", true);
                    });
                }
            }
        }

        private void ClearOpenTimer()
        {
            if (_openBoxTimer != null)
            {
                _openBoxTimer.Cancel();
                _openBoxTimer = null;
            }
        }

        private void ClearAutoTimer(bool bResetIdle = false)
        {
            if (_autoTimer != null)
            {
                if (bResetIdle)
                {
                    VM.DragonSpine.Play("box_idle", true);
                }
                _autoTimer.Cancel();
                _autoTimer = null;
            }
        }
    }

}