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 RedHotRoast;
using SGModule.Net;
using SGModule.NetKit;
using System.Reflection;
using System.Globalization;
using SGModule.Common.Extensions;

namespace RedHotRoast
{
    public static class GameHelper
    {
        public static int gameType = 0;
        public static bool isVipUnlock = false;
        private static LoginModel loginModel;
        private static Dictionary<float, string> numDic = new Dictionary<float, string>();


        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 string GetNumStr(float num, int floatLength = -1)
        {
            var numString = num.ToString(floatLength < 0 ? "" : $"f{floatLength}");
            if (num > 1000)
            {
                return numString;
            }

            if (!numDic.ContainsKey(num))
                numDic.Add(num, numString);
            return numDic[num];
        }

        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)
            {
                valStr = Language.GetContent(val);
            }

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

        public static void ShowVideoAd(string adId, Action<bool> onCompleted)
        {
            MaxADKit.ShowVideo(adId, isSuccess =>
            {
                if (isSuccess)
                {
                    CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchVideoFinish);
                    look_interad_numbers = 0;

                    AdOverEvent(1);
                }
                else
                {
                    ShowTips("not_ads", true);
                }

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

        public static void ShowInterstitial(string key)
        {
            if (GetVipPrivilege(Subscription.RemoveInterstitialAd.As<int>())) return;
            MaxADKit.ShowInterstitial(key, isSuccess =>
            {
                if (isSuccess)
                {
                    SaveData.GetSaveObject().InterstitialPLayNum++;
                    if (SaveData.GetSaveObject().InterstitialPLayNum >= GetCommonModel().RemoveADsPackPopup)
                    {
                        SaveData.GetSaveObject().InterstitialPLayNum = 0;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open, true);
                    }
                    SaveData.SaveDataFunc();
                    CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchIntVideoFinish);

                    if (key == "AfterReward")
                    {
                        TrackKit.SendEvent(ADEventTrack.Event, ADEventTrack.Property.afterRewardAdEnd);
                    }
                    AdOverEvent(2);
                }
            });

            //             CanShowInterstitialTime = (int)(Time.time + 30);
        }


        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(bool isFix = false)
        {
#if GAME_RELEASE
            return DateTimeManager.Instance.GetServerCurrTimestamp(isFix);
#else
            return DateTimeManager.Instance.GetCurrTimestamp();
#endif
        }


        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, int avatarId = 0)
        {

            // var avatarId = DataMgr.PlayerAvatarId.Value;
            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, string name = "", bool isLimit = false, int length = 6)
        {
            if (name == null || name.IsNullOrWhiteSpace())
            {
                name = "LoveLegend";
            }

            if (isLimit)
            {
                name = LimitName(name, length);
            }

            gTextField.text = name;
        }

        public static string GetUserName()
        {
            string name = DataMgr.PlayerName.Value;
            if (name == null || name.IsNullOrWhiteSpace())
            {
                name = GetPlayerInviteCode();
            }

            name ??= "LoveLegend";


            return name;
        }

        public static string GetPlayerInviteCode()
        {
            return GetLoginModel().InviteCode;
        }

        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 = LoginKit.Instance.LoginModel;
        }

        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 bool IsGiftSwitch()
        {
            //is debug test--------


            // return false;
            return true;  //zhushi

            return GetLoginModel().IsMagic;
        }

        public static decimal Get101()
        {
            return DataMgr.Coin.Value;
        }
        public static decimal Get102()
        {
            return DataMgr.Ticket.Value;
        }

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

        /// <summary>
        /// 价格字符串
        /// </summary>
        /// <param name="currency">价格</param>
        /// <returns></returns>
        public static string Get102Str(decimal currency)
        {
            var exchangeRateVO = GetExchangeRateVO();
            decimal price = currency * (decimal)exchangeRateVO.Multi;
            return $"{exchangeRateVO.Payicon}{price:N}";
        }

        /// <summary>
        /// 金币/AD 字符串
        /// </summary>
        /// <param name="currency"></param>
        /// <returns></returns>
        public static string Get101Str(decimal currency = -1)
        {
            if (currency == -1)
            {
                currency = DataMgr.Coin.Value;
            }

            return $"{currency:N0}";
        }

        public static string getPrice(decimal ch)
        {
            var exchangeRateVO = GetExchangeRateVO();
            decimal price = ch * (decimal)exchangeRateVO.Multi;
            return $"{exchangeRateVO.Payicon}{price:N}";
        }


        public static string ChooseCurrency()
        {
            var exchangeRateVO = GetExchangeRateVO();
            return exchangeRateVO.Payicon;
        }

        public static ExchangeRate GetExchangeRateVO()
        {
            var code = GetCurrCountry();
            var voList = ConfigSystem.GetConfig<ExchangeRate>();
            foreach (var ExchangeRateVo in voList)
            {
                if (ExchangeRateVo.CountryKey.Contains(code))
                {
                    return ExchangeRateVo;
                }
            }
            return voList[0];
        }

        public static float GetExchangeRateMulti()
        {
            return GetExchangeRateVO().Multi;
        }

        public static string GetCurrCountry()
        {
            // var loginData = GetLoginModel();
            // var country = loginData.Country;
            // return country.ToUpper();
            string countryCode = "US";
            try
            {
                countryCode = RegionInfo.CurrentRegion.TwoLetterISORegionName;
                Debug.Log("国家代码: " + countryCode); // 例如：US, CN, JP, DE 等
            }
            catch (System.Exception e)
            {
                Debug.LogError("无法获取国家代码: " + e.Message);
            }
            return countryCode.ToUpper();
        }


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

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

        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 IsContinuousSignIn()
        {
            if (DataMgr.SignState.Value.Count == 0)
            {
                return false;
            }

            if (DataMgr.SignState.Value.Count >= 7)
            {
                return false;
            }

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


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

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

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

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

            var currentIndex = GetValueIndex(currentRmLevel);

            if (currentIndex != -1)
            {
                if (type == 0)
                {
                    var vos = ConfigSystem.GetConfig<SmallrewardNum>();
                    SmallrewardNum rewardNumVo = vos[currentIndex];
                    return GetValue(rewardNumVo, currentRmLevel);

                }
                else if (type == 1)
                {
                    var vos = ConfigSystem.GetConfig<LargerewardNum>();
                    LargerewardNum rewardNumVo = vos[currentIndex];
                    return GetValue(rewardNumVo, currentRmLevel);

                }
                else if (type == 2)
                {
                    var vos = ConfigSystem.GetConfig<RewardNum>();
                    RewardNum rewardNumVo = vos[currentIndex];
                    return GetValue(rewardNumVo, currentRmLevel);

                }

            }
            return new float[] { 0, 0 };



        }

        private static int GetValueIndex(int index)
        {
            var ch = Get101();
            var vos = ConfigSystem.GetConfig<RewardNum>();

            var currentIndex = -1;
            if (ch < 0)
            {
                currentIndex = 0;
            }
            else
            {
                for (var i = 0; i < vos.Count; i++)
                {
                    var rewardNumVo = vos[i];
                    var chArray = index switch
                    {
                        1 => rewardNumVo.ch_1,
                        2 => rewardNumVo.ch_2,
                        3 => rewardNumVo.ch_3,
                        _ => default
                    };

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

            return currentIndex;
        }


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

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

                    normalArray = rewardNumVo.nor_1;
                    videoRewardRate = rewardNumVo.rv_1;
                    weight_array = rewardNumVo.weight_1;
                    boost_array = rewardNumVo.Boost_1;
                    break;
                case 2:

                    normalArray = rewardNumVo.nor_2;
                    videoRewardRate = rewardNumVo.rv_2;
                    weight_array = rewardNumVo.weight_2;
                    boost_array = rewardNumVo.Boost_2;
                    break;
                case 3:

                    normalArray = rewardNumVo.nor_3;
                    videoRewardRate = rewardNumVo.rv_3;
                    weight_array = rewardNumVo.weight_3;
                    boost_array = rewardNumVo.Boost_3;

                    break;
            }
            int rate_all = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                rate_all += weight_array[i];
            }
            int random_ = Random.Range(0, rate_all);
            int int_ = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                int_ += weight_array[i];
                if (random_ < int_)
                {
                    videoRewardRate = boost_array[i];
                    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;
            int[] weight_array = null;
            int[] boost_array = null;
            switch (level)
            {
                case 1:

                    normalArray = rewardNumVo.nor_1;
                    videoRewardRate = rewardNumVo.rv_1;
                    weight_array = rewardNumVo.weight_1;
                    boost_array = rewardNumVo.Boost_1;
                    break;
                case 2:
                    normalArray = rewardNumVo.nor_2;
                    videoRewardRate = rewardNumVo.rv_2;
                    weight_array = rewardNumVo.weight_2;
                    boost_array = rewardNumVo.Boost_2;
                    break;
                case 3:

                    normalArray = rewardNumVo.nor_3;
                    videoRewardRate = rewardNumVo.rv_3;
                    weight_array = rewardNumVo.weight_3;
                    boost_array = rewardNumVo.Boost_3;
                    break;
            }

            int rate_all = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                rate_all += weight_array[i];
            }
            int random_ = Random.Range(0, rate_all);
            int int_ = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                int_ += weight_array[i];
                if (random_ < int_)
                {
                    videoRewardRate = boost_array[i];
                    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;
            int[] weight_array = null;
            int[] boost_array = null;
            switch (level)
            {
                case 1:

                    normalArray = rewardNumVo.nor_1;
                    videoRewardRate = rewardNumVo.rv_1;
                    weight_array = rewardNumVo.weight_1;
                    boost_array = rewardNumVo.Boost_1;
                    break;
                case 2:

                    normalArray = rewardNumVo.nor_2;
                    videoRewardRate = rewardNumVo.rv_2;
                    weight_array = rewardNumVo.weight_2;
                    boost_array = rewardNumVo.Boost_2;
                    break;
                case 3:

                    normalArray = rewardNumVo.nor_3;
                    videoRewardRate = rewardNumVo.rv_3;
                    weight_array = rewardNumVo.weight_3;
                    boost_array = rewardNumVo.Boost_3;

                    break;
            }

            int rate_all = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                rate_all += weight_array[i];
            }
            int random_ = Random.Range(0, rate_all);
            int int_ = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                int_ += weight_array[i];
                if (random_ < int_)
                {
                    videoRewardRate = boost_array[i];
                    break;
                }
            }

            float normalValue = Random.Range(normalArray[0], normalArray[1]);
            normalValue = (float)Math.Round(normalValue, 2);
            return new float[] { normalValue, videoRewardRate };
        }

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


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



        /// <summary>
        /// 传的是初始位置的GObject对象
        /// </summary>
        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);
        }


        /// <summary>
        /// 传的是位置
        /// </summary>
        public static void GetRewardOnly1(int id, decimal value, RewardOrigin origin, Vector2 startPos,
            Vector2 endPos, Action<bool> onCompleted = null, decimal rate = 1)
        {
            GetReward1(id, value, origin, startPos, endPos, false, false, onCompleted, rate);
        }

        public static void GetReward1(int id, decimal value, RewardOrigin origin, Vector2 startPos,
            Vector2 endPos,
            bool isDialog = true, bool isNeedAd = true,
            Action<bool> onCompleted = null, decimal rate = 1, decimal ctRate = 50)
        {
            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(id, value, origin)
            {
                multiRate = rate
            };


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


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

            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 void addInterAdnumber()
        {
            
            return;
            if (GetVipPrivilege(Subscription.RemoveInterstitialAd.As<int>())) return;
            look_interad_numbers++;
            Debug.Log($"[back hall]1 SaveData.GetSaveObject().is_get_removead=========={SaveData.GetSaveObject().is_get_removead} ");

            if (!SaveData.GetSaveObject().is_get_removead && look_interad_numbers >= ConfigSystem.GetCommonConf().playtimes)
            {
                look_interad_numbers = 0;
                if (Random.Range(0, 100) < ConfigSystem.GetCommonConf().interstitialtype)
                {
                    if (UIManager.Instance.IsExistUI(UIConst.H5UI))
                    {
                        GameHelper.ShowInterstitial("interstitial_gameend");
                    }
                    else
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Open);
                    }
                }
            }
        }
        public static decimal GetVideoRate()
        {
            return 0m;
        }

        public static int GetItemNumber(int type)
        {
            return type switch
            {
                0 => DataMgr.PropRemoveNum.Value,
                1 => DataMgr.PropBackNum.Value,
                2 => DataMgr.PropRefreshNum.Value,
                _ => 0
            };
        }

        public static void SetItemNumber(int type, int value)
        {
            switch (type)
            {
                case 0:
                    DataMgr.PropRemoveNum.Value = value;
                    break;
                case 1:
                    DataMgr.PropBackNum.Value = value;
                    break;
                case 2:
                    DataMgr.PropRefreshNum.Value = value;
                    break;
            }
        }
        public static void AddItemNumber(int type, int change)
        {
            switch (type)
            {
                case 0:
                    DataMgr.PropRemoveNum.Value += change;
                    break;
                case 1:
                    DataMgr.PropBackNum.Value += change;
                    break;
                case 2:
                    DataMgr.PropRefreshNum.Value += change;
                    break;
            }
        }

        public static int GetLevel()
        {
           //   DataMgr.GameLevel.Value = 200;//zhushi
            return DataMgr.GameLevel.Value;

        }
        public static void SetLevel(int level)
        {
            DataMgr.GameLevel.Value = level;
        }
        public static int GetLevelstate()
        {
            return DataMgr.ResurrectionState.Value;//4种，数字3为可以用广告和金币复活，2为只能用广告，1为只能用金币。0为不能复活
        }

        public static void SetLevelstate(int state)
        {
            DataMgr.ResurrectionState.Value = state;
        }

        public static int GetGoldNumber()
        {
            // return PlayerPrefs.GetInt("_gold", 50);
            int goldNum = (int)Get101();

            return goldNum;
        }
        public static void AddGoldNumber(int value)
        {
            AddGold(value);
        }
        public static bool CheckGoldNumber(int target)
        {
            return GetGoldNumber() >= target;
        }

        private static int _times = 0;
        public static void AddGameTime()
        {
            if (_times >= 10)
            {
                DataMgr.GameTime.Value += _times;
                _times = 0;
            }
            _times++;
        }
        public static int GetGameTime()
        {
            return DataMgr.GameTime.Value;
        }

        public static void SetGameday()
        {
            DataMgr.GameDay.Value = DateTime.Now.Day;
        }
        public static int GetGameday()
        {
            return DataMgr.GameDay.Value;
        }


        public static int GetGameExp()
        {
            return DataMgr.GameExperience.Value;
        }
        public static void AddGameExp(int change)
        {
            DataMgr.GameExperience.Value += change;
        }
        public static void ResetGameExp()
        {
            DataMgr.GameExperience.Value = 0;
        }
        public static int GetBattleLv()
        {
            int exp = GetGameExp();
            List<Passportrewards> list = ConfigSystem.GetConfig<Passportrewards>();
            for (int i = 0; i < list.Count; i++)
            {
                if (exp < list[i].Eliminating_quantity)
                {
                    return i;

                }
            }
            return list.Count;
        }
        public static void AddGold(int a)
        {
            DataMgr.Coin.Value += a;
            GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
        }
        public static void AddGold(float a)
        {
            DataMgr.Coin.Value += (int)a;
        }
        public static bool needShowLevelstate(int id = -1)
        {

            var makeupTaskData = DataMgr.MakeupTaskHistory.Value.Last();
            var vo = MakeupModel.GetData(makeupTaskData.tableId);
            int lv = vo.id;
            int a = DataMgr.ChLevel.Value;
            if (id != -1) lv = id + 1;
            if (a < lv)
            {
                return true;
            }

            return false;
        }

        public static void addMoney(int a)
        {
            DataMgr.Ticket.Value += a;

        }
        public static void addMoney(float a)
        {
            DataMgr.Ticket.Value = (decimal)((float)DataMgr.Ticket.Value + a);

        }


        public static bool showGameUI = true;

        public static int look_interad_numbers = 0;

        public static bool is_first_login = true;

        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 SendLogToServer(string message, string stacktrace, LogType type)
        {
            // 如果只需要日期部分，可以使用ToShortDateString()或ToString("yyyy-MM-dd")等进行格式化
            if (!GameHelper.GetLoginModel().DebugLog) 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.identifier,
                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 RainPlayUI;

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

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

        public static bool IsTemporaryEnd;


        public static void IsShowFirstReward()
        {
            var isGet = DataMgr.GetFirstReaward.Value;
            if (!isGet && IsGiftSwitch())
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.FirstRewardUI_Open);
            }
        }

        public static Dictionary<string, string> adCallbackInfo = new Dictionary<string, string>();

        // public static void SendRevenueToAF(string purch_number)
        // {
        //     if (!GameHelper.IsAdModelOfPay() && !string.IsNullOrEmpty(purch_number) && decimal.TryParse(purch_number, out decimal revenue))
        //     {
        //         // Debug.Log("付费收益上报AF----------- " + revenue.ToString());
        //         // adCallbackInfo.Clear();
        //         // adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId());
        //         // adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().uid.ToString());
        //         // adCallbackInfo.Add("af_currency", "USD");
        //         // adCallbackInfo.Add("af_revenue", revenue.ToString());
        //         // AppsFlyer.sendEvent("af_purchase", adCallbackInfo);
        //
        //         GameHelper.sendRevenueToServer("af_purchase", "af_revenue", (int)(revenue * 10000));
        //     }
        // }
        // public static void sendRevenueToServer(string eventname, string eventproperty, int integer)
        // {
        //     NetworkKit.BuriedPoint(eventname, eventproperty, integer);
        // }
        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 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;
        }

        /// <summary>
        /// 检查是否有网络
        /// </summary>
        /// <returns>true：有网， false：没网 </returns>
        public static bool IsConnect()
        {
            return NetChecker.Instance.GetConnectionStatus() == ConnectionStatus.Connected;
        }

        /// <summary>
        /// 看完广告事件上报
        /// </summary>
        /// <param name="type">1:激励 2:插屏</param>
        public static void AdOverEvent(int type)
        {

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

            NetKit.Instance.Post<RespAdEventData>("event/adWatchOver", respData);
        }

        /// <summary>
        /// 看完广告收益上报
        /// </summary>
        /// <param name="type">1:激励 2:插屏</param>
        public static void AdOverRevenueEvent(int type, float revenue)
        {

            RespAdRevenueEventData respData = new RespAdRevenueEventData()
            {
                type = type,
                revenue = revenue
            };
            // Debug.Log($"[Max] AdOverRevenueEvent  --------{JsonConvert.SerializeObject(respData)} ");
            NetKit.Instance.Post<RespAdRevenueEventData>("event/adRevenue", respData, (response) =>
            {
                Debug.Log($"[Max] adRevenue  ------IsSuccess-- {response.IsSuccess} ");

            });
        }
        /// <summary>
        /// 玩法时长上报
        /// </summary>
        /// <param name="gameType">玩法类型：1:羊了个羊 2:单词接龙 3:关不住我</param>
        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);

            NetKit.Instance.Post<RespGameTimeEventData>("event/gameTime", respData, _ =>
            {
                // Debug.Log($"PlayGameTimeEvent==== {isSuccess}");
                action?.Invoke();
            });
        }
        private static int m_gameTimes = 0;

        public static void SetGameTimes()
        {
            m_gameTimes++;
            PlayerPrefs.SetInt("game_times", m_gameTimes);
        }

        public static int GetPlayGameTimes()
        {
            return PlayerPrefs.GetInt("game_times", 0);
        }


        /// <summary>
        /// 是否能关闭结算界面（必须等调控接口返回数据后才能关闭）
        /// </summary>
        private static bool isCanCloseResultView = false;

        public static bool GetCloseResult()
        {
            if (!IsConnect())
            {
                ShowTips("The network connection is abnormal.");
            }

            return isCanCloseResultView;
        }
        public static void SetCloseResult(bool isCan)
        {
            isCanCloseResultView = isCan;
        }

        /// <summary>
        /// 第几个玩法调控表
        /// </summary>
        public static int conf_num = 1;
        /// <summary>
        /// 玩法调控，请求配置
        /// </summary>
        public static void RequestGameConfig()
        {
            NetKit.Instance.Post<ResGameConfigData>("game/regulate", null, response =>
            {
                if (response.IsSuccess)
                {
                    Debug.Log($"RequestGameConfig==== {response.Data.conf_num}");
                    PlayerPrefs.SetInt("game_conf_num", response.Data.conf_num);
                    conf_num = response.Data.conf_num;
                }

                isCanCloseResultView = true;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);
            });
        }

        /// <summary>
        /// 是否是广告兑换模式
        /// </summary>
        /// <returns>true:广告兑换  -- false:三方支付</returns>
        public static bool IsAdModelOfPay()
        {
            return true;//zhushi
            var isAd = GetLoginModel().Enwp != 1;
            return isAd;
        }

        public static string GetEventName()
        {
            var name = ADEventTrack.Event;
            if (!IsAdModelOfPay())
            {
                name = ADEventTrack.MaxPayEvent;
            }
            return name;
        }
        public static List<int> makeupLevels = new();
        public static void SetLevelsList()
        {

            List<Makeup> makeupList = ConfigSystem.GetConfig<Makeup>();
            for (int i = 0; i < makeupList.Count; i++)
            {
                makeupLevels.Add(makeupList[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 OpenEmail()
        {
            string email = "";
            var common = ConfigSystem.GetCommonConf();
            if (common != null)
            {
                email = common.contactUs;
            }

            string subject = Uri.EscapeDataString("Contact Us");
            string body = Uri.EscapeDataString($"My UID is [ {GetUID()} ]\n");

            string url = $"mailto:{email}?subject={subject}&body={body}";

            try
            {
                OpenBrowser.OpenURL(url);
                GameHelper.ShowTips("try_send", true);
            }
            catch (Exception ex)
            {
                Debug.LogError("打开邮箱失败：" + ex.Message);
                GameHelper.ShowTips("send_failed", true);
            }
        }

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

            for (var i = 0; i < DataMgr.MakeupTaskHistory.Value.Count; i++)
            {
                var task = DataMgr.MakeupTaskHistory.Value[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)
            {

                if (type == 0)
                {
                    var vos = ConfigSystem.GetConfig<SmallrewardNum>();
                    SmallrewardNum rewardNumVo = vos[currentIndex];
                    return GetBoost(rewardNumVo, currentRedeemLevel);
                }
                else if (type == 1)
                {
                    var vos = ConfigSystem.GetConfig<LargerewardNum>();
                    LargerewardNum rewardNumVo = vos[currentIndex];
                    return GetBoost(rewardNumVo, currentRedeemLevel);
                }
                else if (type == 2)
                {
                    var vos = ConfigSystem.GetConfig<RewardNum>();
                    RewardNum rewardNumVo = vos[currentIndex];
                    return GetBoost(rewardNumVo, currentRedeemLevel);

                }

            }
            return null;
        }

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

            int[] boost_array = null;
            switch (level)
            {
                case 1:
                    boost_array = rewardNumVo.Boost_1;
                    break;
                case 2:
                    boost_array = rewardNumVo.Boost_2;
                    break;
                case 3:
                    boost_array = rewardNumVo.Boost_3;
                    break;
            }
            return boost_array;
        }
        private static int[] GetBoost(LargerewardNum rewardNumVo, int level)
        {

            int[] boost_array = null;
            switch (level)
            {
                case 1:
                    boost_array = rewardNumVo.Boost_1;
                    break;
                case 2:
                    boost_array = rewardNumVo.Boost_2;
                    break;
                case 3:
                    boost_array = rewardNumVo.Boost_3;
                    break;
            }
            return boost_array;
        }
        private static int[] GetBoost(RewardNum rewardNumVo, int level)
        {

            int[] boost_array = null;
            switch (level)
            {
                case 1:
                    boost_array = rewardNumVo.Boost_1;
                    break;
                case 2:
                    boost_array = rewardNumVo.Boost_2;
                    break;
                case 3:

                    boost_array = rewardNumVo.Boost_3;
                    break;
            }
            return boost_array;
        }

        /// <summary>
        /// </summary>
        /// <param name="id">1:首充礼包 2:免除广告礼包 3:通行证礼包 4:VIP订阅页面</param>
        /// <returns></returns>
        public static string GetBackgroundName(int id)
        {

            var vos = ConfigSystem.GetConfig<BackgroundImage>();
            for (int i = 0; i < vos.Count; i++)
            {
                if (vos[i].id == id)
                {
                    return vos[i].Name;
                }
            }
            return vos[0].Name;
        }

        #region VIP
        // 会员是否到期
        public static void CheckVipExpiration()
        {
            var vipExpiration = DataMgr.VipExpirationTime.Value;
            // 如果VIP等级大于0且有过期时间
            if (DataMgr.VipLevel.Value > 0 && vipExpiration > 0)
            {
                long currentTime = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds();

                // 如果当前时间超过了过期时间，则认为VIP已过期
                if (currentTime >= vipExpiration)
                {
                    // 重置VIP等级和过期时间
                    DataMgr.VipLevel.Value = -1;
                    DataMgr.VipExpirationTime.Value = 0;

                    // 可以在这里添加过期通知或其他处理逻辑
                    Debug.Log("VIP has expired");
                }
            }
        }
        public static event Action ShowTurn;
        public static void ShowPaidPack()
        {
            if (Random.Range(0, 100) < GetCommonModel().TurnOffPackRate)
            {
                if (!SaveData.GetSaveObject().is_get_packreward)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open);
                }
                else if (!SaveData.GetSaveObject().is_get_ThreeDaysGift)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);//在每个打开的界面的onclose方法中调用CallShowTurn方法
                }
                // else if (SaveData.GetSaveObject().failed_pack_time > GameHelper.GetNowTime())
                // {
                //     float progress = showResurgence();
                //     // if (string.IsNullOrWhiteSpace(jsonstr))
                //     // {
                //     //     // CallShowTurn();
                //     //     // return;
                //     // }
                //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, progress);
                // }
                else if (!SaveData.GetSaveObject().is_get_battlepass)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassViewUI_Open);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassunlockUI_Open);
                }
                else if (!SaveData.GetSaveObject().have_slot)
                {
                    // if (SaveData.GetSaveObject().addview_off_time > GameHelper.GetNowTime())
                    // {
                    //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Open);
                    // }
                    // else
                    // {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuyslotUI_Open, true);
                    // }
                }
                else
                {
                    CallShowTurn();//调用事件
                }
            }
            else
            {
                CallShowTurn();//调用事件
            }



        }
        public static void CallShowTurn()
        {
            ShowTurn += ShowTurnOffReward;
            ShowTurn?.Invoke();
            ShowTurn = null;
        }
        public static void ShowTurnOffReward()
        {
            Debug.Log("chansghidakai");
            // if (!UIManager.Instance.IsExistUI(UIConst.GoldRewardUI))
            // {
            //     if (IsTemporaryEnd) return;
            //     if (SaveData.GetSaveObject().TurnOffDay != DateTime.Now.Day)
            //     {
            //         SaveData.GetSaveObject().TurnOffDay = DateTime.Now.Day;
            //         SaveData.GetSaveObject().TurnOffNumbers = 0;
            //     }
            //     if (Random.Range(0, 100) < ConfigSystem.GetCommonConf().TurnOffRewardsRate)
            //     {
            //         if ((SaveData.GetSaveObject().TurnOffNumbers < ConfigSystem.GetCommonConf().TurnOffRewardslimit) && (GameHelper.GetNowTime() > SaveData.GetSaveObject().TurnOffTime))
            //         {
            //             SaveData.GetSaveObject().TurnOffTime = GameHelper.GetNowTime() + ConfigSystem.GetCommonConf().TurnOffRewardsCD;
            //             SaveData.GetSaveObject().TurnOffNumbers++;
            //             UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GoldRewardUI_Open);
            //         }
            //     }
            //     SaveData.SaveDataFunc();
            // }
        }
        public static bool isAutoPop = false;
        public static int GetVipLevel()
        {
            CheckVipExpiration();

            return DataMgr.VipLevel.Value;
        }

        public static bool GetVipPrivilege(int id)
        {
            Debug.Log($"GameHelp -获取VIP特权--GetVipPrivilege-  {id}");
            var level = GetVipLevel();
            if (level <= 0) return false;
            var vipClub = ConfigSystem.GetConfig<VipClub>();
            var subList = vipClub[level - 1].SubscriptionBenefits2;

            var vipPrivilege = subList.Contains(id);

            return vipPrivilege;
        }

        public static string getLanguageByKey(string key)
        {
            List<LanguageTable> list = ConfigSystem.GetConfig<LanguageTable>();
            LanguageTable item = list.FirstOrDefault(x => x.key == key);
            string code = Language.getCurrentLanguage();
            if (item == null)
            {
                Debug.LogError("Language item not found:" + key);
                return key;
            }
            FieldInfo prop = typeof(LanguageTable).GetField(code);
            if (prop != null)
            {
                string str = prop.GetValue(item).ToString();
                return str;
            }
            return item.en;
            
        }

        #endregion
        
    }
}

public enum Subscription
    {
        VipLevel = 1,
        SLVLevel,
        DoubleChestReward,
        FreeDownImage,
        DoubleLevelReward,
        RemoveInterstitialAd,
        UnlockSecret,
        UnlockLive,
        UnlockAssitant,
    }
