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

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

namespace FL.FGUI
{
    /// <summary>
    /// UI逻辑处理类
    /// </summary>
    /// <typeparam name=""></typeparam>
    public partial class DragonEggUpgradeCtrl : UIController<DragonEggUpgradeVM>
    {
        public enum eState
        {
            fillEnergy = 0,  // 填充能量状态
            fullEnergy = 1,  // 满能量可升阶状态
            upgradeStep = 2, // 升阶倒计时状态
            maxStep = 3, // 已满级
        }

        private const int maxQualityLv = 11;// 总共11个品质等级
        private EnergyTable _curInfo;  // 当前龙蛋等级信息
        private GLoader _costItemIcon;
        private GTextField _costNumLabel;
        private GTextField _watchAdNumLabel;
        private ITimer _stepTimer; // 升阶倒计时定时器

        protected override void OnEnable(object intent)
        {
            AddUIListenres();
            AddEventListeners();
            InitUI();
            ShowUI();
        }
        protected override void OnDisable()
        {
            if (_curInfo != null) _curInfo = null;
            RemoveUIListenres();
            RemoveEventListeners();
            ClearStepTimer();
        }
        #region UI事件
        private void AddUIListenres()
        {
            VM.GoldAddBtn.onClick.Add(OnClickGoldAddBtn);
            VM.PropAddBtn.onClick.Add(OnClickPropAddBtn);
            VM.UpgradeBtn.onClick.Add(OnClickUpgradeBtn);
            VM.BuyBtn.onClick.Add(OnClickBuyBtn);
            VM.AdBtn.onClick.Add(OnClickAdBtn);
            VM.SpeedBtn.onClick.Add(OnClickSpeedBtn);
            VM.CloseBtn.onClick.Add(OnClickCloseBtn);

        }
        private void RemoveUIListenres()
        {
            VM.GoldAddBtn.onClick.Remove(OnClickGoldAddBtn);
            VM.PropAddBtn.onClick.Remove(OnClickPropAddBtn);
            VM.UpgradeBtn.onClick.Remove(OnClickUpgradeBtn);
            VM.BuyBtn.onClick.Remove(OnClickBuyBtn);
            VM.AdBtn.onClick.Remove(OnClickAdBtn);
            VM.SpeedBtn.onClick.Remove(OnClickSpeedBtn);
            VM.CloseBtn.onClick.Remove(OnClickCloseBtn);

        }
        private void OnClickGoldAddBtn(EventContext context)
        {
        }
        private void OnClickPropAddBtn(EventContext context)
        {
        }
        private void OnClickUpgradeBtn(EventContext context)
        {
            DragonEggService.Instance.UpgradeDragonEgg(Context.Time.GetNowTime(), _curInfo.Time * 1000);
        }
        private void OnClickBuyBtn(EventContext context)
        {
            DragonEggService.Instance.FillDragonEggEnergy(_curInfo.Expend);
        }
        //观看广告减少升级时间按钮事件
        private void OnClickAdBtn(EventContext context)
        {
            DragonEggService.Instance.ReduceTimeByWatchAd(Context.Time.GetNowTime());
        }
        // 加速按钮，打开道具使用界面
        private void OnClickSpeedBtn(EventContext context)
        {
            var needTime = DragonEggData.Instance.UpgradeEndTime - Context.Time.GetNowTime();
            var args = new UseItemParam
            {
                id = DragonEggData.Instance.AccelerateId,
                showNum = DragonEggService.Instance.GetAccelerationCardNum(DragonEggData.Instance.AccelerateId, needTime, false),
                maxNum = DragonEggService.Instance.GetAccelerationCardNum(DragonEggData.Instance.AccelerateId, needTime),
                endTime = DragonEggData.Instance.UpgradeEndTime,
                onPromiseCallback = (int num) =>
                {
                    XGame.Log.Warn($"使用加速卡道具后回调函数,使用数量num:{num}");
                },
            };
            Context.UI.OpenAsync(UIKeys.CommonUseItem, args);
        }
        private void OnClickCloseBtn(EventContext context)
        {
            Context.ClosePanel();
        }

        #endregion

