// using FGUI.A000_common;

using System;
using System.Collections.Generic;
using DG.Tweening;
using FairyGUI;
using FGUI.Common_01;
using FGUI.Turntable_11;
using Spine.Unity;
using UnityEngine;

namespace ChillConnect
{
    public class WheelViewUI : BaseUI
    {
        private WheelViewUICtrl ctrl;
        private WheelViewModel model;
        private readonly int[] vidieWeight = new int[8];
        private TurntableModel turntableData;

        private List<com_coin> ItemList = new();
        private bool isClickSpin;
        private bool isClickAbleWatchAD = true;

        private SkeletonAnimation normalAnim;
        // private SkeletonAnimation turnAnim;
        // private SkeletonAnimation awardAnim;
        private Action closeCallback;


        private FGUI.Turntable_11.com_wheel ui;

        public WheelViewUI(WheelViewUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.WheelViewUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期
        protected override void OnInit()
        {
            model = moduleManager.GetModel(ModelConst.WheelViewModel) as WheelViewModel;

        }

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

            GameHelper.showGameUI = true;
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.Turntable_11.com_wheel;
        }

        protected override void OnOpenBefore(object args)
        {

            LoadLastCheckDate();

            CheckNewDay();


            var disc = ui.disc;
            ItemList.Add(disc.award1);
            ItemList.Add(disc.award2);
            ItemList.Add(disc.award3);
            ItemList.Add(disc.award4);
            ItemList.Add(disc.award5);
            ItemList.Add(disc.award6);
            ItemList.Add(disc.award7);
            ItemList.Add(disc.award8);

            HallManager.Instance.UpdateSecondEvent += UpdateTime;

            turntableData = ConfigSystem.GetConfig<TurntableModel>();


            normalAnim = FXManager.Instance.SetFx<SkeletonAnimation>(ui.light_parent, Fx_Type.fx_wheel, ref closeCallback);

            UpdateTime();

            refreshData();

            InitView();

        }
        private DateTime _lastCheckDate;
        private const string PlayerPrefsKeyLastCheckDate = "Wheel_new_days";
        private void LoadLastCheckDate()
        {
            string lastCheckDateString = PlayerPrefs.GetString(PlayerPrefsKeyLastCheckDate, "");
            if (!string.IsNullOrEmpty(lastCheckDateString))
            {
                _lastCheckDate = DateTime.ParseExact(lastCheckDateString, "yyyy-MM-dd", null);
            }
            else
            {
                // 如果没有找到日期，初始化为今天的日期
                _lastCheckDate = DateTime.Today;
                SaveLastCheckDate();
            }
        }

        private void SaveLastCheckDate()
        {
            // 将日期转换为字符串并存储到PlayerPrefs
            PlayerPrefs.SetString(PlayerPrefsKeyLastCheckDate, _lastCheckDate.ToString("yyyy-MM-dd"));
            PlayerPrefs.Save();
        }
        private void CheckNewDay()
        {
            DateTime currentDate = DateTime.Today;

            // 如果当前日期与上次检查的日期不同，说明是新的一天
            if (_lastCheckDate != currentDate)
            {
                // 重置 ThisDayWatchSlyderVideoNum
                DataMgr.ThisDayWatchSlyderVideoNum.Value = 0;

                // 更新最后检查的日期并保存到PlayerPrefs
                _lastCheckDate = currentDate;

                SaveLastCheckDate();
            }
        }

        //初始化页面逻辑
        private void InitView()
        {

            normalAnim.state.SetAnimation(0, "daiji", true);
            for (var i = 0; i < ItemList.Count; i++)
            {
                vidieWeight[i] = turntableData.DataList[i].weight;
            }
            ui.disc.rotation = 0;
            ui.btn_spin.SetClick(SpineAnim);
            ui.close.SetClick(() =>
            {
                CtrlCloseUI();
            });
        }


