using DG.Tweening;
using IgnoreOPS;
using SGModule.Net;

namespace ChillConnect
{
    using System;
    using UnityEngine;
    using System.Collections.Generic;
    using Unity.VisualScripting;
    using FairyGUI;
    using SGModule.ApplePay;
    using Newtonsoft.Json;
    using SGModule.NetKit;
    using Assets.Scripts;
    using SGModule.Common;

    public class HallManager : BaseUnityManager<HallManager>
    {
        public event Action UpdateSecondEvent;
        public event Action UpdateFiveSecondEvent;

        private float _secondTime;
        private float _secondTime1;
        private LoginModel loginModel;
        private bool isGameStart;
        private GameDataSystem gameDataSys;
        private WindowSystem windowSys;
        private RewardSystem rewardSys;
        private ConsumeSystem consumeSys;

        private bool isFirstEnter = true;
        public int enterHallTimes = 0;
        public bool isShowRankView = false;
        public event Action UpdateEvent;


        // public  int countTimes = 0;

        public override void Init()
        {
            CtrlDispatcher.Instance.AddListener(CtrlMsg.Game_Start, OnGameStart);
            GameDispatcher.Instance.AddListener(GameMsg.OpenGame, EnterGame);
            GameDispatcher.Instance.AddListener(GameMsg.BackMainScene, EnterHall);

            AppDispatcher.Instance.AddListener(MainThreadMsg.App_Focus_True, BackToGame);
            SetSoundVolume();
            InitSystem();
        }

        private void InitSystem()
        {
            gameDataSys = new GameDataSystem();
            windowSys = new WindowSystem();
            rewardSys = new RewardSystem();
            consumeSys = new ConsumeSystem();
        }

        void BackToGame(object obj = null)
        {
            if (MaxPayManager.isPay)
            {
                MaxPayManager.isPay = false;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);
                MaxPayManager.Instance.PaySuccess();
            }

            var last_time = PlayerPrefs.GetInt("Dayreftimes", 0);
            DateTime newDate = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            newDate = newDate.AddSeconds(GameHelper.GetNowTime(true));
            // Debug.Log($"barry newdate==== {newDate}");
            var newDays = newDate.Day;

        }
        private void OnGameStart(object obj)
        {
            var lang = PlayerPrefsKit.ReadString("LangIdKey");
            if (lang.IsNullOrWhiteSpace())
            {
                lang = "en";
            }
            Debug.Log(ConfigSystem.GetConfig<CommonModel>().ExchangeModeToggle + "//////////////////////");

            //初始化商品
            // PurchasingManager.Instance.InitProduct();
            var appleData = new ApplePayData
            {
                sku = "",
                amount = 0,
                currency = "USD",
                shopName = "",
                type = ""
            };
            // ApplePayManager.Instance.InitProduct(ConfigSystem.GetConfig<ApplePayModel2>().DataList,
            //     ConfigManager.GameConfig.packageName, PurchasingManager.ApplePaySuccessCallback(appleData));

            Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<ApplePayModel>().DataList));
            UIManager.Instance.SetSwitchLanguage(lang);

            EnterHall(true);
            isGameStart = true;

            TrackKit.TrackLoginFunnel(LoginFunnelEventType.EnterHall);
            // Debug.Log("?????????????????" + PurchasingManager.GetPaySku(PayType.pack_reward));
            // Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<ApplePayModel>().DataList));
            // bool enterGame = CommonHelper.GetBoolByChance(ConfigSystem.GetConfig<CommonModel>().roomrate / 100f);
            // if (GameHelper.IsGiftSwitch() && enterGame)
            // {
            //     EnterGame(enterGame);
            // }

            // DOVirtual.DelayedCall(1f, PurchasingManager.StartPay);

        }
        private void SetSoundVolume()
        {
            float last_sound = PlayerPrefs.GetFloat("soundVolume", 1.0f);
            // Debug.Log($"barry last_sound=== " + last_sound);
            GRoot.inst.soundVolume = last_sound;

            AudioManager.Instance.SetBGMSound();
        }

        private void EnterHall(object obj = null)
        {
            // int index = obj != null ? (int)obj : 2;

            enterHallTimes++;
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PlayUI_Close);
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardAniUI_Close);
            AudioManager.Instance.StopBGM();
            AudioManager.Instance.PlayBGM(AudioConst.MainBg);
            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Open);

            if (GameHelper.IsGiftSwitch() && (obj != null))
            {
                int h5rate = GameHelper.GetCommonModel().loginhallrate;
                int roomrate = GameHelper.GetCommonModel().roomrate;
                // if (UnityEngine.Random.Range(1, 100) < h5rate) {
                //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open);
                // } else
                if (UnityEngine.Random.Range(1, 100) < roomrate)
                {//进入玩法

                    GameHelper.is_first_login = false;
                    // OnClickPlay();
                    if (!SaveData.GetSaveObject().have_slot && (DateTime.Now.Day != PlayerPrefs.GetInt("off_new", 0)))
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Open);
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddviewnewUI_Open);
                        PlayerPrefs.SetInt("off_new", DateTime.Now.Day);
                    }
                    if (!SaveData.GetSaveObject().have_slot && UnityEngine.Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().BonusInside)
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Open);
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddviewnewUI_Open);
                    }
                    else
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RainPlayUI_Open, true);

                    }
                }
                else
                {
                    GameHelper.is_first_login = false;
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Open, true);
                }


            }
            else
            {
                GameHelper.is_first_login = false;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Open);
            }


            if (GameHelper.IsGiftSwitch()) UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BroadcastUI_Open);
            GameHelper.PlayGameTimeEvent(1);
        }


        private void EnterGame(object obj)
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Close);
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RainPlayUI_Open);
            AudioManager.Instance.StopBGM();

            AudioManager.Instance.PlayBGM(AudioConst.GameBg);

        }

        #region 缓存资源

        public void GetGalleryNet(int imageID, Action<bool> action = null)
        {
           // StartCoroutine(TextureHelper.GetGalleryFromNet(imageID, action));
        }

        #endregion

        public void Update()
        {
            if (!isGameStart) return;
            UpdateEvent?.Invoke();
            _secondTime += Time.deltaTime;
            _secondTime1 += Time.deltaTime;
            if (_secondTime >= 1)
            {
                _secondTime = 0;
                UpdateSecondEvent?.Invoke();
            }

            if (_secondTime1 >= 5)
            {
                _secondTime1 = 0;
                UpdateFiveSecondEvent?.Invoke();
            }
        }

        public void AddChangeGiftSwitch(Action action)
        {
        }

        public void RemoveChangeGiftSwitch(Action action)
        {
        }

        void OnApplicationQuit()
        {
          //  DataMgr.ImmediateSendSave();
        }

        private bool isInH5;

        public void SetInH5(bool isInH5)
        {
            this.isInH5 = isInH5;
        }
    }
}
