using System;
using System.Linq;
using SGModule.NetKit;
using UnityEngine;

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

        private Action onChangeDollar;

        private Action onChangeGiftSwitch;

        private long _uid;

        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(DataMsg.currency101, OnChange101);
            PreferencesDispatcher<float>.Instance.AddListener(DataMsg.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(DataMsg.isShowRewardFly101, OnChangeRewardFly101);
            PreferencesDispatcher<bool>.Instance.AddListener(DataMsg.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 (DataMgr.Coin.Value == -1)
            {
                DataMgr.Coin.Value = 0;
            }

            if (DataMgr.Ticket.Value == -1)
            {
                DataMgr.Ticket.Value = 0;
            }

            if (!GameHelper.IsContinuousSignIn())
            {
                DataMgr.SignState.Value.Clear();
            }

            if (DataMgr.PlayerName.Value.IsNullOrWhiteSpace())
            {
                if (GameHelper.GetLoginModel() != null)
                {
                    DataMgr.PlayerName.Value = GameHelper.GetLoginModel().InviteCode;
                }
            }

            DataMgr.IsShowRewardFly101.Value = false;
            DataMgr.IsShowRewardFly102.Value = false;


            CheckMakeupTaskData();


            DataMgr.IsLastH5Tab.Value = true;


            CommonHelper.CheckAdTimes();


            _uid = LoginKit.Instance.LoginModel.Uid;
        }


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


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


            if (DataMgr.MakeupTaskHistory.Value.Count == 0)
            {
                AddMakeupTaskData();
            }
            else
            {
                var common = ConfigSystem.GetCommonConf();

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



                        var rmVOModel = ConfigSystem.GetConfig<Makeup>()
                  .FirstOrDefault(rm => rm.id == makeuptaskData.tableId);

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

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

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

                DataMgr.MakeupTaskHistory.Save();;
            }
            if (SaveData.GetSaveObject().saveingpot_history.Count == 0)
            {
                // Debug.Log("tianjialishiiiiiiiiiiiiii");
                // AddMakeupTaskData();
            }
            else
            {
                var common = ConfigSystem.GetCommonConf();
                foreach (var makeuptaskData in SaveData.GetSaveObject().saveingpot_history)
                {
                    if (makeuptaskData.status == SaveingPotTaskStatus.Inline
                        && makeuptaskData.inlineNum > common.inlineMin)
                    {



                        var rmVOModel = ConfigSystem.GetConfig<Makeup_2>()
                  .FirstOrDefault(rm => rm.id == makeuptaskData.tableId);

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

                        PlayerPrefs.SetInt($"days_{_uid}_{makeuptaskData.tableId}_pot", DateTime.Today.Day);
                        var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0],
                            common.inlineLoginDown[1]);
                        makeuptaskData.loginSpeedNum += loginNum;
                        //如果登录减少人数大于配置的阈值，则不能减少排名了
                        if (makeuptaskData.loginSpeedNum > rmVOModel.Login_Limit_times)
                        {
                            makeuptaskData.loginSpeedNum = rmVOModel.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.GetCommonConf();

             if (type == 1 && DataMgr.MakeupTaskHistory.Value.Count > 0)
            {
                foreach (var makeuptaskData in DataMgr.MakeupTaskHistory.Value)
                {
                    if (makeuptaskData.status == MakeupTaskStatus.Inline
                       && makeuptaskData.inlineNum > common.inlineMin)
                    {
                        var rmVOModel = ConfigSystem.GetConfig<Makeup>()
                       .FirstOrDefault(rm => rm.id == makeuptaskData.tableId);

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

                        makeuptaskData.WatchVideoSpeedNum += dowmNum;
                        //如果看广告的减少人数大于配置的阈值，则不能减少排名了
                        if (makeuptaskData.WatchVideoSpeedNum > rmVOModel.AD_Limit_times)
                        {
                            makeuptaskData.WatchVideoSpeedNum = rmVOModel.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 rmVOModel = ConfigSystem.GetConfig<Makeup_2>()
                       .FirstOrDefault(rm => rm.id == makeuptaskData.tableId);

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

                        makeuptaskData.WatchVideoSpeedNum += dowmNum;
                        //如果看广告的减少人数大于配置的阈值，则不能减少排名了
                        if (makeuptaskData.WatchVideoSpeedNum > rmVOModel.AD_Limit_times)
                        {
                            makeuptaskData.WatchVideoSpeedNum = rmVOModel.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<Makeup>();
            if (makeupVOModel == null || makeupVOModel == null || makeupVOModel.Count <= 0)
            {
                return;
            }


            var lastId = -1;

            var isRepeat = DataMgr.MakeupTaskHistory.Value.Count >= makeupVOModel.Count;
            if (DataMgr.MakeupTaskHistory.Value.Count > 0)
            {
                var makeupTaskData = DataMgr.MakeupTaskHistory.Value.Last();

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

                lastId = makeupTaskData.tableId;
            }


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

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

                        DataMgr.MakeupTaskHistory.Value.Add(makeupTaskData);
                        Debug.Log("uuuuuuuuuuuuuuuuuuuu");
                        makeupTaskData.SetStatus(MakeupTaskStatus.None);
                        DataMgr.MakeupTaskHistory.Save();;

                        DataMgr.MakeupTaskH5Time.Value = 0;
                        break;
                    }
                }
            }
        }

        private void OnChange101(ChangeValue<decimal> obj)
        {
            var val = obj.newValue - obj.oldValue;
            if (val > 0)
            {
                DataMgr.MaxCurrency101.Value += (int)val;
            }

            if (!DataMgr.IsShowRewardFly101.Value)
            {
                GameDispatcher.Instance.Dispatch(GameMsg.Update101Completed);
            }

            onChangeDollar?.Invoke();
        }


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

        private void NewDay(object obj)
        {
            DataMgr.IsShowOpenReward.Value = true;
        }

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

            int adNums = AdExchangeManager.Instance.GetLookRewardADNum();
            adNums++;
            AdExchangeManager.Instance.SetLookRewardADNum(adNums);

            if (DataMgr.MakeupTaskHistory.Value.Count > 0)
            {
                CheckSpeedUpTaskData();

                var taskData = DataMgr.MakeupTaskHistory.Value.Last();
                if (taskData.status == MakeupTaskStatus.Task)
                {
                    var makeupVo = MakeupModel.GetData(taskData.tableId);
                    if (makeupVo != null && taskData.videoCount < makeupVo.ad_need)
                    {
                        taskData.videoCount++;
                        DataMgr.MakeupTaskHistory.Save();;
                        PlayerPrefs.SetInt("fin_ad_num", 0);
                    }
                    else
                    {
                        if (PlayerPrefs.GetInt("fin_ad_num", 0) == 0)
                        {
                            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 =MakeupModel_2.GetData(taskData.tableId);
                SaveData.GetSaveObject().saveingpot_ch += makeupVo.ADIncrease;

                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.Update101Completed);
                            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:
                    {
                        var roomTicket = DataMgr.Coin.Value;
                        roomTicket += (int)rewardSingleData.GetTotalValue();

                        DataMgr.Coin.Value = roomTicket;
                    }
                    break;
                case 102:
                    {
                        var dollar = DataMgr.Ticket.Value;
                        dollar += rewardSingleData.GetTotalValue();

                        DataMgr.Ticket.Value = dollar;
                        break;
                    }
                case 111:
                    {
                        var dollar = DataMgr.PlayReawrd111.Value;
                        dollar += rewardSingleData.GetTotalValue();

                        DataMgr.PlayReawrd111.Value = dollar;
                        break;
                    }
            }
        }
    }
}