        private void AddEventListeners()
        {
            EventSingle.Instance.AddListener(EventDefine.UpdataItemData, UpdataItemData);
            EventSingle.Instance.AddListener(EventDefine.FillEnergy, FillEnergy);
            EventSingle.Instance.AddListener(EventDefine.UpgradeDragonEgg, UpgradeDragonEgg);
            EventSingle.Instance.AddListener(EventDefine.ReduceDragonEggTime, ReduceDragonEggTime);
            EventSingle.Instance.AddListener(EventDefine.UpgradeDragonEggSucess, UpgradeDragonEggSucess);
        }
        private void RemoveEventListeners()
        {
            EventSingle.Instance.RemoveListener(EventDefine.UpdataItemData, UpdataItemData);
            EventSingle.Instance.RemoveListener(EventDefine.FillEnergy, FillEnergy);
            EventSingle.Instance.RemoveListener(EventDefine.UpgradeDragonEgg, UpgradeDragonEgg);
            EventSingle.Instance.RemoveListener(EventDefine.ReduceDragonEggTime, ReduceDragonEggTime);
            EventSingle.Instance.RemoveListener(EventDefine.UpgradeDragonEggSucess, UpgradeDragonEggSucess);
        }

        private void InitUI()
        {
            VM.EggQualityList.ListType = EGListType.None;
            if (_costItemIcon == null)
            {
                _costItemIcon = VM.BuyBtn.GetChild("ItemIcon").asLoader;
            }
            if (_costNumLabel == null)
            {
                _costNumLabel = VM.BuyBtn.GetChild("NumLabel").asTextField;
            }
            if (_watchAdNumLabel == null)
            {
                _watchAdNumLabel = VM.AdBtn.GetChild("NumLabel").asTextField;
            }
        }

        private void ShowUI()
        {
            _curInfo = EnergyTableRepo.Get(DragonEggData.Instance.EggLv);
            EnergyTable nextInfo = EnergyTableRepo.Get(DragonEggData.Instance.EggLv + 1);
            ShowEggQualityUI(nextInfo);
            ShowUpgradeUI(nextInfo);
        }

        /// <summary>
        /// 道具变化
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="args"></param>
        private void UpdataItemData(int eventId, object args)
        {

        }

        // 是否未解锁的品质
        private bool IsLockQuality(int quality)
        {
            int globalId = DragonEggData.Instance.GetUnlockQuality(quality);
            bool bLock = globalId > 0;
            if (bLock)
            {// 获取全局表的具体解锁条件来判断是否已解锁
                //已达解锁条件，移除
                if (!bLock)
                {
                    DragonEggData.Instance.RemoveUnlockQualityDic(quality);
                }
            }
            return bLock;
        }

        /// <summary>
        /// 龙蛋品质概率UI
        /// </summary>
        private void ShowEggQualityUI(EnergyTable nextInfo)
        {
            bool bMax = nextInfo == null;
            int index = 0;
            var dataList = new List<EggQualityItemData>();
            for (int i = 0; i < maxQualityLv; i++)
            {
                index = (i + 1) * 2 - 1;
                dataList.Add(new EggQualityItemData
                {
                    quality = i + 1,
                    curVal = _curInfo.Pro_quality[index],
                    nextVal = bMax ? 0 : nextInfo.Pro_quality[index],
                    bMaxLv = bMax,
                    bLock = IsLockQuality(i + 1),
                });
            }
            RefreshEggQualityList(dataList);
        }
        private void RefreshEggQualityList(List<EggQualityItemData> dataList)
        {
            VM.EggQualityList.BindDatas(dataList);
        }

        /// <summary>
        /// 升级龙蛋UI
        /// </summary>
        private void ShowUpgradeUI(EnergyTable nextInfo)
        {
            bool bMaxLv = nextInfo == null;
            if (bMaxLv)
            {
                VM.State.selectedIndex = (int)eState.maxStep;
                VM.MaxLv.text = string.Format(string.Format(StringDefine.dragonEggCurLv, $"{_curInfo.Id}(MAX)"));
            }
            else
            {
                ShowLvUI(_curInfo.Id, nextInfo.Id);
                if (DragonEggData.Instance.UpgradeEndTime > 0)
                {
                    ShowUpgradeState(eState.upgradeStep);
                }
                else
                {
                    VM.EggEnergyBar.max = _curInfo.Expend.Length / 2;
                    ShowEggEnergyBar(DragonEggData.Instance.EggEnergy);
                }
            }
        }

