
using System;
using System.Collections.Generic;
using DG.Tweening;
using FGUI.A000_common;
using UnityEngine;
using FairyGUI;
using FGUI.G020_PrizeWheel;
using Spine.Unity;
using Random = UnityEngine.Random;

namespace ScrewsMaster
{
    public class PrizeWheelUI : BaseUI
    {

        private const string GreenStr = "<font color='#b7e25a' size='46'></font>";
        private const string RedStr = "<font color='#fb8a87' size='46'></font>";
        private const string RemainingCountTextStr = "Left Spin Times: ";
        private PrizeWheelUICtrl ctrl;
        private PrizeWheelModel model;
        private PrizeWheelPanel ui;

        private SkeletonAnimation prizeWheelAnim;
        private Action closeCallback;

        private List<PrizeWheelData> _prizeWheelDataList;
        private int[] _wheelTimes;

        private List<SpinWheelRewardItem> _spinWheelRewardItems;

        private int _rewardIndex = 0;
        private long _cooldown;
        private bool _inCooldown;
        private bool _canUse;
        private bool _inAnim;

        private AudioSource _audioSource;

        private GTextField _goldNumText;

        public PrizeWheelUI(PrizeWheelUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.PrizeWheelUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "G020_PrizeWheel";
            uiInfo.assetName = "PrizeWheelPanel";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

        #region 生命周期
        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.PrizeWheelModel) as PrizeWheelModel;
        }

        protected override void OnClose()
        {
            HallManager.Instance.UpdateSecondEvent -= UpdateData;

            if (_audioSource != null && _audioSource.isPlaying)
            {
                _audioSource.Stop();
            }
        }

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

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {
                ui.TopBox.y += Screen.safeArea.y;
            }

            DateTime dateTime1 = DateTimeOffset.FromUnixTimeSeconds(GameHelper.GetNowTime()).LocalDateTime;
            DateTime dateTime2 = DateTimeOffset.FromUnixTimeSeconds(PreferencesMgr.Instance.PrizeWheelTime).LocalDateTime;

            bool isSameDay = dateTime1.Date == dateTime2.Date;
            if (!isSameDay)
            {
                PreferencesMgr.Instance.PrizeWheelTime = 0;
                PreferencesMgr.Instance.PrizeWheelCount = 0;
            }

