using System;
using System.Linq;
using UnityEngine;

namespace ScrewsMaster
{
    public class GameDataSystem : BaseSystem
    {
        public Action UpdateSecondEvent;

        private Action onChangeDollar;

        private Action onChangeGiftSwitch;

        public GameDataSystem(bool isAutoInit = true)
        {
            if (isAutoInit)
            {
                Init();
            }
        }

        public sealed override void Init()
        {
            base.Init();
            AddListener();
        }

        private void AddListener()
        {
            CtrlDispatcher.Instance.AddListener(CtrlMsg.Game_StartBefore, InitPreferences);
            PreferencesDispatcher<decimal>.Instance.AddListener(PreferencesMsg.currency102, OnChange102);
            PreferencesDispatcher<float>.Instance.AddListener(PreferencesMsg.playReawrd111, OnChange111);
            CtrlDispatcher.Instance.AddListener(CtrlMsg.GameNewDays, NewDay);
            CtrlDispatcher.Instance.AddListener(CtrlMsg.Module_GiftSwitchChange, OnChangeGiftSwitch);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshADTask, RefreshADTaskData);
            CtrlDispatcher.Instance.AddListener(CtrlMsg.WatchVideoFinish, AddWatchVideo);
            CtrlDispatcher.Instance.AddListener(CtrlMsg.WatchIntVideoFinish, AddIntWatchVideo);

