using System;
using FairyGUI;
using UnityEngine;
using DG.Tweening;
using Spine.Unity;
using System.Text;
using System.Collections.Generic;
using Random = UnityEngine.Random;
using System.Text.RegularExpressions;
using System.Linq;
using AppsFlyerSDK;
using static ScrewsMaster.NetworkKit;

namespace ScrewsMaster
{
    public static class GameHelper
    {
        private static LoginModel loginModel;

        public static string GetRandomNum(int count)
        {
            var resultStr = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                resultStr.Append(Random.Range(0, 10));
            }

            return resultStr.ToString();
        }

        public static Vector3 FguiPotToUnityTrfLocalPot(Vector3 pot)
        {
            var v = Vector3.zero;
            v.x = pot.x;
            v.y = -pot.y;
            v.z = pot.z;
            return v;
        }

        public static void ShowLoading(float min = 0.2f, float max = 1f, Action onCompleted = null)
        {
            ShowLoading(Random.Range(min, max), onCompleted);
        }

        public static void ShowLoading(float time, Action onCompleted = null)
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Open);
            TimerHelper.mEasy.AddTimer(time, () =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);
                onCompleted?.Invoke();
            });
        }

        public static void ShowTips(string val, bool isLangue = false)
        {
            var valStr = val;
            if (isLangue)
            {
            }

            var tipsData = JoastData.GetTips(valStr);
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SCTipsUI_Open, tipsData);
        }

        public static string GetCurrCountry()
        {
            var loginModel = ModuleManager.Instance.GetModel(ModelConst.LoginModel) as LoginModel;
            var country = loginModel.country;
            return country.ToUpper();
        }

        public static bool CheckAccountValidly(string account)
        {
            return CheckEMailValidly(account);
        }

        public static bool CheckEMailValidly(string eMail)
        {
            if (eMail.IsNullOrWhiteSpace())
            {
                return false;
            }


            const string expression =
                @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            return Regex.IsMatch(eMail, expression);
        }

        public static bool CheckIDPhoneValidly(string phone)
        {
            if (phone.IsNullOrWhiteSpace() || phone.Length < 9 || phone.Length > 14)
            {
                return false;
            }

            const string expression =
                @"^[0-9]*$";
            return Regex.IsMatch(phone, expression);
        }

        public static void ShowVideoAd(string adId, Action<bool> onCompleted)
        {
            MaxADKit.ShowVideo(adId, isSuccess =>
            {
                if (isSuccess)
                {
                    CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchVideoFinish);
                    look_interad_numbers = 0;
                    AddAdWatchCount(1);
                    AdOverEvent(1);
                }
                else
                {
                    ShowTips("Ads Not Ready", true);
                }

                onCompleted?.Invoke(isSuccess);
            });
        }

        private static long CanShowInterstitialTime;


        public static void ShowInterstitial(string key)
        {
#if !UNITY_EDITOR
            //if(Random.Range(0, 100)>ConfigSystem.GetConfig<CommonModel>().interstitialtype) return;
            MaxADKit.ShowInterstitial(key, isSuccess =>
            {
                if (isSuccess)
                {
                    CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchIntVideoFinish);
                    Debug.Log($"ShowInterstitial key==== {key}");
                    if (key == "AfterReward")
                    {
                        NetworkKit.androidPointObject.@event = BuriedPointEvent.Apple_AD_event;
                        NetworkKit.androidPointObject.property = BuriedPointEvent.afterRewardAdEnd;
                        NetworkKit.androidPointObject.n = 1;
                        NetworkKit.PostWithHeader<AndroidPointObject>("/event/incrN", androidPointObject, (isSuccess, obj) =>
                       {
                       });
                    }
                    AdOverEvent(2);
                }
            });
