using SGModule.NetKit;

namespace RedHotRoast
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using IgnoreOPS;
    // using SGModule.ApplePay;
    using SGModule.Common;
    using UnityEngine;

    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 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, (a) =>
            {
                EnterHall();
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Open);
            });

            AppDispatcher.Instance.AddListener(MainThreadMsg.App_Focus_True, BackToGame);
            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();
            }

        }
        private void OnGameStart(object obj)
        {
            var enterGame = CommonHelper.GetBoolByChance(ConfigSystem.GetCommonConf().roomrate / 100f);
            EnterHall(enterGame);
            isGameStart = true;
            var appleData = new ApplePayData
            {
                sku = "",
                amount = 0,
                currency = "USD",
                shopName = "",
                type = ""
            };
            List<ApplePay2> listA = ConfigSystem.GetConfig<ApplePay2>();

            // // 方式一：LINQ Select
            // List<ProductConfig> listB = listA
            //     .Select(a => new ProductConfig
            //     {
            //         name = a.name,
            //         sku = a.sku,
            //         price = a.price,
            //         type = a.type
            //     })
            //     .ToList();
            // if (GameHelper.IsGiftSwitch())
            // {
            //     GameObject.Find("game_bg_a").SetActive(false);
            // }
            // //初始化商品
            // ApplePayManager.Instance.InitProduct(listB,
            //     ConfigManager.GameConfig.packageName, PurchasingManager.ApplePaySuccessCallback(appleData));

            if (GameHelper.IsGiftSwitch() && enterGame)
            {
                if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal)
                {
                    EnterGame(enterGame);
                }
                else
                {
                    if (!DataMgr.LevelUnlockListNew.Value.Any(x => x.level_ == GameHelper.GetLevel()))
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockLevelNewUI_Open, true);
                    }
                    else
                    {
                        EnterGame(enterGame);
                    }
                }
            }


            TrackKit.TrackLoginFunnel(LoginFunnelEventType.EnterHall);

            // 游戏启动时，检查VIP是否过期
            GameHelper.CheckVipExpiration();
            // DataMgr.Coin.Value = 999999;//zhushi
            MemoryManager.StartMemoryMonitor(ConfigSystem.GetCommonConf().ClearRAM);
            if (GameHelper.IsGiftSwitch()) UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BroadcastUI_Open);
        }

        private void EnterHall(object obj = null)
        {
            bool enterGame = false;
            if (obj != null)
            {
                enterGame = (bool)obj;
            }

            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, enterGame);

            GameHelper.PlayGameTimeEvent(1);
            MemoryManager.CleanMemoryMonitor();
        }


        private void EnterGame(object obj)
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainTabUI_Close);
            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()
        // {
        //     PreferencesMgr.Instance.ImmediateSendSave();
        // }

        private bool isInH5;

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