            PreferencesDispatcher<bool>.Instance.AddListener(PreferencesMsg.isShowRewardFly101, OnChangeRewardFly101);
            PreferencesDispatcher<bool>.Instance.AddListener(PreferencesMsg.isShowRewardFly111, OnChangeRewardFly111);
            GameDispatcher.Instance.AddListener(GameMsg.ProcessReward, OnGetReward);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, OnRefreshMakeupData);

        }

        private void OnChangeGiftSwitch(object obj)
        {
            onChangeGiftSwitch?.Invoke();
        }


        private void InitPreferences(object obj)
        {
            if (GameHelper.Get102() == -1)
            {
                PreferencesMgr.Instance.Currency102 = 0;
            }

            // if (PreferencesMgr.Instance.PlayerName.IsNullOrWhiteSpace())
            // {
            //     PreferencesMgr.Instance.PlayerName = "CrazyZoo";
            // }

            if (!GameHelper.IsContinuousSignIn())
            {
                PreferencesMgr.Instance.SignState.Clear();
                PreferencesMgr.Instance.SaveSignState();
            }

            if (PreferencesMgr.Instance.PlayerName.IsNullOrWhiteSpace())
            {
                if (ModuleManager.Instance.GetModel(ModelConst.LoginModel) is LoginModel loginModel)
                {
                    PreferencesMgr.Instance.PlayerName = loginModel.invite_code;
                }
            }

            PreferencesMgr.Instance.IsShowRewardFly101 = false;
            PreferencesMgr.Instance.IsShowRewardFly102 = false;

            InitAchievement();

            CheckMakeupTaskData();


            PreferencesMgr.Instance.IsLastH5Tab = true;
        }


        private void OnRefreshMakeupData(object obj)
        {
            AddMakeupTaskData();
        }


        private void CheckMakeupTaskData()
        {
            if (!GameHelper.IsGiftSwitch())
            {
                return;
            }


            if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0)
            {
                AddMakeupTaskData();
            }
            else
            {
                var common = ConfigSystem.GetConfig<CommonModel>();

                foreach (var makeuptaskData in PreferencesMgr.Instance.MakeupTaskHistory)
                {
                    if (makeuptaskData.status == MakeupTaskStatus.Inline
                        && makeuptaskData.inlineNum > common.inlineMin)
                    {



                        var redeemVOModel = ConfigSystem.GetConfig<MakeupModel>().dataList
                  .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId);

                        var days = PlayerPrefs.GetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}", 0);
                        if (days == DateTime.Today.Day)
                        {
                            continue;
                        }

                        PlayerPrefs.SetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}", DateTime.Today.Day);
                        var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0],
                            common.inlineLoginDown[1]);
                        makeuptaskData.loginSpeedNum += loginNum;
                        //如果登录减少人数大于配置的阈值，则不能减少排名了
                        Debug.Log($"登录累计增加的排名为：{makeuptaskData.loginSpeedNum} 阈值为：{redeemVOModel.Login_Limit_times}");
                        if (makeuptaskData.loginSpeedNum > redeemVOModel.Login_Limit_times)
                        {
                            makeuptaskData.loginSpeedNum = redeemVOModel.Login_Limit_times;
                            continue;
                        }

                        //Debug.Log($"订单为： {makeuptaskData.tableId} 通过登录减少的排名为：{loginNum}");
                        makeuptaskData.inlineNum -= loginNum;
                        if (makeuptaskData.inlineNum < common.inlineMin)
                        {
                            makeuptaskData.inlineNum = common.inlineMin;
                        }
                    }
                }

                PreferencesMgr.Instance.SaveMakeupTaskHistory();
            }
            if (SaveData.GetSaveobject().saveingpot_history.Count == 0)
            {
                // Debug.Log("tianjialishiiiiiiiiiiiiii");
                // AddMakeupTaskData();
            }
            else
            {
                var common = ConfigSystem.GetConfig<CommonModel>();
                foreach (var makeuptaskData in SaveData.GetSaveobject().saveingpot_history)
                {
                    if (makeuptaskData.status == SaveingPotTaskStatus.Inline
                        && makeuptaskData.inlineNum > common.inlineMin)
                    {



                        var redeemVOModel = ConfigSystem.GetConfig<MakeupModel_2>().dataList
                  .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId);

                        var days = PlayerPrefs.GetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}_pot", 0);
                        if (days == DateTime.Today.Day)
                        {
                            continue;
                        }

                        PlayerPrefs.SetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}_pot", DateTime.Today.Day);
                        var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0],
                            common.inlineLoginDown[1]);
                        makeuptaskData.loginSpeedNum += loginNum;
                        //如果登录减少人数大于配置的阈值，则不能减少排名了
                        // Debug.Log($"登录累计增加的排名为：{makeuptaskData.loginSpeedNum} 阈值为：{redeemVOModel.Login_Limit_times}");
                        if (makeuptaskData.loginSpeedNum > redeemVOModel.Login_Limit_times)
                        {
                            makeuptaskData.loginSpeedNum = redeemVOModel.Login_Limit_times;
                            continue;
                        }

                        //Debug.Log($"订单为： {makeuptaskData.tableId} 通过登录减少的排名为：{loginNum}");
                        makeuptaskData.inlineNum -= loginNum;
                        if (makeuptaskData.inlineNum < common.inlineMin)
                        {
                            makeuptaskData.inlineNum = common.inlineMin;
                        }
                    }
                }
            }
            SaveData.saveDataFunc();
        }

        private void CheckSpeedUpTaskData(int type = 1)
        {
            if (!GameHelper.IsGiftSwitch())
            {
                return;
            }

            var common = ConfigSystem.GetConfig<CommonModel>();

            if (type == 1 && PreferencesMgr.Instance.MakeupTaskHistory.Count > 0)
            {
                foreach (var makeuptaskData in PreferencesMgr.Instance.MakeupTaskHistory)
                {
                    if (makeuptaskData.status == MakeupTaskStatus.Inline
                       && makeuptaskData.inlineNum > common.inlineMin)
                    {
                        var redeemVOModel = ConfigSystem.GetConfig<MakeupModel>().dataList
                       .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId);

                        var dowmNum = redeemVOModel.AD_Down;
                        // Debug.Log($"CheckSpeedUpTaskData dowmNum=== {dowmNum} makeuptaskData.WatchVideoSpeedNum ==== {makeuptaskData.WatchVideoSpeedNum}");

                        makeuptaskData.WatchVideoSpeedNum += dowmNum;
                        //如果看广告的减少人数大于配置的阈值，则不能减少排名了
                        if (makeuptaskData.WatchVideoSpeedNum > redeemVOModel.AD_Limit_times)
                        {
                            makeuptaskData.WatchVideoSpeedNum = redeemVOModel.AD_Limit_times;
                            continue;
                        }

                        //Debug.Log($"订单为： {makeuptaskData.tableId} 通过看广告减少的排名为：{dowmNum}");
                        makeuptaskData.inlineNum -= dowmNum;
                        //Debug.Log($"订单为： {makeuptaskData.tableId} 减少后的排名：{makeuptaskData.inlineNum}");
                        if (makeuptaskData.inlineNum < common.inlineMin)
                        {
                            makeuptaskData.inlineNum = common.inlineMin;
                        }
                    }
                }
            }
            if (type == 2 && SaveData.GetSaveobject().saveingpot_history.Count > 0)
            {
                foreach (var makeuptaskData in SaveData.GetSaveobject().saveingpot_history)
                {
                    if (makeuptaskData.status == SaveingPotTaskStatus.Inline
                       && makeuptaskData.inlineNum > common.inlineMin)
                    {
                        var redeemVOModel = ConfigSystem.GetConfig<MakeupModel_2>().dataList
                       .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId);

                        var dowmNum = redeemVOModel.AD_Down;
                        // Debug.Log($"CheckSpeedUpTaskData dowmNum=== {dowmNum} makeuptaskData.WatchVideoSpeedNum ==== {makeuptaskData.WatchVideoSpeedNum}");

                        makeuptaskData.WatchVideoSpeedNum += dowmNum;
                        //如果看广告的减少人数大于配置的阈值，则不能减少排名了
                        if (makeuptaskData.WatchVideoSpeedNum > redeemVOModel.AD_Limit_times)
                        {
                            makeuptaskData.WatchVideoSpeedNum = redeemVOModel.AD_Limit_times;
                            continue;
                        }

                        //Debug.Log($"订单为： {makeuptaskData.tableId} 通过看广告减少的排名为：{dowmNum}");
                        makeuptaskData.inlineNum -= dowmNum;
                        //Debug.Log($"订单为： {makeuptaskData.tableId} 减少后的排名：{makeuptaskData.inlineNum}");
                        if (makeuptaskData.inlineNum < common.inlineMin)
                        {
                            makeuptaskData.inlineNum = common.inlineMin;
                        }
                    }
                }
            }
        }
        public void AddMakeupTaskData()
        {
            var makeupVOModel = ConfigSystem.GetConfig<MakeupModel>();
            if (makeupVOModel == null || makeupVOModel.dataList == null || makeupVOModel.dataList.Count <= 0)
            {
                return;
            }


            var lastId = -1;

            var isRepeat = PreferencesMgr.Instance.MakeupTaskHistory.Count >= makeupVOModel.dataList.Count;
            if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0)
            {
                var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();

                if (makeupTaskData.status != MakeupTaskStatus.Inline)
                {
                    return;
                }

                lastId = makeupTaskData.tableId;
            }


            if (lastId == makeupVOModel.dataList.Last().id)
            {
                lastId = -1;
            }

            foreach (var makeupVo in makeupVOModel.dataList)
            {
                if (makeupVo.id > lastId)
                {
                    if ((isRepeat && !makeupVo.is_onetime) || !isRepeat)
                    {
                        var makeupTaskData = new MakeupTaskData();
                        makeupTaskData.tableId = makeupVo.id;
                        makeupTaskData.id = PreferencesMgr.Instance.MakeupTaskHistory.Count + 1;
                        makeupTaskData.amountStr = $"{GameHelper.Get102Str(makeupVo.item_need)}";
                        makeupTaskData.amount = makeupVo.item_need;
                        makeupTaskData.orderID = GameHelper.GetRandomNum(8);

                        PreferencesMgr.Instance.MakeupTaskHistory.Add(makeupTaskData);
                        makeupTaskData.SetStatus(MakeupTaskStatus.None);
                        PreferencesMgr.Instance.SaveMakeupTaskHistory();

                        PreferencesMgr.Instance.MakeupTaskH5Time = 0;
                        break;
                    }
                }
            }
        }

        private void InitAchievement()
        {
            var achieveVOModel = ConfigSystem.GetConfig<AchieveModel>();
            if (PreferencesMgr.Instance.AchievementAnswerList.Count == 0 && achieveVOModel != null &&
                achieveVOModel.dataList.Count > 0)
            {
                var achieveVo = achieveVOModel.dataList[0];
                for (var i = 0; i < achieveVo.tol_num.Length; i++)
                {
                    PreferencesMgr.Instance.AchievementAnswerList.Add(false);
                }
            }

            if (PreferencesMgr.Instance.AchievementSignInList.Count == 0 && achieveVOModel != null &&
                achieveVOModel.dataList.Count > 0)
            {
                var achieveVo = achieveVOModel.dataList[1];
                for (var i = 0; i < achieveVo.tol_num.Length; i++)
                {
                    PreferencesMgr.Instance.AchievementSignInList.Add(false);
                }
            }
        }


        private void OnChange102(ChangeValue<decimal> obj)
        {
            var val = obj.newValue - obj.oldValue;
            if (val > 0)
            {
                PreferencesMgr.Instance.MaxCurrency102 += val;
            }

            if (!PreferencesMgr.Instance.IsShowRewardFly101)
            {
                GameDispatcher.Instance.Dispatch(GameMsg.Update102Completed);
            }

            onChangeDollar?.Invoke();
        }


        private void OnChange111(ChangeValue<float> obj)
        {
            if (!PreferencesMgr.Instance.IsShowRewardFly111)
            {
                GameDispatcher.Instance.Dispatch(GameMsg.Update111Completed);
            }
        }

        private void NewDay(object obj)
        {
            PreferencesMgr.Instance.IsShowOpenReward = true;
        }

        private void RefreshADTaskData(object obj = null)
        {
        }
        private void AddIntWatchVideo(object obj = null)
        {
            if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0)
            {
                CheckSpeedUpTaskData();
            }
        }
        private void AddWatchVideo(object obj = null)
        {
            PreferencesMgr.Instance.VideoWatchCount++;
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshTodoUI);

            if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0)
            {
                CheckSpeedUpTaskData();

                var taskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                if (taskData.status == MakeupTaskStatus.Task)
                {
                    var makeupVo = ConfigSystem.GetConfig<MakeupModel>().GetData(taskData.tableId);
                    if (makeupVo != null && taskData.videoCount < makeupVo.ad_need)
                    {
                        taskData.videoCount++;
                        NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.watch_ad_number, 1);
                        PreferencesMgr.Instance.SaveMakeupTaskHistory();
                        PlayerPrefs.SetInt("fin_ad_num", 0);
                    }
                    else
                    {
                        if (PlayerPrefs.GetInt("fin_ad_num", 0) == 0)
                        {
                            NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.finish_ad_number, 1);
                            PlayerPrefs.SetInt("fin_ad_num", 1);
                        }

                    }
                }

            }
            if (SaveData.GetSaveobject().saveingpot_history.Count > 0)
            {
                SaveingPotHelper.TestingClearTime();
                CheckSpeedUpTaskData(2);
                SaveingPotClass taskData = SaveData.GetSaveobject().saveingpot_history.Last();
                Makeup_2 makeupVo = ConfigSystem.GetConfig<MakeupModel_2>().GetData(taskData.tableId);
                SaveData.GetSaveobject().saveingpot_cash += makeupVo.ADIncrease;
                GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot);
                if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch())
                {
                    if ((SaveData.GetSaveobject().saveingpot_cash > taskData.amount) && (!taskData.auto_show) && !UIManager.Instance.IsExistUI(UIConst.H5UI))
                    {

                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SaveingPotUI_Open);
                        taskData.auto_show = true;
                    }
                }

                if (taskData.status == SaveingPotTaskStatus.Task)
                {
                    ;
                    if (makeupVo != null && taskData.videoCount < makeupVo.ad_need)
                    {
                        taskData.videoCount++;
                        NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.watch_ad_number, 1);
                        PlayerPrefs.SetInt("fin_ad_num_saveingpot", 0);
                    }
                    else
                    {
                        if (PlayerPrefs.GetInt("fin_ad_num_saveingpot", 0) == 0)
                        {
                            NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.finish_ad_number, 1);
                            PlayerPrefs.SetInt("fin_ad_num_saveingpot", 1);
                        }

                    }
                }

            }
        }

        private void OnChangeRewardFly101(ChangeValue<bool> obj)
        {
            var oldValue = obj.oldValue;
            var newValue = obj.newValue;

            InitChangeRewardFly(101, oldValue, newValue);
        }

        private void OnChangeRewardFly111(ChangeValue<bool> obj)
        {
            var oldValue = obj.oldValue;
            var newValue = obj.newValue;

            InitChangeRewardFly(111, oldValue, newValue);
        }

        private void InitChangeRewardFly(int id, bool oldValue, bool newValue)
        {
            if (oldValue)
            {
                if (newValue)
                {
                }
                else
                {
                    switch (id)
                    {
                        case 101:
                            GameDispatcher.Instance.Dispatch(GameMsg.Update102Completed);
                            break;
                        case 102:
                            GameDispatcher.Instance.Dispatch(GameMsg.Update102Completed);
                            break;
                        case 111:
                            GameDispatcher.Instance.Dispatch(GameMsg.Update111Completed);
                            break;
                    }
                }
            }
            else
            {
                if (newValue)
                {
                }
                else
                {
                }
            }
        }


        private void OnGetReward(object obj)
        {
            if (obj is RewardData rewardModel)
            {
                foreach (var rewardData in rewardModel.GetRewardDataList())
                {
                    ProcessData(rewardData);
                }
            }
        }


        private void ProcessData(RewardSingleData rewardSingleData)
        {
            if (rewardSingleData.origin == RewardOrigin.None)
            {
                return;
            }

            switch (rewardSingleData.id)
            {
                case 101:
                    GameHelper.AddGoldNumber((int)rewardSingleData.GetTotalValue());
                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                    break;
                case 102:
                    GameHelper.AddMoney((float)rewardSingleData.GetTotalValue());
                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
                    break;
                case 111:
                    {
                        var dollar = PreferencesMgr.Instance.PlayReawrd111;
                        dollar += rewardSingleData.GetTotalValue();

                        PreferencesMgr.Instance.PlayReawrd111 = dollar;
                        break;
                    }
            }

        }
    }
}