        private void refreshData()
        {

            for (int i = 0; i < ItemList.Count; i++)
            {
                var item = ItemList[i];
                var turntable = turntableData.DataList[i];
                var id = turntable.wheel_item;
                var quantity = turntable.quantity;

                if (!GameHelper.IsGiftSwitch() && id == 102)
                {
                    id = 101;
                    quantity *= 10;
                }

                item.text_num.text = id == 102 ? GameHelper.Get102Str((decimal)quantity) : GameHelper.Get101Str((decimal)quantity);
                item.status.selectedIndex = id == 102 ? com_coin.Status_b : com_coin.Status_a;
            }


            var times = DataMgr.ThisDayWatchSlyderVideoNum.Value;
            var limits = GameHelper.GetCommonModel().wheelTimes[0];
            // ui.spin.text_spintimes.SetVar("times", times.ToString()).FlushVars();
            // ui.spin.text_spintimes.SetVar("limits", limits.ToString()).FlushVars();

            ui.text_spintimes.SetVar("times", times.ToString()).FlushVars();
            ui.text_spintimes.SetVar("limits", limits.ToString()).FlushVars();

        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

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

        #region 消息
        protected override void AddListener()
        {

        }
        protected override void RemoveListener()
        {

        }
        #endregion


        private Tween ResultTween;
        private float turnTime = 7.0f;


        private void SpineAnim()
        {
            if (isClickSpin)
                return;

            if (GameHelper.GetNowTime() < DataMgr.NextOpenWheelStampTime.Value) return;

            if (isClickAbleWatchAD)
            {
                isClickAbleWatchAD = false;

                GameHelper.ShowVideoAd("reward_luckySpin", isSuccess =>
                {
                    if (isSuccess)
                    {
                        Spin();
                    }

                    isClickAbleWatchAD = true;
                });
            }
        }

        private void Spin()
        {
            // normalAnim.SetActive(false);
            ui.disc.rotation = 0;
            normalAnim.state.SetAnimation(0, "zhuandong", true);
            isClickSpin = true;
            ui.close.touchable = false;
            ui.close.grayed = false;

            ui.btn_spin.touchable = false;

            var index = CommonHelper.GetIndexByChanceList(vidieWeight);
            var data = turntableData.DataList[index];
            var angle = 3600 - (data.Seq - 1) * 45;
            AudioManager.Instance.PlayDynamicEffect(AudioConst.wheel_spin);
            DOTween.To(() => ui.disc.rotation, e => ui.disc.rotation = e, angle, turnTime)
              .SetEase(Ease.OutQuad);

            ResultTween = DOVirtual.DelayedCall(turnTime, () => ReceivePlane(data));

        }

        private void ReceivePlane(Turntable vo)
        {
            normalAnim.state.SetAnimation(0, "zhongjiang", true);

            DOVirtual.DelayedCall(1.5f, () =>
                       {
                           isClickSpin = false;
                           ResultTween = null;
                           ui.close.touchable = true;
                           ui.close.grayed = false;

                           ui.btn_spin.cont_spin.selectedIndex = 1;

                           ui.btn_spin.cont_state.selectedIndex = 1;

                           var id = vo.wheel_item;
                           var quantity = vo.quantity;

                           if (id == 0)
                           {
                               var startPoint = GameHelper.GetUICenterPosition(ui.startpoint);
                               var endPoint = GameHelper.GetUICenterPosition(ui.point);

                               var rewardData = new RewardData();
                               var rewardSingleData = new RewardSingleData(101, (decimal)quantity, RewardOrigin.LuckyWheel)
                               {
                                   startPosition = startPoint,
                                   endPosition = new Vector2(endPoint.x - 150, endPoint.y - 136),
                               };
                               rewardData.AddReward(rewardSingleData);
                               rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.Dialog |
                         RewardDisplayType.ValueChange;
                               rewardData.AddCompleted((isScu) =>
                               {
                                   normalAnim.state.SetAnimation(0, "daiji", true);
                               });
                               GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                           }
                           else
                           {
                               GameHelper.AddItemNumber(id - 1, (int)quantity);
                               GameHelper.ShowTips("Successfully received");
                           }



                           DataMgr.NextOpenWheelStampTime.Value =
                                              GameHelper.GetNowTime() + GameHelper.GetCommonModel().wheelTimes[1];
                           DataMgr.ThisDayWatchSlyderVideoNum.Value = DataMgr.ThisDayWatchSlyderVideoNum.Value + 1;

                           UpdateTime();
                           refreshData();
                       });
        }

        private void UpdateTime()
        {
            if (DataMgr.ThisDayWatchSlyderVideoNum.Value >= GameHelper.GetCommonModel().wheelTimes[0])
            {
                DateTime currentTime = DateTime.Now;


                ui.btn_spin.cont_state.selectedIndex = 2;
                ui.btn_spin.touchable = false;
                ui.btn_spin.enabled = false;
                ui.btn_spin.cont_spin.selectedIndex = 1;
            }
            else
            {
                if (GameHelper.GetNowTime() >= DataMgr.NextOpenWheelStampTime.Value)
                {
                    ui.btn_spin.touchable = true;
                    ui.btn_spin.enabled = true;
                    ui.btn_spin.cont_spin.selectedIndex = 0;
                    ui.btn_spin.cont_state.selectedIndex = 0;
                }
                else
                {
                    ui.btn_spin.touchable = false;
                    ui.btn_spin.enabled = false;
                    ui.btn_spin.cont_spin.selectedIndex = 1;
                    ui.btn_spin.cont_state.selectedIndex = 1;
                }

                ui.btn_spin.text_time.text = model.NextOpenWheelTimeStr;
            }
        }

    }
}