namespace ScrewsMaster
{
    using System;
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;

    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;
        public QuestionBank selectedQuestionbankVo;
        public event Action UpdateEvent;

        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);
            InitSystem();
        }

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

        private void OnGameStart(object obj)
        {
            var lang = PlayerPrefsKit.ReadString("LangIdKey");
            if (lang.IsNullOrWhiteSpace())
            {
                lang = "en";
            }
            PurchasingManager.Instance.InitProduct();
            AudioManager.Instance.PlayBGM("game_bgm");
            UIManager.Instance.SetSwitchLanguage(lang);
            EnterHall();

            isGameStart = true;
        }

        private void EnterHall(object obj = null)
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardAniUI_Close);
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepPlayUI_Open);
            // Debug.Log("dakaiyouxijiemian");
            // AudioManager.Instance.PlayBGM(AudioConst.MainBg);

            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainTabUI_Open);


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

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

            // DateTime newDate = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            // newDate = newDate.AddSeconds(GameHelper.GetNowTime());
            // var newDays = newDate.Day;
            // var last_time = PlayerPrefs.GetInt("Dayreftimes", 0);
            // if (last_time != newDays)
            // {
            //     var config = ConfigSystem.GetConfig<CommonModel>();
            //     if (config == null)
            //     {
            //         return;
            //     }
            //     SaveData.GetSaveobject().onlineRewardsTimes = 0;
            // }
        }
        private void EnterGame(object obj)
        {
            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainTabUI_Close);
            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Close);
            var questionDatas = obj as List<GameQuestionData>;
        }

        #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 List<GameQuestionData> RandomSelectQuestions(QuestionBank vo, bool isGuide = false)
        {
            var questionDatas = new List<GameQuestionData>();
            int needGenerate = CommonHelper.RandomRange(ConfigSystem.GetConfig<CommonModel>().quiznum);

            int temp = needGenerate;
            while (temp > 0)
            {
                var questionModel = QuestionBankKit.GetQuestionTable(vo, isGuide);
                bool isAdd = true;
                foreach (var gameQuestionData in questionDatas)
                {
                    if (gameQuestionData.questionType.Equals(questionModel.questionType)
                        && gameQuestionData.questionTableID.Equals(questionModel.questionTableID))
                    {
                        isAdd = false;
                    }
                }

                if (isAdd)
                {
                    temp--;
                    questionDatas.Add(questionModel);
                }
            }

            foreach (var questionData in questionDatas)
            {
                GetGalleryNet(questionData.logoId);
            }

            return questionDatas;
        }

        public void GetQuestionData(List<GameQuestionData> questionDatas, Action<int> totalDownloadAction,
            Action preAction = null,
            Action<bool> action = null)
        {
            StartCoroutine(GetQuestionData1(questionDatas, totalDownloadAction, preAction, action));
        }


        private IEnumerator GetQuestionData1(List<GameQuestionData> questionDatas, Action<int> totalDownloadAction,
            Action preAction = null,
            Action<bool> action = null)
        {
            int logoCount = 0;

            int completedIndex = 0;
            int cacheCompletedIndex = 0;

            foreach (var questionData in questionDatas)
            {
                if (questionData.logoId != 0)
                {
                    logoCount++;
                }
            }

            totalDownloadAction?.Invoke(logoCount);

            for (var i = 0; i < questionDatas.Count; i++)
            {
                var questionData = questionDatas[i];
                GetGalleryNet(questionData.logoId, (bool isSuccess) =>
                {
                    completedIndex++;
                    if (isSuccess)
                    {
                        cacheCompletedIndex++;
                    }

                    preAction?.Invoke();
                    if (completedIndex == questionDatas.Count)
                    {
                        CommonHelper.RandomSortList(questionDatas);
                        action?.Invoke(cacheCompletedIndex == questionDatas.Count);
                    }
                });
            }

            yield return null;
        }

        public void AddChangeGiftSwitch(Action action)
        {
        }

        public void RemoveChangeGiftSwitch(Action action)
        {
        }

        void OnApplicationQuit()
        {
            PreferencesMgr.Instance.ImmediateSendSave();
        }

        private bool isInH5;
    }
}