        /// <summary>
        /// 填充龙蛋能量槽事件
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="args"></param>
        private void FillEnergy(int eventId, object args)
        {
            ShowEggEnergyBar(DragonEggData.Instance.EggEnergy);
        }

        private void ShowEggEnergyBar(int energy)
        {
            VM.EggEnergyBar.value = energy;
            ShowUpgradeState(energy == VM.EggEnergyBar.max ? eState.fullEnergy : eState.fillEnergy);
        }

        /// <summary>
        /// 龙蛋升级状态
        /// </summary>
        /// <param name="state"></param>
        private void ShowUpgradeState(eState state)
        {
            VM.State.selectedIndex = (int)state;
            if (state == eState.fillEnergy)
            {
                ShowEggEnergyCostUI();
            }
            else if (state == eState.upgradeStep)
            {
                ShowUpgradeStepUI();
            }
        }

        private void ShowLvUI(int curLv, int nextLv)
        {
            VM.CurLv.text = string.Format(StringDefine.dragonEggCurLv, curLv);
            VM.NextLv.text = string.Format(StringDefine.dragonEggCurLv, nextLv);
        }

        /// <summary>
        /// 填充能量消耗
        /// </summary>
        private void ShowEggEnergyCostUI()
        {
            if (_curInfo != null)
            {
                int index = DragonEggData.Instance.EggEnergy * 2;
                int itemId = _curInfo.Expend[index];
                var itemInfo = ItemTableRepo.Get(itemId);
                _costItemIcon.icon = itemInfo.Icon;
                long needCount = _curInfo.Expend[index + 1];
                long count = ItemData.Instance.GetItemNum(itemId);
                _costNumLabel.text = needCount.ToString();
                _costNumLabel.color = count < needCount ? Color.red : Color.white;
            }
        }

        /// <summary>
        /// 龙蛋升级中(倒计时状态)
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="args"></param>
        private void UpgradeDragonEgg(int eventId, object args)
        {
            ShowUpgradeState(eState.upgradeStep);
        }

        private void ShowUpgradeStepUI()
        {
            ShowAdBtnUI();
            ShowLeftStepTime();
            if (_stepTimer == null)
            {
                _stepTimer = Context.Time.AddLooperTimer(500, (int dt) =>
                {
                    ShowLeftStepTime();
                });
            }
        }
        /// <summary>
        /// 龙蛋升阶倒计时
        /// </summary>
        private void ShowLeftStepTime()
        {
            long leftTime = DragonEggData.Instance.UpgradeEndTime - Context.Time.GetNowTime();
            if (leftTime > 0)
            {
                TimeSpan timeData = TimeSpan.FromMilliseconds(leftTime);
                VM.NeedTimeLabel.text = timeData.ToString(@"hh\:mm\:ss");
            }
            else
            {
                ClearStepTimer();
            }
        }

        private void ClearStepTimer()
        {
            if (_stepTimer != null)
            {
                _stepTimer.Cancel();
                _stepTimer = null;
            }
        }

        /// <summary>
        /// 观看广告按钮ui
        /// </summary>
        private void ShowAdBtnUI()
        {
            _watchAdNumLabel.text = $"{DragonEggData.Instance.WatchAdCount}/{DragonEggData.Instance.MaxWatchAdCount}";
            VM.AdBtn.enabled = DragonEggData.Instance.WatchAdCount > 0;
        }

        /// <summary>
        /// 减少龙蛋升级时间
        /// </summary>
        private void ReduceDragonEggTime(int eventId, object args)
        {
            ShowAdBtnUI();
            ShowLeftStepTime();
        }

        /// <summary>
        /// 龙蛋升级成功
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="args"></param>
        private void UpgradeDragonEggSucess(int eventId, object args)
        {
            ClearStepTimer();
            ShowUI();
        }


    }
}