using System;
using System.Linq;
using IgnoreOPS;
using Newtonsoft.Json;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;

namespace ChillConnect
{
    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(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.PlayerName.Value.IsNullOrWhiteSpace())
            {
                if (GameHelper.GetLoginModel() != null)
                {
                    DataMgr.PlayerName.Value = GameHelper.GetLoginModel().InviteCode;
                }
            }
            if (DataMgr.PlayerName.Value.IsNullOrWhiteSpace())
            {
                // DataMgr.PlayerName = "ProductSort001";
            }

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



            // DataMgr.IsShowRewardFly101 = false;
            // DataMgr.IsShowRewardFly102 = false;


            CheckMakeupTaskData();
            // RankSystemMgr.Instance.checkUsers();

            // DataMgr.IsLastH5Tab = true;
        }


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


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


            if (DataMgr.MakeupTaskHistory.Value.Count == 0)
            {
                Debug.Log("tianjialishiiiiiiiiiiiiii");
                AddMakeupTaskData();
            }
            else
            {
                var common = ConfigSystem.GetConfig<CommonModel>();

                foreach (var makeuptaskData in DataMgr.MakeupTaskHistory.Value)
                {
                    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_{LoginKit.Instance.LoginModel.Uid}_{makeuptaskData.tableId}", 0);
                        if (days == DateTime.Today.Day)
                        {
                            continue;
                        }

                        PlayerPrefs.SetInt($"days_{LoginKit.Instance.LoginModel.Uid}_{makeuptaskData.tableId}", DateTime.Today.Day);
                        var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0],
                            common.inlineLoginDown[1]);

                        //如果登录减少人数大于配置的阈值，则不能减少排名了
                        // Debug.Log($"登录累计增加的排名为：{makeuptaskData.loginSpeedNum} 阈值为：{redeemVOModel.Login_Limit_times}");
                        if (makeuptaskData.loginSpeedNum > redeemVOModel.Login_Limit_times)
                        {
                            makeuptaskData.loginSpeedNum = redeemVOModel.Login_Limit_times;
                            continue;
                        }
                        if (makeuptaskData.loginSpeedNum + loginNum > redeemVOModel.Login_Limit_times) loginNum = redeemVOModel.Login_Limit_times - makeuptaskData.loginSpeedNum;
                        makeuptaskData.loginSpeedNum += loginNum;
                        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.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_{LoginKit.Instance.LoginModel.Uid}_{makeuptaskData.tableId}_pot", 0);
                        if (days == DateTime.Today.Day)
                        {
                            continue;
                        }

                        PlayerPrefs.SetInt($"days_{LoginKit.Instance.LoginModel.Uid}_{makeuptaskData.tableId}_pot", DateTime.Today.Day);
                        var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0],
                            common.inlineLoginDown[1]);
                        //如果登录减少人数大于配置的阈值，则不能减少排名了
                        // Debug.Log($"登录累计增加的排名为：{makeuptaskData.loginSpeedNum} 阈值为：{redeemVOModel.Login_Limit_times}");
                        if (makeuptaskData.loginSpeedNum > redeemVOModel.Login_Limit_times)
                        {
                            makeuptaskData.loginSpeedNum = redeemVOModel.Login_Limit_times;
                            continue;
                        }
                        if (makeuptaskData.loginSpeedNum + loginNum > redeemVOModel.Login_Limit_times) loginNum = redeemVOModel.Login_Limit_times - makeuptaskData.loginSpeedNum;
                        makeuptaskData.loginSpeedNum += loginNum;
                        //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 && DataMgr.MakeupTaskHistory.Value.Count > 0)
            {
                foreach (var makeuptaskData in DataMgr.MakeupTaskHistory.Value)
                {
                    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}");


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

                        if (makeuptaskData.WatchVideoSpeedNum + dowmNum > redeemVOModel.AD_Limit_times) dowmNum = redeemVOModel.AD_Limit_times - makeuptaskData.WatchVideoSpeedNum;

                        Debug.Log($"订单为： {makeuptaskData.tableId} 通过看广告减少的排名为：{dowmNum}");
                        makeuptaskData.WatchVideoSpeedNum += 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}");

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


            var lastId = -1;

            var isRepeat = DataMgr.MakeupTaskHistory.Value.Count >= makeupVOModel.DataList.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.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 = DataMgr.MakeupTaskHistory.Value.Count + 1;
                        makeupTaskData.amountStr = $"{GameHelper.Get101Str(makeupVo.item_need)}";
                        makeupTaskData.amount = makeupVo.item_need;
                        makeupTaskData.orderID = GameHelper.GetRandomNum(8);

                        DataMgr.MakeupTaskHistory.Value.Add(makeupTaskData);
                        if ((GameHelper.isRDExchangeMode() && SaveData.GetSaveObject().ExchangeProcessMode == 1) || (!GameHelper.isRDExchangeMode() && SaveData.GetSaveObject().CHProcessMode == 1)) makeupTaskData.SetStatus(MakeupTaskStatus.Level);
                        else makeupTaskData.SetStatus(MakeupTaskStatus.None);
                        DataMgr.MakeupTaskHistory.Save();

                        // DataMgr.MakeupTaskH5Time = 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(1);
            // }
        }
        private void AddWatchVideo(object obj = null)
        {
            DataMgr.VideoWatchCount.Value++;
            RankSystemMgr.Instance.addGameExp(addPointType.ads);

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

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

                var taskData = DataMgr.MakeupTaskHistory.Value.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);
                        TrackKit.SendEvent(Property.adEvent, Property.WatchAdNumber);
                        DataMgr.MakeupTaskHistory.Save();
                        PlayerPrefs.SetInt("fin_ad_num", 0);
                    }
                    else
                    {
                        if (PlayerPrefs.GetInt("fin_ad_num", 0) == 0)
                        {
                            TrackKit.SendEvent(Property.adEvent, Property.FinishAdNumber);
                            // NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.finish_ad_number, 1);
                            PlayerPrefs.SetInt("fin_ad_num", 1);
                        }

                    }
                }
                else if (taskData.status == MakeupTaskStatus.Level)
                {
                    var ExpiryUnlock = ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock;
                    taskData.LvVideoCount++;
                    if (taskData.LvVideoCount >= ExpiryUnlock)
                    {

                        taskData.LvVideoCount = 0;
                        taskData.ch_time = GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().BalanceExpired * 3600;
                    }
                    DataMgr.MakeupTaskHistory.Save();
                }
            }
            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_ch += makeupVo.ADIncrease;
                GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot);
                if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch())
                {
                    if ((SaveData.GetSaveObject().saveingpot_ch > 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.Update101Completed);
                            break;
                        case 102:
                            GameDispatcher.Instance.Dispatch(GameMsg.Update101Completed);
                            break;
                        case 111:
                            GameDispatcher.Instance.Dispatch(GameMsg.Update111Completed);
                            break;
                    }
                }
            }
            else
            {
                if (newValue)
                {
                }
            }
        }


        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 dollar = DataMgr.Coin.Value;
                        dollar += (int)rewardSingleData.GetTotalValue();

                        DataMgr.Coin.Value = dollar;
                        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;
                    }
            }
        }
    }
}
