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 System.Threading;
using IgnoreOPS;
using SGModule.Net;
using System.IO;
using Newtonsoft.Json;
using SGModule.DataStorage;
using UnityEngine.Events;
using AppsFlyerSDK;
using SGModule.NetKit;
namespace ChillConnect
{
    public static class GameHelper
    {
        public static int gameType = 0;
        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)
            {
            }

            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("Ads Not Ready", true);
                }

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

        public static void ShowInterstitial(string key)
        {
            // if (!true)
            // {
            //     return;
            // }


            //             if (Time.time < CanShowInterstitialTime)
            //             {
            //                 return;
            //             }

            //if(Random.Range(0, 100)>ConfigSystem.GetConfig<CommonModel>().interstitialtype) return;
            MaxADKit.ShowInterstitial(key, isSuccess =>
            {
                if (isSuccess)
                {
                    CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchIntVideoFinish);
                    SaveData.GetSaveObject().InterstitialPLayNum++;
                    if (SaveData.GetSaveObject().InterstitialPLayNum >= GetCommonModel().RemoveADsPackPopup)
                    {
                        SaveData.GetSaveObject().InterstitialPLayNum = 0;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open);
                    }
                    SaveData.saveDataFunc();
                    if (key == "AfterReward")
                    {

                        TrackKit.SendEvent(Property.adEvent, Property.AfterRewardAdEnd);
                    }
                    AdOverEvent(2);
                }
            });

            //             CanShowInterstitialTime = (int)(Time.time + 30);
        }
        public static void ShowOpenAd()
        {
            MaxADKit.ShowOpenAdIfReady((issuccess) =>
            {
                if (issuccess)
                {
                    GameDispatcher.Instance.Dispatch(GameMsg.CloseMask);
                    TrackKit.SendEvent(Property.adEvent, Property.open_show);
                    TrackKit.SendEvent(Property.adEvent, Property.open_show_people);
                    SaveData.GetSaveObject().TodayOpenNum[1]++;
                    SaveData.saveDataFunc();
                    AdOverEvent(3);
                }
            });
        }

        public static bool NeedShowOpenAd()
        {
            int open_ = PlayerPrefs.GetInt("OpenAD", 1);
            PlayerPrefs.SetInt("OpenAD", GetCommonModel().SplashSwitch);
            if (open_ == 0) return false;
            if (JsonConvert.SerializeObject(SaveData.GetSaveObject()) == null) return false;
            Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<AppOpenAdModel>().DataList));
            Debug.Log(ConfigSystem.GetConfig<AppOpenAdModel>().DataList.Count);
            if (SaveData.GetSaveObject().first_login_time == 0) SaveData.GetSaveObject().first_login_time = GameHelper.GetNowTime();
            DateTime startTime = DateTimeOffset.FromUnixTimeSeconds(SaveData.GetSaveObject().first_login_time).LocalDateTime;
            // DateTime startTime = DateTimeOffset.FromUnixTimeSeconds(1755591905).LocalDateTime;
            long timestamp = GameHelper.GetNowTime();
            DateTime now = DateTimeOffset.FromUnixTimeSeconds(timestamp).LocalDateTime;
            int daysPassed = (now.Date - startTime.Date).Days;
            int list_index = daysPassed;
            Debug.Log(list_index);
            if (PlayerPrefs.GetInt("first_openad", 0) == 0)
            {
                SplashAD data_ = ConfigSystem.GetConfig<AppOpenAdModel>().DataList[0];
                PlayerPrefs.SetInt("first_openad", 1);
                if (data_.upperlimit > 0)
                {
                    if (Random.Range(0, 100) < data_.Retention_Rate)
                    {
                        return true;
                    }
                }
            }
            else
            {
                list_index++;
                if (list_index >= ConfigSystem.GetConfig<AppOpenAdModel>().DataList.Count) list_index = ConfigSystem.GetConfig<AppOpenAdModel>().DataList.Count - 1;
                SplashAD data_ = ConfigSystem.GetConfig<AppOpenAdModel>().DataList[list_index];
                if (list_index < 0) list_index = 0;
                if (daysPassed != SaveData.GetSaveObject().TodayOpenNum[0])
                {
                    SaveData.GetSaveObject().TodayOpenNum[0] = daysPassed;
                    SaveData.GetSaveObject().TodayOpenNum[1] = 0;
                }
                if (SaveData.GetSaveObject().TodayOpenNum[1] < data_.upperlimit)
                {
                    if (Random.Range(0, 100) < data_.Retention_Rate)
                    {
                        SaveData.saveDataFunc();
                        return true;
                    }
                }
            }


            return false;
        }

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

            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 ??= "Captain";


            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 true;//zhushi
            return false;//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.GetConfig<CommonModel>();
        }

        public static string Get102Str(decimal currency102 = -1)
        {
            if (currency102 == -1)
            {
                currency102 = DataMgr.Ticket.Value;
            }

            if (IsGiftSwitch())
            {
                if (isRDExchangeMode())
                {
                    return $"{currency102:N}";
                }
                else
                {
                    return $"${currency102:N}";
                }
            }
            else
            {
                currency102 = (int)currency102;
                return $"{currency102:N0}";
            }
        }

        public static string Get101Str(decimal currency)
        {
            return $"{currency:N0}";
        }

        public static string getChString(decimal ch)
        {
            if (GameHelper.isRDExchangeMode()&&GameHelper.IsGiftSwitch())
            {
                string str = "<img src='ui://o9974uc5qbo98'/>";
                return str + $" {ch:N0}";
            }
            else
            {
                return $"${ch:N}";
            }
        }

        public static string getChNumber(decimal ch)
        {
            return $"{ch:N}";
        }

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

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

        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 body = "";
            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 string GetCurrCountry()
        {
            var loginModel = GetLoginModel();
            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 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 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<SmallrewardNumModel>().DataList;
                    SmallrewardNum rewardNumVo = vos[currentIndex];
                    return GetValue(rewardNumVo, currentRedeemLevel);
                }
                else if (type == 1)
                {
                    var vos = ConfigSystem.GetConfig<LargerewardNumModel>().DataList;
                    LargerewardNum rewardNumVo = vos[currentIndex];
                    return GetValue(rewardNumVo, currentRedeemLevel);
                }
                else if (type == 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.ch_1,
                        2 => rewardNumVo.ch_2,
                        3 => rewardNumVo.ch_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;
            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()
        {
            // look_interad_numbers++;

            // if (SaveData.GetSaveObject().is_get_removead && GameHelper.IsGiftSwitch())
            // {
            //     int cd = SaveData.GetSaveObject().remove_ad_time - Convert.ToInt32(GameHelper.GetNowTime());
            //     if (cd < 0)
            //     {
            //         SaveData.GetSaveObject().is_get_removead = false;
            //         SaveData.GetSaveObject().remove_ad_time = 0;
            //     }
            // }

            // if (!SaveData.GetSaveObject().is_get_removead &&
            //     look_interad_numbers >= ConfigSystem.GetConfig<CommonModel>().playtimes)
            // {
            //     look_interad_numbers = 0;
            //     int times = ConfigSystem.GetConfig<CommonModel>().interstitialtype;
            //     if (Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().interstitialtype)
            //     {
            //         if (UIManager.Instance.IsExistUI(UIConst.H5UI))
            //         {
            //             GameHelper.ShowInterstitial("interstitial_gameend");
            //         }
            //         else
            //         {
            //             UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Open);
            //         }
            //     }
            // }
            look_interad_numbers++;
            if (!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)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Open);
                }
            }
        }

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

        public static int GetItemNumber(int type)
        {
            if (type == 0)
            {
                // return PlayerPrefs.GetInt("_out", 0);
                return SaveData.GetSaveObject().OutPropNum;
            }
            else if (type == 1)
            {
                // return PlayerPrefs.GetInt("_back", 0);
                return SaveData.GetSaveObject().BackPropNum;
            }
            else if (type == 2)
            {
                // return PlayerPrefs.GetInt("_refresh", 0);
                return SaveData.GetSaveObject().RefreshPropNum;
            }


            return 0;
        }

        public static void SetItemNumber(int type, int value)
        {
            if (type == 0)
            {
                // PlayerPrefs.SetInt("_out", value);
                SaveData.GetSaveObject().OutPropNum = value;
            }
            else if (type == 1)
            {
                // PlayerPrefs.SetInt("_back", value);
                SaveData.GetSaveObject().BackPropNum = value;
            }
            else if (type == 2)
            {
                // PlayerPrefs.SetInt("_refresh", value);
                SaveData.GetSaveObject().RefreshPropNum = value;
            }
        }

        public static void AddItemNumber(int type, int change)
        {
            if (type == 0)
            {
                // PlayerPrefs.SetInt("_out", PlayerPrefs.GetInt("_out", 0) + change);
                SaveData.GetSaveObject().OutPropNum += change;
            }
            else if (type == 1)
            {
                // PlayerPrefs.SetInt("_back", PlayerPrefs.GetInt("_back", 0) + change);
                SaveData.GetSaveObject().BackPropNum += change;
            }
            else if (type == 2)
            {
                // PlayerPrefs.SetInt("_refresh", PlayerPrefs.GetInt("_refresh", 0) + change);
                SaveData.GetSaveObject().RefreshPropNum += change;
            }
        }

        public static int GetLevel()
        {
            // return 20;//zhushi
            return SaveData.GetSaveObject().LevelNum;
        }

        public static void SetLevel(int level)
        {
            // PlayerPrefs.SetInt("_level", level);
            SaveData.GetSaveObject().LevelNum = level;
        }

        public static int GetLevelstate()
        {
            // return PlayerPrefs.GetInt("_lvstate", 3); //4种，数字3为可以用广告和金币复活，2为只能用广告，1为只能用金币。0为不能复活
            return SaveData.GetSaveObject().LevelState;
        }

        public static void SetLevelstate(int state)
        {
            // PlayerPrefs.SetInt("_lvstate", state);
            SaveData.GetSaveObject().LevelState = 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;
        }

        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);
            SaveData.GetSaveObject().GameDay = DateTime.Now.Day;
        }


        public static int GetGameday()
        {
            // return PlayerPrefs.GetInt("_day", 0);
            return SaveData.GetSaveObject().GameDay;
        }



        public static int GetGameExp()
        {
            // return PlayerPrefs.GetInt("_exp", 0);
            return SaveData.GetSaveObject().GameExp;
        }


        public static void AddGameExp(int change)
        {
            // PlayerPrefs.SetInt("_exp", GetGameExp() + change);
            SaveData.GetSaveObject().GameExp += change;
        }

        public static void ResetGameExp()
        {
            // PlayerPrefs.SetInt("_exp", 0);
            SaveData.GetSaveObject().GameExp = 0;
        }

        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)
                {
                    return i;
                }
            }

            return list.Count;
        }

        public static bool IsPassMax()
        {
            int exp = GetGameExp();
            List<Passportrewards> list = ConfigSystem.GetConfig<PassportrewardsModel>().DataList;
            if (exp >= list[list.Count - 1].Eliminating_quantity) return true;
            else return false;
        }

        public static void AddGold(int a)
        {
            DataMgr.Coin.Value += a;
            GameDispatcher.Instance.Dispatch(GameMsg.Update101Completed);
        }

        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 = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);
            int lv = vo.id;
            int a = SaveData.GetSaveObject().ChLv;//PlayerPrefs.GetInt("cash_lv", 0);
            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()
        {
            //  if (!GameHelper.IsGiftSwitch())
            return;
            var isGet = SaveData.GetSaveObject().IsGetFirstReward;
            if (loginModel.NewPlayer || !isGet)
            {
                GameHelper.GetLoginModel().NewPlayer = false;
                if (GameHelper.IsGiftSwitch())
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.FirstRewardUI_Open);
                }
                // else {
                //     PlayerPrefs.SetInt("FirstReward", 1);
                //     AddGoldNumber(50);
                // }
            }
        }

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

        public static void SendRevenueToAF(string purch_number)
        {
            // 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);

            // AppsFlyer.sendEvent("af_purchase", adCallbackInfo);

            // Debug.Log($"AppsFlyer sendEvent af_purchase {purch_number}");
        }

        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, (response) =>
            {
                // Debug.Log($"barry adWatchOver========={isSuccess}");
            });
        }
        public static void AdOverRevenueEvent(int type, float revenue)
        {
            RespAdRevenueEventData respData = new RespAdRevenueEventData()
            {
                type = type,
                revenue = revenue
            };
            NetKit.Instance.Post<RespAdEventData>("event/adRevenue", respData);
        }
        /// <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, (response) =>
            {
                // 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()
        {
            return true;
            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) =>
            {
                // Debug.Log($"barry RequestGameConfig isSuccess===={isSuccess}");
                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()
        {
            var isAd = GetLoginModel().Enwp != 1;
            // return true;//zhushi

            return isAd;
        }

        public static List<int> makeupLevels = new();

        public static void SetLevelsList()
        {
            makeupLevels.Clear();
            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()
        {
            SetLevelsList();
            bool isShow = false;
            for (int i = 0; i < makeupLevels.Count; i++)
            {
                Debug.Log(makeupLevels[i]);
                if (IsGiftSwitch() && GetLevel() == makeupLevels[i])
                {
                    isShow = true;
                    break;
                }
            }

            return isShow;
        }

        public static long getNowTimeByMillisecond()
        {
#if !GAME_RELEASE
            return DateTimeManager.Instance.GetCurrTimesTampByMillisecond();
            // return DateTimeManager.Instance.GetServerCurrTimestamp();
#else
            return DateTimeManager.Instance.GetServerCurrTimestampByMillisecond();
#endif
        }

        public static void SendRevenueToServer(string eventname, string eventproperty, int integer)
        {
            TrackKit.SendEvent(eventname, eventproperty, integer);
        }
        public static string getDesByKey(string key)
        {
            Debug.Log(key);
            Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig<ExchangeDesModel>().DataList));
            if (isRDExchangeMode())
            {
                string str = ConfigSystem.GetConfig<ExchangeDesModel>().DataList.FirstOrDefault(data => data.des_key == key)?.Mode_1 ?? "";
                if (str != "")
                {
                    str = str.Replace("<img1>", "<img src='ui://o9974uc5qbo98'/>")
                            .Replace("<img2>", "<img src='ui://o9974uc5t9w7c3'/>");
                }
                return str;
            }
            else
            {
                return ConfigSystem.GetConfig<ExchangeDesModel>().DataList.FirstOrDefault(data => data.des_key == key)?.Mode_0 ?? "";
            }
        }
        public static bool isRDExchangeMode()
        {
            return true;  //zhushi
            return SaveData.GetSaveObject().ExchangeModeToggle == 1;
        }
        private static HashSet<string> generatedKeys = new HashSet<string>();
        public static string GenerateUniqueKey()
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

            string key;
            do
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(GenerateRandomString(chars, 4));
                sb.Append("-");
                sb.Append(GenerateRandomString(chars, 6));
                sb.Append("-");
                sb.Append(GenerateRandomString(chars, 4));

                key = sb.ToString();
            } while (generatedKeys.Contains(key)); // 如果重复就重新生成

            generatedKeys.Add(key); // 添加到集合中
            return key;
        }
        static string GenerateRandomString(string charSet, int length)
        {
            StringBuilder sb = new StringBuilder();
            System.Random random = new System.Random();
            for (int i = 0; i < length; i++)
            {
                int index = random.Next(charSet.Length);
                sb.Append(charSet[index]);
            }
            return sb.ToString();
        }
        public static string getPrice(decimal ch)
        {
            return $"${ch:N}";
        }
        public static string GetPriceInt(decimal ch)
        {
            return $"${ch:N0}";
        }
        public static void CopyText(string text)
        {
#if UNITY_EDITOR_WIN || UNITY_EDITOR_OSX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX
            GUIUtility.systemCopyBuffer = text;
#elif UNITY_ANDROID
            // CopyToClipboardAndroid(text);

#elif UNITY_IOS
            BrigdeIOS.copyText(text);
#else
            Debug.LogWarning("当前平台不支持复制到剪贴板功能");
#endif
            GameHelper.ShowTips("Copy Succeed");
        }
        public static void ShowPaidPack()
        {
            if(!GameHelper.IsGiftSwitch()) return;

            if (Random.Range(0, 100) < GetCommonModel().TurnOffPackRate)
            {
                if (!SaveData.GetSaveObject().is_get_packreward)
                {
                    Debug.Log("kkkkkkkkkkkkkk2222" + GetCommonModel().TurnOffPackRate);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_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, true);
                        }
                        else
                        {
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuyslotUI_Open, true);
                        }
                    }
                    else
                    {
                        CallShowTurn();//调用事件
                    }
            }
            else
            {
                CallShowTurn();//调用事件
            }



        }
        public static void CallShowTurn()
        {
            ShowTurn += ShowTurnOffReward;
            ShowTurn?.Invoke();
            ShowTurn = null;
        }
        public static event Action ShowTurn;
        private static string jsonstr = "";

        static float showResurgence()
        {

            jsonstr = "";
            var json = DataManager.Instance.LoadData(DataKeys.LevelData, string.Empty);
            if (!string.IsNullOrEmpty(json))
            {
                jsonstr = json;
            }
            if (string.IsNullOrEmpty(jsonstr))
                return 0;
            List<List<Card_item>> card_item_list = JsonConvert.DeserializeObject<List<List<Card_item>>>(jsonstr);


            int surplus_item = 0;
            for (int i = 0; i < card_item_list.Count; i++)
            {
                for (int j = 0; j < card_item_list[i].Count; j++)
                {
                    //  if (card_item_list[i][j].sheep_card.IsDestroyed() || card_item_list[i][j].sheep_card == null) continue;
                    surplus_item++;
                }
            }

            return 1 - (float)surplus_item / (SaveData.GetSaveObject().all_card_numbers * 3);

        }
        public static void ShowTurnOffReward()
        {
            Debug.Log("chansghidakai");
            if (!UIManager.Instance.IsExistUI(UIConst.GoldRewardUI) && GameHelper.IsGiftSwitch())
            {
                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.GetConfig<CommonModel>().TurnOffRewardsRate)
                {
                    if ((SaveData.GetSaveObject().TurnOffNumbers < ConfigSystem.GetConfig<CommonModel>().TurnOffRewardslimit) && (GameHelper.GetNowTime() > SaveData.GetSaveObject().TurnOffTime))
                    {
                        SaveData.GetSaveObject().TurnOffTime = GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().TurnOffRewardsCD;
                        SaveData.GetSaveObject().TurnOffNumbers++;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GoldRewardUI_Open);
                    }
                }
                SaveData.saveDataFunc();
            }
        }

        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 == 1)
                {
                    var vos = ConfigSystem.GetConfig<LargerewardNumModel>().DataList;
                    LargerewardNum rewardNumVo = vos[currentIndex];
                    return GetBoost(rewardNumVo, currentRedeemLevel);
                }
                else if (type == 2)
                {
                    var vos = ConfigSystem.GetConfig<RewardNumModel>().DataList;
                    RewardNum rewardNumVo = vos[currentIndex];
                    return GetBoost(rewardNumVo, currentRedeemLevel);

                }

            }
            return null;
        }
        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;
        }
        public static void clearJsonData()
        {
            if (File.Exists(jsonFilePath))
            {
                File.Delete(jsonFilePath);
            }
        }
        public static string jsonFilePath = Path.Combine(Application.persistentDataPath, "RainData1.json");
        public static string getTrackEvenName()
        {
            string event_ = Property.adEvent;
            if (GetLoginModel().Enwp == 1)
            {
                int rate = GameHelper.GetCommonModel().PayRate;
                if (!GameHelper.IsGiftSwitch() || GameHelper.GetCommonModel().PayRate == 100)
                {
                    MaxPayManager.isIOSPay = true;
                }
                event_ = MaxPayManager.isIOSPay ? Property.IOS_Pay_Event : Property.MaxPayEvent;
            }
            return event_;
        }
    }
}