            var commonModel = ConfigSystem.GetConfig<CommonModel>();
            _wheelTimes = commonModel.wheelTimes;
            InitAllPrizeWheelData();
            InitView();

        }

        protected override void OnOpen(object args)
        {
            ui.Open.Play(() =>
            {
                prizeWheelAnim.SetActive(true);
            });
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }
        #endregion

        #region 消息
        protected override void AddListener()
        {

        }
        protected override void RemoveListener()
        {

        }
        #endregion

        //初始化页面逻辑
        private void InitView()
        {
            ui.StartSpinBtn.CountdownText.visible = false;
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) ui.StartSpinBtn.img_saveingpot.visible = true;
            else ui.StartSpinBtn.img_saveingpot.visible = false;
            _goldNumText = ui.gold.GetChild("number_text") as GTextField;

            prizeWheelAnim = FXManager.Instance.SetFx<SkeletonAnimation>(ui.PrizeWheelAnimParent, Fx_Type.fx_prize_wheel, ref closeCallback);
            prizeWheelAnim.state.SetAnimation(0, "daiji", true);
            prizeWheelAnim.SetActive(false);

            _goldNumText.text = GameHelper.GetGoldNumber().ToString();

            InitButtons();
            InitPrizeWheelList();

            HallManager.Instance.UpdateSecondEvent += UpdateData;
            UpdateView();
        }

        private void UpdateData()
        {
            if (_inAnim)
                return;

            _cooldown = GameHelper.GetNowTime() - PreferencesMgr.Instance.PrizeWheelTime;
            _canUse = PreferencesMgr.Instance.PrizeWheelCount < _wheelTimes[0];
            _inCooldown = _cooldown < _wheelTimes[1];

            if (_inCooldown)
            {
                TimeSpan timeSpan = TimeSpan.FromSeconds(_wheelTimes[1] - _cooldown);

                // 格式化为 "hh:mm:ss" 的字符串
                string formattedTime = string.Format("{0:D2}:{1:D2}:{2:D2}",
                    timeSpan.Hours,
                    timeSpan.Minutes,
                    timeSpan.Seconds);
                ui.StartSpinBtn.CountdownText.text = formattedTime;
            }

            ui.StartSpinBtn.grayed = _inCooldown || !_canUse;
            ui.StartSpinBtn.CountdownText.visible = _inCooldown && _canUse;
            ui.StartSpinBtn.BtnTitleBox.visible = !ui.StartSpinBtn.CountdownText.visible;
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && !ui.StartSpinBtn.grayed) ui.StartSpinBtn.img_saveingpot.visible = true;
            else ui.StartSpinBtn.img_saveingpot.visible = false;
        }

        private void UpdateView()
        {
            UpdateRemainingCountText();
            UpdateData();
            ui.StartSpinBtn.grayed = _inCooldown || !_canUse;
            ui.StartSpinBtn.CountdownText.visible = _inCooldown;
            ui.StartSpinBtn.touchable = true;
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && !ui.StartSpinBtn.grayed) ui.StartSpinBtn.img_saveingpot.visible = true;
            else ui.StartSpinBtn.img_saveingpot.visible = false;
        }

        private void UpdateRemainingCountText()
        {
            var canUse = PreferencesMgr.Instance.PrizeWheelCount < _wheelTimes[0];
            var color = canUse ? "#b7e25a" : "#fb8a87";
            // ui.RemainingCountText.text =
            //     $"{RemainingCountTextStr} <font color='{color}' size='46'>{PreferencesMgr.Instance.PrizeWheelCount}</font> " +
            //     $"/ <font color='{color}' size='46'>{_wheelTimes[0]}</font>";
            ui.RemainingCountText.text =
                $"{RemainingCountTextStr}" +
                $"<font color='#b7e25a' size='46'>{PreferencesMgr.Instance.PrizeWheelCount}</font>" +
                $"/<font color='#fb8a87' size='46'>{_wheelTimes[0]}</font>";
        }

        private void InitPrizeWheelList()
        {
            _spinWheelRewardItems = new List<SpinWheelRewardItem>(8);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_1);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_2);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_3);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_4);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_5);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_6);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_7);
            _spinWheelRewardItems.Add(ui.PrizeWheel.item_8);


            for (int i = 0; i < _spinWheelRewardItems.Count; i++)
            {
                var data = _prizeWheelDataList[i];
                _spinWheelRewardItems[i].num.text = Mathf.CeilToInt(data.quantity).ToString();
            }
        }

        private void PlayPrizeWheelAnim()
        {
            prizeWheelAnim.state.SetAnimation(0, "zhuandong", true);
            ui.PrizeWheel.rotation = 0;
            _audioSource = AudioManager.Instance.PlayDynamicEffect(AudioConst.PlayPrizeWheelAnim);
            ui.PrizeWheel.TweenRotate(-360 * 10 + _rewardIndex * -45, 6.8f).SetEase(EaseType.QuadInOut).OnComplete(() =>
            {
                _inAnim = false;
                prizeWheelAnim.state.AddAnimation(0, "zhongjiang", false, 0f);
                prizeWheelAnim.state.AddAnimation(0, "daiji", true, 0f);
                DispatchReward();
                UpdateView();
            });
        }

        private int CalRewardResult()
        {
            var sum = 0;
            for (int i = 0; i < _prizeWheelDataList.Count; i++)
            {
                var data = _prizeWheelDataList[i];
                sum += data.weight;
            }

            var random = Random.Range(0, sum + 1);

            sum = 0;
            for (int i = 0; i < _prizeWheelDataList.Count; i++)
            {
                var data = _prizeWheelDataList[i];
                sum += data.weight;
                if (random <= sum)
                {
                    return i;
                }
            }

            return 0;
        }

        private void DispatchReward()
        {
            PreferencesMgr.Instance.PrizeWheelCount += 1;
            PreferencesMgr.Instance.PrizeWheelTime = GameHelper.GetNowTime();

            var startPos = GameHelper.GetUICenterPosition(_spinWheelRewardItems[_rewardIndex]);
            var data = _prizeWheelDataList[_rewardIndex];

            var curGoldNum = GameHelper.GetGoldNumber();
            var rewardModel = new RewardData();
            var rewardData = new RewardSingleData(data.wheel_item, Mathf.CeilToInt(data.quantity), RewardOrigin.PrizeWheel)
            {
                startPosition = startPos,
                endPosition = GameHelper.GetUICenterPosition(ui.gold),

            };
            rewardModel.AddReward(rewardData);

            rewardModel.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;

            // if (vo.is_double) rewardModel.condition = RewardCondition.None;
            rewardModel.AddCompleted(isSuccess =>
            {
                if (isSuccess)
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.DailyBonusCollect);

                    DOVirtual.Float(curGoldNum, GameHelper.GetGoldNumber(), 1f,
                        value => { _goldNumText.text = ((int)value).ToString(); });//金币变化动画
                }
                else
                {
                    // GameHelper.ShowTips("Not time to check in yet");

                }
            });

            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardModel);
        }


        private void InitButtons()
        {
            ui.CloseBtn.SetClick(OnClickCloseBtn);
            ui.StartSpinBtn.SetClick(OnClickStartSpinBtn);
        }

        private void OnClickCloseBtn()
        {

            prizeWheelAnim.SetActive(false);
            ui.Close.Play(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrizeWheelUI_Close);
            });
        }

        private void OnClickStartSpinBtn()
        {
            if (!_canUse)
            {
                GameHelper.ShowTips("Today's quota is exhausted.");
                return;
            }
            if (_inCooldown)
            {
                _cooldown = GameHelper.GetNowTime() - PreferencesMgr.Instance.PrizeWheelTime;
                GameHelper.ShowTips($"In cooldown, {_wheelTimes[1] - _cooldown} seconds left.");
                return;
            }
            ui.StartSpinBtn.grayed = true;
            ui.StartSpinBtn.touchable = false;
            ui.StartSpinBtn.img_saveingpot.visible = false;
            GameHelper.ShowVideoAd("reward_lobby", isSuccess =>
            {
                if (isSuccess)
                {
                    _inAnim = true;
                    _rewardIndex = CalRewardResult();
                    PlayPrizeWheelAnim();
                }
                else
                {
                    ui.StartSpinBtn.grayed = false;
                    ui.StartSpinBtn.touchable = true;
                    if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) ui.StartSpinBtn.img_saveingpot.visible = true;
                    else ui.StartSpinBtn.img_saveingpot.visible = false;
                }
            });
        }


        public void InitAllPrizeWheelData()
        {
            var prizeWheelDataModel = ConfigSystem.GetConfig<PrizeWheelDataModel>();
            _prizeWheelDataList = prizeWheelDataModel.dataList;
        }
    }
}