using System;
using UnityEngine;
using DG.Tweening;
using BingoBrain.Core;
using FGUI.JWheel;
using System.Collections.Generic;
using Spine.Unity;
using Newtonsoft.Json;

namespace BingoBrain
{
    public class BingoToyUI : BaseUI
    {
        private BingoToyUICtrl ctrl;
        private BingoToyModel model;
        public com_wheel ui;
        private List<com_reward> com_RewardLst = new();
        private int[] freeWeight = new int[8];
        private List<float> vidieWeight = new();
        private bool isClickSpin;
        private Action CloseCb;
        private ParticleSystem fx_zhuangpan_enter;
        private SkeletonAnimation wheel_ani;

        public BingoToyUI(BingoToyUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.BingoToyUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期

        protected override void OnInit()
        {
            model = ModuleBoardk.GetModel(ModelConst.BingoToyModel) as BingoToyModel;
        }

        protected override void OnClose()
        {
            ui?.FadeOut();
            Hall.Instance.UpdateSecondEvent -= UpdateTime;
            CloseCb?.Invoke();
        }

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

        protected override void OnOpenBefore(object args)
        {
            Audio.Instance.PlayDynamicEffect("pop_open");
            // FX.Instance.SetFx<ParticleSystem>(ui.gp_Fx, Fx_Type.fx_zhuangpan_enter, ps =>
            // {
            //     fx_zhuangpan_enter = ps;
            //     fx_zhuangpan_enter.gameObject.SetActive(false);
            // }, CloseCb);
            FX.Instance.SetFx<SkeletonAnimation>(ui.gp_Fx, Fx_Type.fx_wheel,
                ps =>
                {
                    //  ps.transform.localPosition = new Vector3(0, 195, 0);
                    wheel_ani = ps;
                    NAAVsa.PlayAnim(wheel_ani, "daiji", true);
                }, CloseCb);

            ui.com_wheels.gp_Select.visible = false;

            SetWheelData();

            com_RewardLst.Add(ui.com_wheels.com_reward1);
            com_RewardLst.Add(ui.com_wheels.com_reward2);
            com_RewardLst.Add(ui.com_wheels.com_reward3);
            com_RewardLst.Add(ui.com_wheels.com_reward4);
            com_RewardLst.Add(ui.com_wheels.com_reward5);
            com_RewardLst.Add(ui.com_wheels.com_reward6);
            com_RewardLst.Add(ui.com_wheels.com_reward7);
            com_RewardLst.Add(ui.com_wheels.com_reward8);

            var dataList = GameHelper.GetConfig<TurntableModel>().GetDataList();
            for (var i = 0; i < dataList.Count; i++)
            {
                freeWeight[i] = dataList[i].weightA;
                vidieWeight.Add(dataList[i].weightB);
            }

            ui.closeButton.SetClick(CtrlCloseUI);
            ui.btn_spin.SetClick(ClickSpinBtn);
            ui.com_Spinn.SetClick(ClickSpinBtn);
            ui.fairyBatching = false;
            Hall.Instance.UpdateSecondEvent += UpdateTime;
        }

        private void UpdateTime()
        {
            ui.btn_spin.cont_button.selectedIndex =
                GameHelper.GetNowTime() >= PreferencesMgr.Instance.NextOpenWheelStampTime
                    ? btn_spin.Button_none
                    : btn_spin.Button_cd;

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

        private void SetWheelData()
        {
            if (PreferencesMgr.Instance.WheelVersion != GameHelper.GetDynamicVersion())
            {
                PreferencesMgr.Instance.FerrWheelLst.Clear();
                PreferencesMgr.Instance.VidelWheelLst.Clear();
            }

            var turntableModel = GameHelper.GetConfig<TurntableModel>();
            // if (PreferencesMgr.Instance.FerrWheelLst.Count < turntableModel.GetCount() ||
            //     PreferencesMgr.Instance.VidelWheelLst.Count < turntableModel.GetCount())
            // {
            Debug.Log("????????????????ttttttttttttttttt");
            PreferencesMgr.Instance.FerrWheelLst.Clear();
            PreferencesMgr.Instance.VidelWheelLst.Clear();
            var list = turntableModel.GetDataList();
            foreach (var item in list)
            {
                PreferencesMgr.Instance.FerrWheelLst.Add(
                    item.quantityA[GameHelper.GetDynamicIndex(item.wheel_itemA)]);
                PreferencesMgr.Instance.VidelWheelLst.Add(
                    item.quantityB[GameHelper.GetDynamicIndex(item.wheel_itemB)]);
            }

            PreferencesMgr.Instance.SaveFerrWheelLst();
            PreferencesMgr.Instance.SaveVidelWheelLst();
            PreferencesMgr.Instance.WheelVersion = GameHelper.GetDynamicVersion();
            // }
        }

        protected override void OnOpen(object args)
        {
            ui?.FadeIn();
            UpdateTime();
            RefreshUI();
            ui.cont_state.selectedIndex =
                PreferencesMgr.Instance.IsOnceWheel ? com_wheel.State_normal : com_wheel.State_videl;
        }

        private void RefreshUI(object o = null)
        {
            var turntableModel = GameHelper.GetConfig<TurntableModel>();

            for (var i = 0; i < com_RewardLst.Count; i++)
            {
                var rewards = com_RewardLst[i];
                if (GameHelper.IsGiftSwitch()) rewards.gift.selectedIndex = 1;
                var turntable = turntableModel.GetData(i + 1);
                int id;
                string val;
                if (PreferencesMgr.Instance.IsOnceWheel)
                {
                    id = turntable.wheel_itemA;
                    val = id == 102
                        ? GameHelper.Get102Str((decimal)PreferencesMgr.Instance.FerrWheelLst[i])
                        : PreferencesMgr.Instance.FerrWheelLst[i].ToString();
                }
                else
                {
                    id = turntable.wheel_itemB;
                    if(id == 101)
                    {
                        PreferencesMgr.Instance.VidelWheelLst[i]=MathF.Ceiling(PreferencesMgr.Instance.VidelWheelLst[i]);
                    }
                    val = id == 102
                        ? GameHelper.Get102Str((decimal)PreferencesMgr.Instance.VidelWheelLst[i])
                        : PreferencesMgr.Instance.VidelWheelLst[i].ToString();
                }

                rewards.cont_currency.selectedIndex = id switch
                {
                    101 => com_reward.Currency_coin,
                    102 => com_reward.Currency_diam,
                    104 => com_reward.Currency_card,
                    _ => rewards.cont_currency.selectedIndex
                };

                rewards.text_num.text = val;
            }
        }

        private void ClickSpinBtn()
        {
            if (isClickSpin)
                return;
            if (!PreferencesMgr.Instance.IsOnceWheel)
            {
                if (GameHelper.GetNowTime() < PreferencesMgr.Instance.NextOpenWheelStampTime)
                {
                    return;
                }

                GameHelper.GetVideo("reward_wheel", isSuccess =>
                {
                    if (isSuccess)
                    {
                        PlayLucky();
                    }
                });
            }
            else
            {
                PlayLucky();
            }
        }

        private void PlayLucky()
        {
            isClickSpin = true;

            ui.closeButton.touchable = false;
            ui.closeButton.grayed = true;
            ui.btn_spin.touchable = false;
            ui.btn_spin.grayed = true;
            ui.com_Spinn.touchable = false;
            ui.com_Spinn.cont_spin.selectedIndex = com_spin.Spin_grey;
            ui.com_wheels.rotation = 0;
            var index = PreferencesMgr.Instance.IsOnceWheel
                ? GlobalHarmony.RandomWeight(freeWeight)
                : GlobalHarmony.GetChanceList(vidieWeight);

            var turntableModel = GameHelper.GetConfig<TurntableModel>();
            var vo = turntableModel.GetData(index + 1);

            var angle = UnityEngine.Random.Range(3600 - (vo.Seq - 1) * 45, 3600 - (vo.Seq - 1) * 45)
                        ;
            NAAVsa.PlayAnim(wheel_ani, "zhuandong", true);
            Audio.Instance.PlayDynamicEffect("wheel_spin");
            ui.fx_zhen.Play();
            DOTween.To(() => ui.com_wheels.rotation, (e) => ui.com_wheels.rotation = e, angle, model.animationTime)
                .SetEase(AnimationCurveData.Instance.LuckySpinAniCurve);
            tw = DOVirtual.DelayedCall(model.animationTime, () => OpenReceivePlane(vo));
        }

        private Tween tw;

        private void OpenReceivePlane(Turntable vo)
        {
            ui.fx_zhen.Stop();
            // ui.img_zhen.rotation = 0;
            ui.com_wheels.gp_Select.visible = true;
            ui.com_wheels.gp_Select.rotation = (vo.Seq - 2) * 45 + 22.5f;
            NAAVsa.PlayAnim(wheel_ani, "zhongjiang", true);
            DOVirtual.DelayedCall(1.5f, () =>
            {
                ui.com_wheels.gp_Select.visible = false;
                isClickSpin = false;
                tw = null;
                ui.closeButton.touchable = true;
                ui.btn_spin.touchable = true;
                ui.com_Spinn.touchable = true;
                ui.btn_spin.grayed = false;
                ui.closeButton.grayed = false;
                ui.com_Spinn.cont_spin.selectedIndex = com_spin.Spin_none;
                NAAVsa.PlayAnim(wheel_ani, "daiji", true);
                if (PreferencesMgr.Instance.IsOnceWheel)
                {
                   // ui.closeButton.touchable = false;
                  //  ui.btn_spin.touchable = false;
                    ui.com_Spinn.touchable = false;
                  //  ui.btn_spin.grayed = true;

                    GameHelper.GetRewardExtra(vo.wheel_itemA, (decimal)PreferencesMgr.Instance.FerrWheelLst[vo.Seq - 1],
                        vo.cont_index, isCompleted =>
                        {
                            PreferencesMgr.Instance.FerrWheelLst.Clear();
                            PreferencesMgr.Instance.IsOnceWheel = false;

                            ui.fx_exit.Play();
                            var sequence = DOTween.Sequence();
                            sequence.Append(DOVirtual.DelayedCall(0.75f, () =>
                            {
                                ui.cont_state.selectedIndex = PreferencesMgr.Instance.IsOnceWheel
                                    ? com_wheel.State_normal
                                    : com_wheel.State_videl;
                                SetWheelData();
                                RefreshUI();
                                ui.fx_enter.Play();
                            }));
                            sequence.Append(DOVirtual.DelayedCall(0.75f, () =>
                            {
                                fx_zhuangpan_enter.gameObject.SetActive(true);
                                ui.closeButton.touchable = true;
                                ui.btn_spin.touchable = true;
                                ui.com_Spinn.touchable = true;
                                ui.btn_spin.grayed = false;
                                Audio.Instance.PlayDynamicEffect("wheel_show");
                            }));

                        });
                }
                else
                {
                    GameHelper.GetRewardOnly(vo.wheel_itemB,
                        (decimal)PreferencesMgr.Instance.VidelWheelLst[vo.Seq - 1], RewardOrigin.Wheel);

                    PreferencesMgr.Instance.VidelWheelLst.Clear();
                    PreferencesMgr.Instance.NextOpenWheelStampTime =
                        GameHelper.GetNowTime() + GameHelper.GetCommonModel().TurntableCD;
                    UpdateTime();

                    SetWheelData();
                    RefreshUI();
                }
            });
        }

        #endregion
    }
}