#endif
        }


        public static Vector2 GetUICenterPosition(GObject gObject, bool isCenter = false)
        {
            Vector2 centerPot = Vector2.zero;
            if (!isCenter)
            {
                centerPot = gObject.size / 2;
            }

            return gObject.LocalToRoot(Vector2.zero, GRoot.inst) + centerPot;
        }

        public static void PlayFGUIFx(Transition transition, bool isReset = true,
            PlayCompleteCallback onCompleted = null)
        {
            if (isReset)
            {
                if (transition.playing)
                {
                    transition.Stop();
                }
            }

            if (!transition.playing)
            {
                transition.Play();
            }

            transition.SetCompleteEvent(onCompleted);
        }

        #region 时间判断

        public static int GetTomorrowCountTime()
        {
            var today = DateTime.Now;
            return 86400 - today.Hour * 3600 - today.Minute * 60 - today.Second;
        }


        public static long GetNowTime()
        {
            return DateTimeManager.Instance.GetServerCurrTimestamp();
        }


        public static bool InToday(long time, int offset = 0, bool isInclude = false)
        {
            DateTime oldDate = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            oldDate = oldDate.AddSeconds(time);
            oldDate = new DateTime(oldDate.Year, oldDate.Month, oldDate.Day);


            var yesterday = DateTimeManager.Instance.GetCurrDateTime().AddDays(offset);

            yesterday = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day);
            if (isInclude)
            {
                return oldDate >= yesterday;
            }

            return oldDate > yesterday;
        }

        #endregion


        public static void SetSelfAvatar(GLoader gLoader)
        {
            var avatarId = PreferencesMgr.Instance.PlayerAvatarId;
            TextureHelper.SetAvatarToLoader(avatarId, gLoader);
        }

        public static void SetSelfCountryFlag(GLoader gLoader)
        {
            SetCountryFlag(gLoader, GetLoginModel().country.ToLower());
        }


        public static void SetCountryFlag(GLoader countryFlagLoader, string country)
        {
            var sprite = LoadKit.Instance.LoadSprite("Atlas.Flag", country.ToLower());
            if (sprite == null)
            {
                sprite = LoadKit.Instance.LoadSprite("Atlas.Flag", "us");
            }

            var countryTexture = new NTexture(sprite);
            countryFlagLoader.texture = countryTexture;
        }


        public static string LimitName(string name, int length, string suffix = "...")
        {
            if (!string.IsNullOrEmpty(name) && name.Length > length)
            {
                name = name.Substring(0, length) + suffix;
            }

            return name;
        }


        public static void SetName(GTextField gTextField, bool isLimit = false, int length = 6)
        {
            var name = PreferencesMgr.Instance.PlayerName;
            if (isLimit)
            {
                name = LimitName(name, length);
            }


            gTextField.text = name;
        }

        public static long GetUID()
        {
            return GetLoginModel().uid;
        }

        public static void OnRiseUI(int itemId, UILayerType layerType = UILayerType.Highest)
        {
            var gObject = GetItemUI(itemId);
            if (gObject != null)
            {
                SetUILayer(gObject, gObject.sortingOrder + 500, layerType);
            }
        }


        public static void OnRiseUIRecover(int itemId, UILayerType layerType = UILayerType.Top)
        {
            var gObject = GetItemUI(itemId);
            if (gObject == null) return;
            SetUILayer(gObject, gObject.sortingOrder - 500, layerType);
            UIManager.Instance.ResetGObjectUILayer(gObject);
        }


        public static GComponent GetItemUI(int itemId)
        {
            GComponent gObject = null;
            switch (itemId)
            {
                case 101:
                    {
                        // if (UIManager.Instance.GetDynamicUI(UIConst.CurrencyUI) is CurrencyUI topUI)
                        // {
                        //     gObject = topUI.ui.btn_currency;
                        // }
                    }
                    break;
            }

            return gObject;
        }

        public static void SetUILayer(GObject gObject, int sortingOrder, UILayerType layerType)
        {
            gObject.sortingOrder = sortingOrder;
            UIManager.Instance.SetGObjectUILayer(layerType, gObject);
        }

        public static LoginModel GetLoginModel()
        {
            if (loginModel != null)
            {
                return loginModel;
            }

            return loginModel = ModuleManager.Instance.GetModel(ModelConst.LoginModel) as LoginModel;
        }

        public static bool IsGiftSwitch()
        {
            //is_magic == false -> A 面

            //  return true;  //zhushi
            //return false;//zhushi

            return GetLoginModel().is_magic;
        }


        public static bool IsOpenGuide()
        {
            return true;
            return false;
        }

        public static bool CheckNameValidly(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return false;
            }


            const string expression = @"^[a-zA-Z]*$";
            return Regex.IsMatch(name, expression);
        }


        public static decimal Get102()
        {
            return PreferencesMgr.Instance.Currency102;
        }


        public static void InitGalleryView(GList glist, int numItems, float duration,
            ListItemRenderer OnRendererPersonItem,
            int itemWidth)
        {
            glist.itemRenderer = OnRendererPersonItem;
            glist.numItems = numItems;

            var moveW = itemWidth * glist.numItems - glist.viewWidth;
            DOVirtual.Float(0, moveW + 300, duration, prg =>
            {
                if (prg > moveW)
                {
                    return;
                }

                glist.scrollPane.SetPosX(prg, false);
            }).SetLoops(-1);
        }

        public static SkeletonAnimation ShowFinger(GGraph target, GTweenCallback onComplete = null)
        {
            Action closeCallBack = null;
            var handSpine = FXManager.Instance.SetFx<SkeletonAnimation>(target, Fx_Type.fx_hand_pre, ref closeCallBack);
            handSpine.state.SetAnimation(0, "idle", true);
            var tweenBtn = CommonHelper.FadeIn(target);
            tweenBtn.OnComplete(onComplete);
            return handSpine;
        }

        public static void ShowGuide(int _step, Vector2 _targeSize, Vector2 _targePos, Action _onEnd = null,
            GObject _fingerGuideObj = null)
        {
            // var guideData = new GuideData()
            // {
            //     targeSize = _targeSize,
            //     targePos = _targePos,
            //     step = _step,
            //     onEnd = _onEnd,
            //     fingerGuidePos = _targePos,
            // };
            //
            // if (_fingerGuideObj != null)
            // {
            //     guideData.fingerGuidePos = GameHelper.GetUICenterPosition(_fingerGuideObj);
            // }
            //
            //
            // guideData.needMaskCloseEvent = _step == 10;
            //
            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GuideUI_Open, guideData);
            //
            // if (_step == 3)
            // {
            // }
        }

        public static CommonModel GetCommonModel()
        {
            return ConfigSystem.GetConfig<CommonModel>();
        }


        public static string Get101String(decimal currency102 = -1)
        {
            if (currency102 == -1)
            {
                currency102 = GameHelper.Get102();
            }

            if (GameHelper.IsGiftSwitch())
            {
                return $"${currency102:N}";
            }
            else
            {
                return $"{currency102:N}";
            }
        }

        public static string Get102Str(decimal currency102)
        {

            var paymentTypeVO = GetPaymentTypeVO();
            if (IsGiftSwitch())
            {
                return $"{paymentTypeVO.payicon}{currency102 * paymentTypeVO.multi:N}";
            }
            else
            {
                return $"{currency102:N}";
            }
        }

        public static string GetDeviceLanguage()
        {
            return "US";
        }

        public static bool IsContinuousSignIn()
        {
            if (PreferencesMgr.Instance.SignState.Count == 0)
            {
                return false;
            }

            if (PreferencesMgr.Instance.SignState.Count >= 7)
            {
                return false;
            }

            var tmp = PreferencesMgr.Instance.SignState[PreferencesMgr.Instance.SignState.Count - 1];
            return InToday(tmp, -1, true);
        }

        public static void OpenEmail()
        {
            var email = "";
            var common = ConfigSystem.GetConfig<CommonModel>();
            if (common != null)
            {
                email = common.contactUs;
            }

            var subject = "Contact Us";
            var body = $"My UID is [ {GetUID()} ]\n";
            var url = $"mailto:{email}?subject={subject}&body={body}";
            var uri = new Uri(url);

            OpenBrowser.OpenURL(uri.AbsoluteUri);
            GameHelper.ShowTips("Trying to call send mail...");
        }

        public static PaymentType GetPaymentTypeVO()
        {
            var isRu = GetCurrCountry().ToUpper().Equals("RU");
            var isPT = AppConst.isPt();
            var PaymentTypeModel = ConfigSystem.GetConfig<PaymentTypeModel>();
            var voList = PaymentTypeModel.dataList;
            foreach (var paymentTypeVo in voList)
            {
                if (isRu)
                {
                    if (paymentTypeVo.countryKey.Contains("RU"))
                    {
                        return paymentTypeVo;
                    }
                }
                else if (isPT)
                {
                    if (paymentTypeVo.countryKey.Contains("BR"))
                    {
                        return paymentTypeVo;
                    }
                }
                else
                {
                    if (paymentTypeVo.countryKey.Contains("US"))
                    {
                        return paymentTypeVo;
                    }
                }
            }


            return voList[0];
        }


        public static int GetPaymentMulti()
        {
            return GetPaymentTypeVO().multi;
        }


        public static decimal GetQuizMax()
        {
            return 0m;
        }

        public static int GetIsWacthAd()
        {
            return PlayerPrefs.GetInt("isWacthAd");
        }

        public static void SetIsWatchAd(int isWacthAd)
        {
            PlayerPrefs.SetInt("isWacthAd", isWacthAd);
        }

        public static int GetReviveCount()
        {
            return PlayerPrefs.GetInt("reviveCount");
        }

        public static void SetReviveCount()
        {
            int count = PlayerPrefs.GetInt("reviveCount") + 1;
            PlayerPrefs.SetInt("reviveCount", count);
        }

        public static void RestartReviveCount()
        {
            PlayerPrefs.SetInt("reviveCount", 0);
        }


        public static float[] GetRewardValue(int type)
        {
            var currentRedeemLevel = 1;

            for (var i = 0; i < PreferencesMgr.Instance.MakeupTaskHistory.Count; i++)
            {
                var task = PreferencesMgr.Instance.MakeupTaskHistory[i];

                if (task.status == MakeupTaskStatus.Inline)
                {
                    currentRedeemLevel++;
                }
            }

            Debug.Log($"GetRewardValue=====================currentRedeemLevel {currentRedeemLevel} \n type: {type}");

            if (currentRedeemLevel > 3)
            {
                currentRedeemLevel = 3;
            }

            var currentIndex = GetValueIndex(currentRedeemLevel);

            if (currentIndex != -1)
            {
                switch (type)
                {
                    case 0:
                        {
                            var vos = ConfigSystem.GetConfig<SmallrewardNumModel>().dataList;
                            SmallrewardNum rewardNumVo = vos[currentIndex];
                            return GetValue(rewardNumVo, currentRedeemLevel);
                        }
                    case 1:
                        {
                            var vos = ConfigSystem.GetConfig<LargerewardNumModel>().dataList;
                            LargerewardNum rewardNumVo = vos[currentIndex];
                            return GetValue(rewardNumVo, currentRedeemLevel);
                        }
                    case 2:
                        {
                            var vos = ConfigSystem.GetConfig<RewardNumModel>().dataList;
                            RewardNum rewardNumVo = vos[currentIndex];
                            return GetValue(rewardNumVo, currentRedeemLevel);
                        }
                }
            }
            return new float[] { 0, 0 };
        }

        private static int GetValueIndex(int index)
        {
            var cash = Get102();
            var vos = ConfigSystem.GetConfig<RewardNumModel>().dataList;

            var currentIndex = -1;
            if (cash < 0)
            {
                currentIndex = 0;
            }
            else
            {
                for (var i = 0; i < vos.Count; i++)
                {
                    var rewardNumVo = vos[i];
                    var cashArray = index switch
                    {
                        1 => rewardNumVo.cash_1,
                        2 => rewardNumVo.cash_2,
                        3 => rewardNumVo.cash_3,
                        _ => default
                    };

                    if (i < vos.Count - 1)
                    {
                        if (cash >= (decimal)cashArray[0] && cash < (decimal)cashArray[1])
                        {
                            currentIndex = i;
                            break;
                        }
                    }
                    else
                    {
                        if (cash >= (decimal)cashArray[0])
                        {
                            currentIndex = i;
                            break;
                        }
                    }
                }
            }

            return currentIndex;
        }


        private static float[] GetValue(SmallrewardNum rewardNumVo, int level)
        {

            float[] normalArray = null;
            var videoRewardRate = 0f;
            switch (level)
            {
                case 1:

                    normalArray = rewardNumVo.nor_1;
                    videoRewardRate = rewardNumVo.rv_1;

                    break;
                case 2:

                    normalArray = rewardNumVo.nor_2;
                    videoRewardRate = rewardNumVo.rv_2;
                    break;
                case 3:

                    normalArray = rewardNumVo.nor_3;
                    videoRewardRate = rewardNumVo.rv_3;

                    break;
            }
            float normalValue = Random.Range(normalArray[0], normalArray[1]);
            normalValue = (float)Math.Round(normalValue, 2);
            return new float[] { normalValue, videoRewardRate };
        }
        private static float[] GetValue(LargerewardNum rewardNumVo, int level)
        {

            float[] normalArray = null;
            var videoRewardRate = 0f;
            switch (level)
            {
                case 1:

                    normalArray = rewardNumVo.nor_1;
                    videoRewardRate = rewardNumVo.rv_1;

                    break;
                case 2:

                    normalArray = rewardNumVo.nor_2;
                    videoRewardRate = rewardNumVo.rv_2;
                    break;
                case 3:

                    normalArray = rewardNumVo.nor_3;
                    videoRewardRate = rewardNumVo.rv_3;

                    break;
            }
            float normalValue = Random.Range(normalArray[0], normalArray[1]);
            normalValue = (float)Math.Round(normalValue, 2);
            return new float[] { normalValue, videoRewardRate };
        }
        private static float[] GetValue(RewardNum rewardNumVo, int level)
        {

            float[] normalArray = null;
            var videoRewardRate = 0f;
            switch (level)
            {
                case 1:

                    normalArray = rewardNumVo.nor_1;
                    videoRewardRate = rewardNumVo.rv_1;

                    break;
                case 2:

                    normalArray = rewardNumVo.nor_2;
                    videoRewardRate = rewardNumVo.rv_2;
                    break;
                case 3:

                    normalArray = rewardNumVo.nor_3;
                    videoRewardRate = rewardNumVo.rv_3;

                    break;
            }
            float normalValue = Random.Range(normalArray[0], normalArray[1]);
            normalValue = (float)Math.Round(normalValue, 2);
            return new float[] { normalValue, videoRewardRate };
        }
        public static bool CanGuide()
        {
            return IsOpenGuide() && IsGiftSwitch() && !PreferencesMgr.Instance.IsGuideFinish;
        }


        public static decimal GetQuizRate()
        {
            return 0m;
        }


        public static decimal GetNormalRewardValue()
        {
            return 0m;
        }


        public static void GetRewardOnly(decimal value, RewardOrigin origin, GObject startGObject = null,
            GObject endGObject = null, Action<bool> onCompleted = null, decimal rate = 1)
        {
            GetReward(value, origin, startGObject, endGObject, false, false, onCompleted, rate);
        }


        public static void GetReward(decimal value, RewardOrigin origin, GObject startGObject = null,
            GObject endGObject = null,
            bool isDialog = true, bool isNeedAd = true,
            Action<bool> onCompleted = null, decimal rate = 1, decimal ctRate = 50)
        {
            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(101, value, origin)
            {
                multiRate = rate
            };


            if (startGObject != null)
            {
                rewardSingleData.startPosition = GetUICenterPosition(startGObject);
            }


            if (endGObject != null)
            {
                rewardSingleData.endPosition = GetUICenterPosition(endGObject);
            }

            rewardData.AddReward(rewardSingleData);

            if (isDialog)
            {
                rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.Dialog |
                                         RewardDisplayType.ValueChange;

                rewardData.condition = isNeedAd ? RewardCondition.AD : RewardCondition.None;
            }
            else
            {
                rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            }


            rewardData.AddCompleted(onCompleted);
            rewardData.ctRate = ctRate;
            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
        }


        public static decimal GetVideoRate()
        {
            return 0m;
        }


        public static string GetPaymentPayer()
        {
            return GetPaymentTypeVO().payer;
        }


        public static bool IsContinuousSignToday()
        {
            if (PreferencesMgr.Instance.SignState.Count == 0)
            {
                return false;
            }

            if (PreferencesMgr.Instance.SignState.Count >= 7)
            {
                return true;
            }

            var tmp = PreferencesMgr.Instance.SignState[PreferencesMgr.Instance.SignState.Count - 1];
            return InToday(tmp, 0, true);
        }

        public static decimal GetQuizRewardValue()
        {
            return 0m;
        }

        public static bool IsCTFunction()
        {
            return true;
        }

        public static int GetItemNumber(ItemEnum item)
        {
            var index = (int)item;
            var items = PreferencesMgr.Instance.Items;
            if (items.TryGetValue(index, out var num))
            {
                return num;
            }

            return 0;
        }

        public static void SetItemNumber(ItemEnum item, int value)
        {
            var index = (int)item;
            var items = PreferencesMgr.Instance.Items;
            if (items.ContainsKey(index))
            {
                items[index] = value;
            }
            else
            {
                items.Add(index, value);
            }

            PreferencesMgr.Instance.Items = items;
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshItemCount);
        }

        public static void AddItemNumber(ItemEnum type, int change)
        {
            SetItemNumber(type, GetItemNumber(type) + change);
        }

        public static bool GetPayBox1()
        {
            // return PlayerPrefs.GetInt("PayBox1", 0);
            return PreferencesMgr.Instance.PayBox1;
        }
        public static bool GetPayBox2()
        {
            // return PlayerPrefs.GetInt("PayBox2", 0);
            return PreferencesMgr.Instance.PayBox2;
        }

        public static void SetPayBox1(bool value)
        {

            // PlayerPrefs.SetInt("PayBox1", value);
            PreferencesMgr.Instance.PayBox1 = value;

        }
        public static void SetPayBox2(bool value)
        {
            PreferencesMgr.Instance.PayBox2 = value;
            // PlayerPrefs.SetInt("PayBox2", value);

        }

        public static int GetLevel()
        {
            // PlayerPrefs.GetInt("Level", 1);
            //  return 5; //zhushi
            return PreferencesMgr.Instance.GameLevel;

        }
        public static void SetLevel(int level)
        {
            PreferencesMgr.Instance.GameLevel = level;
            // PlayerPrefs.SetInt("Level", level);
        }
        public static int getLevelstate()
        {
            return PlayerPrefs.GetInt("_lvstate", 3);//4种，数字3为可以用广告和金币复活，2为只能用广告，1为只能用金币。0为不能复活
        }

        public static void setLevelstate(int state)
        {
            PlayerPrefs.SetInt("_lvstate", state);
        }

        #region 广告次数

        public static int GetAdWatchCount()
        {
            return PreferencesMgr.Instance.AdWatchCount;
        }
        public static int AddAdWatchCount(int value, bool updateExchangeTime = false)
        {
            int a = Mathf.Max(GetAdWatchCount() + value, 0);
            PreferencesMgr.Instance.AdWatchCount = a;
            GameDispatcher.Instance.Dispatch(GameMsg.AdWatchCountUpdated);

            if (updateExchangeTime)
            {
                UpdateAdRewardExchangeTime();
            }
            return a;
        }
        public static bool CheckAdWatchCount(int target)
        {
            return GetAdWatchCount() >= target;
        }

        public static void UpdateAdRewardExchangeTime()
        {
            SaveData.GetSaveobject().lastAdRewardExchangeTime = GetNowTime();
            GameDispatcher.Instance.Dispatch(GameMsg.AdRewardClaimed);
        }

        public static long GetAdRewardCooldownTime()
        {
            return SaveData.GetSaveobject().lastAdRewardExchangeTime + GetCommonModel().exchangeCD;
        }

        public static bool InAdRewardCooldown()
        {
            if (SaveData.GetSaveobject().lastAdRewardExchangeTime == 0)
            {
                return false;
            }

            return GetAdRewardCooldownTime() > GetNowTime();
        }

        #endregion

        public static int GetGoldNumber()
        {
            // return PlayerPrefs.GetInt("_gold", 10000);
            return PreferencesMgr.Instance.TotalCoins;
        }
        public static int AddGoldNumber(int value)
        {
            int a = Mathf.Max(GetGoldNumber() + value, 0);
            PreferencesMgr.Instance.TotalCoins = a;
            // PlayerPrefs.SetInt("_gold", a);
            return a;
        }
        public static bool CheckGoldNumber(int target)
        {
            return GetGoldNumber() >= target;
        }

        public static void addGameTime()
        {
            int a = PlayerPrefs.GetInt("_time", 0) + 1;
            PlayerPrefs.SetInt("_time", a);

        }
        public static int getGameTime()
        {
            return PlayerPrefs.GetInt("_time", 0);
        }

        public static void setGameday()
        {

            PlayerPrefs.SetInt("_day", DateTime.Now.Day);

        }
        public static int getGameday()
        {
            return PlayerPrefs.GetInt("_day", 0);
        }


        public static int GetGameExp()
        {
            // PlayerPrefs.GetInt("_exp", 0);
            return PreferencesMgr.Instance.BattleExp;
        }
        public static void AddGameExp(int change)
        {
            PreferencesMgr.Instance.BattleExp += change;
            // if (PreferencesMgr.Instance.BattleExp >= _nextNeedEliminatingQuantity)
            // {
            //     GameDispatcher.Instance.Dispatch(GameMsg.BattleLevelUp);
            //     GetBattleLv();
            // }

            GameDispatcher.Instance.Dispatch(GameMsg.BattleLevelUp);
            // PlayerPrefs.SetInt("_exp", GetGameExp() + change);
        }
        public static void ResetGameExp()
        {
            PreferencesMgr.Instance.BattleExp = 0;
            // PlayerPrefs.SetInt("_exp", 0);
        }

        private static int _curBattleLv;
        private static int _nextNeedEliminatingQuantity;
        public static int GetBattleLv()
        {
            int exp = GetGameExp();
            List<Passportrewards> list = ConfigSystem.GetConfig<PassportrewardsModel>().dataList;
            for (int i = 0; i < list.Count; i++)
            {
                if (exp < list[i].Eliminating_quantity)
                {
                    _curBattleLv = i;
                    _nextNeedEliminatingQuantity = list.Count < i + 1 ? list[i + 1].Eliminating_quantity : list[i].Eliminating_quantity;
                    return i;

                }
            }
            return list.Count;
        }

        public static bool needShowLevelstate(int id = -1)
        {

            var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
            var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);
            int lv = vo.id;
            int a = PlayerPrefs.GetInt("cash_lv", 0);
            if (id != -1) lv = id + 1;
            if (a < lv)
            {
                return true;
            }

            return false;
        }
        public static void AddMoney(int a)
        {
            PreferencesMgr.Instance.Currency102 += a;

        }
        public static void AddMoney(float a)
        {
            // PreferencesMgr.Instance.Currency101 = (decimal)((float)PreferencesMgr.Instance.Currency101 + a);
            PreferencesMgr.Instance.Currency102 += (decimal)a;

        }



        public static bool showGameUI = true;

        public static int look_interad_numbers = 0;

        public static bool is_first_login = true;

        public static void AddInterAdNumber()
        {
            look_interad_numbers++;
            if (IsGiftSwitch() && look_interad_numbers >= ConfigSystem.GetConfig<CommonModel>().playtimes)
            {
                look_interad_numbers = 0;

                if (Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().interstitialtype)
                {
                    GameHelper.ShowInterstitial("interstitial_h5reward");
                }
            }
            // if (IsGiftSwitch() && !SaveData.GetSaveobject().is_get_removead && look_interad_numbers >= ConfigSystem.GetConfig<CommonModel>().playtimes)
            // {
            //     look_interad_numbers = 0;

            //     if (Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().interstitialtype)
            //     {
            //         if (UIManager.Instance.IsExistUI(UIConst.H5UI))
            //             GameHelper.ShowInterstitial("interstitial_h5reward");
            //         else
            //             UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Open);
            //     }
            // }
        }

        public static Dictionary<string, bool> statusDic = new Dictionary<string, bool>();
        public static Dictionary<string, Dictionary<string, bool>> statusDic2 = new Dictionary<string, Dictionary<string, bool>>();

        public static string trace_id;
        public static void PostFunnelLogin(string str, bool payload = false)
        {
            Debug.Log(str);
            if (statusDic.TryGetValue(str, out var status))
            {
                if (status)
                {
                    return;
                }
            }

            if (str == "bootstrap")
            {
                long timestamp = DateTime.Now.ToUniversalTime().Ticks - 621355968000000000;
                trace_id = timestamp.ToString();
            }
            long user_id = 0;
            if (loginModel != null && loginModel.uid != 0) user_id = loginModel.uid;
            string play_object = "";
            if (str == "afRecv" || str == "loginRecv")
            {
                play_object = payload ? "success" : "fail";
            }

            var requestData = new
            {
                uid = user_id,
                trace_id = trace_id,
                device_id = SystemInfo.deviceUniqueIdentifier,
                pack_name = NetworkManager.packName,
                version = Application.version,
                channel = SuperApplication.Instance.attribution,
                type = str,
                payload = play_object
            };
            statusDic.Add(str, true);
            NetworkKit.Post<RespLoginFunnelData>("event/funnelLogin", requestData, (isSuccess, data) =>
            {

            });
        }

        public static void SendLogToServer(string message, string stacktrace, LogType type)
        {
            // 如果只需要日期部分，可以使用ToShortDateString()或ToString("yyyy-MM-dd")等进行格式化
            if (!GameHelper.GetLoginModel().debug_log) return;
            System.DateTime currentDate = System.DateTime.Now;
            var formattedDate = currentDate.ToString("yyyy_MM_dd_HH_mm");
            var md5Str = MD5Kit.GetStringMD5(message + stacktrace);
            if (!statusDic2.ContainsKey(formattedDate))
            {
                statusDic2.Add(formattedDate, new Dictionary<string, bool>());
            }
            if (!statusDic2[formattedDate].ContainsKey(md5Str))
            {
                statusDic2[formattedDate].Add(md5Str, false);
            }
            //Debug.Log($"SendLogToServer requestData========={formattedDate} \nmd5Str=== {md5Str}");
            if (statusDic2[formattedDate][md5Str])
            {
                return;
            }
            long user_id = 0;
            if (loginModel != null && loginModel.uid != 0) user_id = loginModel.uid;
            var requestData = new
            {
                uid = user_id,
                device = SystemInfo.deviceModel,
                os_ver = SystemInfo.operatingSystem,
                network = GetNetworkType(),
                device_id = SystemInfo.deviceUniqueIdentifier,
                pack_name = NetworkManager.packName,
                version = Application.version,
                channel = SuperApplication.Instance.attribution,
                level = type == 0 ? "error" : "warn",
                message = message,
                stacktrace = stacktrace
            };
            statusDic2[formattedDate][md5Str] = true;
            //  Debug.Log($"SendLogToServer requestData1========={JsonConvert.SerializeObject(requestData)}");
            // NetworkKit.Post<orderData>("event/cliDebugLog", requestData, (isSuccess, data) =>
            //  {

            //  });
        }
        private static string GetNetworkType()
        {
            string types = "Not Connected";
            switch (Application.internetReachability)
            {
                case NetworkReachability.ReachableViaCarrierDataNetwork:
                    types = "Mobile Data";
                    break;
                case NetworkReachability.ReachableViaLocalAreaNetwork:
                    types = "Wi-Fi";
                    break;
            }
            return types;
        }


        private static GameObject SheepPlayUI;

        public static void ShowSheepPlayUI(bool isShow)
        {
            if (SheepPlayUI == null)
            {
                SheepPlayUI = GameObject.Find("(SheepPlayUI)sheep_play");
            }
            if (SheepPlayUI != null)
            {

                SheepPlayUI.transform.localPosition = isShow ? new Vector3(0, 0, 0) : new Vector3(-2000, 0, 0);
            }
        }

        //获取当前时间戳,精确到秒的时间戳
        public static long GetCurrentTimestamp()
        {
            // 获取当前UTC时间
            DateTime now = DateTime.UtcNow;
            // 计算从1970年1月1日00:00:00到现在的总秒数
            long timestamp = (long)(now - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
            return timestamp;
        }

        public static bool IsTemporaryEnd;

        public static void SendErrorToServer(string error, string stackTrace)
        {
            var reqData = new RespDebugData
            {
                level = "error",
                message = error,
                stacktrace = stackTrace
            };
            NetworkKit.SendLogToServer(reqData);
        }

        public static Dictionary<string, string> adCallbackInfo = new Dictionary<string, string>();
        public static void sendHighRevenueToAF()
        {
            float purch_number = GameHelper.GetCommonModel().afSendNum;
            string countryCode = "USD";
            adCallbackInfo.Clear();
            adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId());
            adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().uid.ToString());
            adCallbackInfo.Add("af_currency", countryCode);
            adCallbackInfo.Add("af_revenue", purch_number.ToString());

            AppsFlyer.sendEvent("af_new_purchase", adCallbackInfo);

            Debug.Log($"AppsFlyer sendEvent af_new_purchase {purch_number}");
        }
        public static List<int> makeupLevels = new();
        public static void SetLevelsList()
        {

            List<Makeup> makeup_list = ConfigSystem.GetConfig<MakeupModel>().dataList;
            for (int i = 0; i < makeup_list.Count; i++)
            {
                makeupLevels.Add(makeup_list[i].levels_need);
            }
            // Debug.Log($"barry makeupLevels-======== {SerializeUtil.ToJson(makeupLevels)}");
        }

        public static bool IsShowLevelTips()
        {
            GameHelper.SetLevelsList();
            bool isShow = false;
            for (int i = 0; i < makeupLevels.Count; i++)
            {
                if (IsGiftSwitch() && GetLevel() == makeupLevels[i])
                {
                    isShow = true;
                    break;
                }

            }

            return isShow;
        }
        public static long getNowTimeByMillisecond()
        {
#if !JarvisRelease
            return DateTimeManager.Instance.GetCurrTimesTampByMillisecond();
            // return DateTimeManager.Instance.GetServerCurrTimestamp();
#else
                return DateTimeManager.Instance.GetServerCurrTimestampByMillisecond();
#endif
        }
        public static void sendRevenueToServer(string eventname, string eventproperty, int integer)
        {
            NetworkKit.BuriedPoint(eventname, eventproperty, integer);
        }
        public static bool IsAdModelOfPay()
        {
            bool isAd = true;

            if (GetLoginModel().enwp == 1)
            {
                isAd = false;
            }
            return true;//zhushi
            // return false;//zhushi
            return isAd;
        }

        private static int m_gameTimes = 0;
        public static void PlayGameTimeEvent(int gameType, Action action = null)
        {
            m_gameTimes = GetPlayGameTimes();

            if (m_gameTimes == 0)
            {
                action?.Invoke();
                return;
            }
            ;
            RespGameTimeEventData respData = new RespGameTimeEventData()
            {
                type = gameType,
                second = m_gameTimes
            };

            m_gameTimes = 0;

            PlayerPrefs.SetInt("game_times", m_gameTimes);
            Debug.Log("fasongshichang");
            NetworkKit.PostWithHeader<RespGameTimeEventData>("event/gameTime", respData, (isSuccess, obj) =>
            {
                Debug.Log($"PlayGameTimeEvent==== {m_gameTimes}");
                action?.Invoke();
            });
        }
        public static int GetPlayGameTimes()
        {
            return PlayerPrefs.GetInt("game_times", 0);
        }
        public static void SetGameTimes()
        {
            m_gameTimes++;
            PlayerPrefs.SetInt("game_times", m_gameTimes);
        }
        public static int conf_num = 1;
        /// <summary>
        /// 玩法调控，请求配置
        /// </summary>
        public static void RequestGameConfig()
        {
            NetworkKit.PostWithHeader<ResGameConfigData>("game/regulate", null, (isSuccess, obj) =>
            {
                if (isSuccess)
                {
                    Debug.Log($"RequestGameConfig==== {obj.conf_num}");
                    PlayerPrefs.SetInt("game_conf_num", obj.conf_num);
                    ShowScrews.Instance.InitAllLeveData();
                    conf_num = obj.conf_num;
                }

                isCanCloseResultView = true;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);
            });
        }
        private static bool isCanCloseResultView = false;

        public static bool GetCloseResult()
        {
            return isCanCloseResultView;
        }
        public static void SetCloseResult(bool isCan)
        {
            isCanCloseResultView = isCan;
        }
        public static void AdOverEvent(int type)
        {

            RespAdEventData respData = new RespAdEventData()
            {
                type = type
            };

            NetworkKit.PostWithHeader<RespAdEventData>("event/adWatchOver", respData, (isSuccess, obj) =>
            {

            });
        }
    }
}
public class ResGameConfigData
{
    public int conf_num;
}
public class RespGameTimeEventData
{
    public int type;
    public int second;
}
public class RespAdEventData
{
    public int type;
}
