using System;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using FGUI.ZM_Game_04;
using Newtonsoft.Json;
using Unity.VisualScripting;
using Random = UnityEngine.Random;
using DG.Tweening;
using System.IO;
using FGUI.ZM_Common_01;
using FGUI.LG_Common;
using SGModule.Common.Extensions;
using SGModule.ConfigLoader;
using SGModule.NetKit;
using Spine.Unity;
using System.Linq;


namespace RedHotRoast
{
    public class RainPlayUI : BaseUI
    {
        private RainPlayUICtrl ctrl;
        private RainPlayModel model;
        private FGUI.ZM_Game_04.com_game ui;

        public RainPlayUI(RainPlayUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.RainPlayUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "ZM_Game_04";
            uiInfo.assetName = "com_game";
            uiInfo.layerType = UILayerType.Bottom;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = false;
        }
        private Action closeCallback;
        private readonly Action clearSpinepool;
        private static string jsonFilePath = Path.Combine(Application.persistentDataPath, "RainData1.json");
        private int width_max = 7;
        private int height_max = 6;
        private readonly float card_width = 6.8f;
        private readonly float card_height = 7.3f;

        private float real_card_width = 6.8f;  //视觉宽度
        private float real_card_height = 7.3f;  //视觉高度

        private readonly float card_width_slot = 6.45f;

        private readonly float card_scale = 5.2f;
        private readonly float card_slot_scale = 4.628f;
        private int card_type_max = 15;

        private int card_layer = 2;

        private int all_card_numbers = 0;
        public int ad_cool_down = 20;

        private int slot_max = 7;
        private int extra_max = 5;
        private Card_item last_card_item;

        // private sheep_card refresh_item;
        //private List<card_item> card_item_list = new List<card_item>();
        // private List<Vector2>[] stacked_list = new List<Vector2>();
        private List<Vector2> left_extra_list = new List<Vector2>();
        private List<Vector2> right_extra_list = new List<Vector2>();
        private List<List<Vector2>> map_list = new List<List<Vector2>>();
        private List<List<Card_item>> card_item_list = new List<List<Card_item>>();
        private List<Card_item> slot_list = new List<Card_item>();
        private List<Vector3> refresh_list = new List<Vector3>();
        private List<Card_item> out_list = new List<Card_item>();
        private List<Card_item> pool_list = new List<Card_item>();
        private string jsonstr = null;
        private float bg_x = -22.5f;
        private float bg_y = GameObject.Find("match_bg_down").transform.position.y;

        private int[] layer_array;
        private int[] type_array;
        private int[] all_array;
        public int ad_numbers = 0;
        public int ad_times = 0;

        private bool is_first_login_go_to_h5 = false;
        #region 生命周期
        protected override void OnInit()
        {

        }

        protected override void OnClose()
        {
            HallManager.Instance.UpdateSecondEvent -= upData;
            HallManager.Instance.UpdateSecondEvent -= GameHelper.AddGameTime;
            HallManager.Instance.UpdateSecondEvent -= GameHelper.SetGameTimes;
            closeCallback?.Invoke();
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_Game_04.com_game;
            //model = ModuleManager.Instance.GetModel(ModelConst.SheepPLayUIModel) as SheepPLayUIModel;

        }

        protected override void OnOpenBefore(object args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            ui.btn_add.x += 20;
            ui.btn_add.y += 15;
#endif
            if (Screen.safeArea.y != 0)
            {
                ui.group_.y += Screen.safeArea.y - 15;
            }
            GameHelper.IsShowFirstReward();
            ui.gift_switch.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0;

            CreateGoldtimeList();

            layer_array = new int[] { 19, };
            type_array = new int[] { 14, };
            all_array = new int[] { 30, };
            // SetDiffArray();

            Sprite e = Resources.Load<Sprite>("card/card_sprite/1");
            real_card_width = e.bounds.size.x * 5.2f;
            real_card_height = e.bounds.size.y * 5.2f;

            ad_times = PlayerPrefs.GetInt("ad_time", 0);
            ad_numbers = PlayerPrefs.GetInt("ad_number", 1);



            ad_cool_down = ConfigSystem.GetCommonConf().lobbyrewrdtime * 60;

            CheckFeature();
            ui.btn_head.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PersonViewUI_Open);
                GameHelper.showGameUI = false;
            });

            // ui.btn_game_menu.SetClickDownEffect(1.0f);
            ui.btn_game_menu.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open, 1);
                // OnBackToHall();
            });
            upData();
            OnChangeAvatar();
            SetName();

            HallManager.Instance.UpdateSecondEvent += GameHelper.AddGameTime;
            HallManager.Instance.UpdateSecondEvent += GameHelper.SetGameTimes;
            HallManager.Instance.UpdateSecondEvent += upData;
            LoadData();


            InitView();
            var loginModel = GameHelper.GetLoginModel();
            if (GameHelper.IsGiftSwitch() && !loginModel.NewPlayer)
            {
                //var isShow = false;
                if (is_first_login_go_to_h5)
                {

                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open);
                    GameHelper.is_first_login = false;
                }
            }
            else
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open);
                GameHelper.is_first_login = false;

            }
            if (GameHelper.GetGameday() != DateTime.Now.Day)
            {
                DataMgr.GameTime.Value = 0;
                SaveData.GetSaveObject().time_task_record = new List<int>();
                GameHelper.SetGameday();
            }

            int random_ = Random.Range(0, 100);
            // GameHelper.GetCommonModel().roomGuideRate = 100;//zhushi
            if (GameHelper.IsGiftSwitch() && random_ < GameHelper.GetCommonModel().roomGuideRate)
            {
                List<int> unlocklist = new List<int>();
                if ((GameHelper.GetCommonModel().Live == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().LivePreview) && (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockLive[1]))
                {
                    if (DataMgr.IsUnlockLive.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockLive.As<int>()))//未解锁。
                    {
                        unlocklist.Add(0);
                    }
                }
                if ((GameHelper.GetCommonModel().Secret == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().SecretPreview) && (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockSecret[1]))
                {
                    if (DataMgr.IsUnlockSecret.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockSecret.As<int>()))//未解锁。
                    {
                        unlocklist.Add(1);
                    }
                }
                if ((GameHelper.GetCommonModel().Assitant == 1) && (GameHelper.GetLevel() >= GameHelper.GetCommonModel().AssitantPreview))
                {
                    if (DataMgr.IsUnlockChat.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockAssitant.As<int>()))//未解锁。
                    {
                        unlocklist.Add(2);
                    }
                }
                if (unlocklist.Count > 0)
                {
                    if (GameHelper.IsGiftSwitch())
                    {
                        int random_index = Random.Range(0, unlocklist.Count);
                        if (unlocklist[random_index] == 0)
                        {
                            uiCtrlDispatcher.Dispatch(UICtrlMsg.LiveUnlockUI_Open);
                        }
                        else if (unlocklist[random_index] == 1)
                        {
                            uiCtrlDispatcher.Dispatch(UICtrlMsg.ScAlbumLockUI_Open);
                        }
                        else if (unlocklist[random_index] == 2)
                        {
                            uiCtrlDispatcher.Dispatch(UICtrlMsg.ChatUnlockUI_Open);
                        }
                    }
                }

            }
            // if (!GameHelper.IsGiftSwitch())
            // {
            // }
            //    LevelData = ConfigSystem.GetConfig<LevelUnlockModel>().DataList[successData_.level - 1];
            ui.btn_add.t0.Play();
            SkeletonAnimation ske_pot = FXManager.Instance.SetFx<SkeletonAnimation>((ui.btn_chat as btn_chat).ani_parent, Fx_Type.fx_btnchat, ref closeCallback);
            ske_pot.state.SetAnimation(0, "animation", true);
            ui.btn_chat.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ChatChooseUI_Open);
            });
            if (GameHelper.IsGiftSwitch() && GameHelper.GetCommonModel().Assitant == 1 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().AssitantPreview)
            {
                ui.btn_chat.visible = true;
            }
        }
        private void OnBackToHall(object obj = null)
        {
            if (!GameHelper.GetVipPrivilege(Subscription.RemoveInterstitialAd.As<int>()) && GameHelper.IsGiftSwitch())
            {
                int random_ = UnityEngine.Random.Range(1, 100);
                Debug.Log($"[back hall] SaveData.GetSaveObject().is_get_removead=========={SaveData.GetSaveObject().is_get_removead} ");
                if (!SaveData.GetSaveObject().is_get_removead && random_ < GameHelper.GetCommonModel().HomeInterstitialAd)
                {
                    //GameHelper.ShowInterstitial("BackHall");
                    // uiCtrlDispatcher.Dispatch(UICtrlMsg.AdcomingUI_Open);
                }
            }

            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] != null)
                    {
                        GameObject.Destroy(card_item_list[i][j].sheep_card);
                    }

                }
            }
            SaveJson();


            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RainPlayUI_Close);
            GameDispatcher.Instance.Dispatch(GameMsg.BackMainScene);
            CtrlCloseUI();
        }

        private int clear_nubers = 0;
        private bool main_ui_show = true;

        private void OnChangeAvatar(object obj = null)
        {
            var headId = DataMgr.PlayerAvatarId.Value;
            if (obj != null)
            {
                headId = obj.As<ChangeValue<int>>().newValue;
            }
            var head = ui.btn_head as btn_head;
            GameHelper.SetSelfAvatar(head.head.load_avatar, headId);

            if (head != null)
            {
                var vipLevel = GameHelper.GetVipLevel();
                if (vipLevel > 0)
                {
                    head.vip_loader.visible = true;
                    head.vip_loader.url = $"ui://LG_Common/vip_{vipLevel}";
                }
                else
                {
                    head.vip_loader.visible = false;
                }
                GameHelper.SetSelfAvatar(head.head.load_avatar, headId);
            }
        }
        private void OnChangeName(ChangeValue<string> obj)
        {
            SetName();
        }

        private void SetName()
        {
            // GameHelper.SetName(ui.text_name);
        }

        protected override void OnOpen(object args)
        {

        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }
        #endregion

        #region 消息
        protected override void AddListener()
        {
            PreferencesDispatcher<string>.Instance.AddListener(DataMsg.playerName, OnChangeName);
            PreferencesDispatcher<int>.Instance.AddListener(DataMsg.playerAvatarId, OnChangeAvatar);
            GameDispatcher.Instance.AddListener(GameMsg.Sheep_item_refresh, SetItemNumber);
            GameDispatcher.Instance.AddListener(GameMsg.Slot_refresh, SetSlotNumber);
            GameDispatcher.Instance.AddListener(GameMsg.Remake_state, ReceiveRemakState);
            GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, SetTopCurr);
            AppDispatcher.Instance.AddListener(AppMsg.App_Focus_False, SaveJson);
            AppDispatcher.Instance.AddListener(AppMsg.App_Quit, SaveJson);
            GameDispatcher.Instance.AddListener(GameMsg.Ad_success, ad_success);

            GameDispatcher.Instance.AddListener(GameMsg.reset_game, ReSetGame);
            GameDispatcher.Instance.AddListener(GameMsg.card_click, CardClick);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshGame, RefreshGame);
            GameDispatcher.Instance.AddListener(GameMsg.Update101, SetTopCurr);
            GameDispatcher.Instance.AddListener(GameMsg.ExitGame, OnBackToHall);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.AddListener(GameMsg.resurgence, Resurgence);
            GameDispatcher.Instance.AddListener(GameMsg.resurgence_close, ChangeSlotState);
            GameDispatcher.Instance.AddListener(GameMsg.creatCARD, CreatCard);
            GameDispatcher.Instance.AddListener(GameMsg.CheckEnd, CheckEnd);

            // MainThreadDispatcher.Instance.AddListener(MainThreadMsg.App_Focus_True, backGame);

        }
        protected override void RemoveListener()
        {
            PreferencesDispatcher<string>.Instance.RemoveListener(DataMsg.playerName, OnChangeName);
            PreferencesDispatcher<int>.Instance.RemoveListener(DataMsg.playerAvatarId, OnChangeAvatar);
            GameDispatcher.Instance.RemoveListener(GameMsg.Sheep_item_refresh, SetItemNumber);
            GameDispatcher.Instance.RemoveListener(GameMsg.Slot_refresh, SetSlotNumber);
            GameDispatcher.Instance.RemoveListener(GameMsg.Remake_state, ReceiveRemakState);
            GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr);
            AppDispatcher.Instance.RemoveListener(AppMsg.App_Focus_False, SaveJson);
            AppDispatcher.Instance.RemoveListener(AppMsg.App_Quit, SaveJson);
            GameDispatcher.Instance.RemoveListener(GameMsg.reset_game, ReSetGame);
            GameDispatcher.Instance.RemoveListener(GameMsg.Ad_success, ad_success);

            GameDispatcher.Instance.RemoveListener(GameMsg.card_click, CardClick);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshGame, RefreshGame);
            GameDispatcher.Instance.RemoveListener(GameMsg.Update101, SetTopCurr);
            GameDispatcher.Instance.RemoveListener(GameMsg.ExitGame, OnBackToHall);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.RemoveListener(GameMsg.resurgence, Resurgence);
            GameDispatcher.Instance.RemoveListener(GameMsg.resurgence_close, ChangeSlotState);
            GameDispatcher.Instance.RemoveListener(GameMsg.creatCARD, CreatCard);
            GameDispatcher.Instance.RemoveListener(GameMsg.CheckEnd, CheckEnd);
        }
        #endregion

        public override void OnSwitchLanguage()
        {
            base.OnSwitchLanguage();
            ui.btn_secret.title = "LV." + GameHelper.GetCommonModel().UnlockSecret[1];
        }


        //初始化页面逻辑
        private void InitView()
        {

            var btnSecret = ui.btn_secret as btn_secret;
            var btnSecretAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnSecret.anim, Fx_Type.fx_btn_secret, ref closeCallback);
            btnSecretAnim.state.SetAnimation(0, "animation", true);
            
            var btnVip = ui.btn_vip as btn_vip;
            var btnVipAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnVip.anim, Fx_Type.fx_btn_vip, ref closeCallback);
            btnVipAnim.state.SetAnimation(0, "animation", true);

            var btnAlbum = ui.btn_album as btn_albums;
            var btnAlbumAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnAlbum.anim, Fx_Type.fx_btn_album, ref closeCallback);
            btnAlbumAnim.state.SetAnimation(0, "animation", true);

            var btnLive = ui.btn_live as btn_live;
            var btnLiveAnim = FXManager.Instance.SetFx<SkeletonAnimation>(btnLive.anim, Fx_Type.fx_btn_live, ref closeCallback);
            btnLiveAnim.state.SetAnimation(0, "animation", true);

            ui.fairyBatching = true;
            int level = GameHelper.GetLevel();

            ui.com_stage.text_level.text = level.ToString();
            Debug.Log(jsonstr);
            if (jsonstr == null)
            {
                SetLeveldiff();//
                InitPosList();//
                CreatCard();//
            }
            else
            {
                // InitPosList();
                CreatSaveItem();
            }
            RefreshCardState(true);
            ui.btn_remove.prop.selectedIndex = btn_prop.Prop_remove;
            ui.btn_back.prop.selectedIndex = btn_prop.Prop_back;
            ui.btn_refresh.prop.selectedIndex = btn_prop.Prop_refresh;
            ui.btn_back.SetClick(BackFunc);
            ui.btn_refresh.SetClick(RefreshFunc);


            ui.btn_back.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepwindowUI_Open, 1);
            });
            ui.btn_remove.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepwindowUI_Open, 0);
            });
            ui.btn_refresh.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepwindowUI_Open, 2);
            });
            ui.btn_album.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AlubumUI_Open);
            });

            ui.btn_live.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LiveUI_Open);
            });

            ui.btn_record.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RecordViewUI_Open);
            });

            ui.btn_secret.title = "LV." + GameHelper.GetCommonModel().UnlockSecret[1];
            ui.btn_secret.SetClick(() =>
            {
                if (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockSecret[1])
                {
                    if (DataMgr.IsUnlockSecret.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockSecret.As<int>()))//未解锁。
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretUnlockUI_Open);
                    }
                    else
                    {
                        if (DataMgr.IsUnlockSecret.Value == 0)
                        {
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockTipsUI_Open, 1);
                        }
                        else
                        {
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretAlbumsUI_Open);
                        }
                    }
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretAlbumsUI_Open);
                }

            });

            setBtnAds();
            ui.btn_noads.SetClick(() =>
            {
                if (!SaveData.GetSaveObject().is_get_packreward && !SaveData.GetSaveObject().is_get_removead)
                {
                    if (((btn_noads)ui.btn_noads).img_ad.visible)
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open, true);
                    }
                    else
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open);
                    }

                }
                else if (SaveData.GetSaveObject().is_get_packreward)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open, true);
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open);
                }
            });

            ui.btn_vip.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.VipClubViewUI_Open);
            });


#if !UNITY_EDITOR
            string type = SystemInfo.deviceModel.ToLower().Trim();
            if (type.Substring(0, 3) != "iph")
            {
                ui.btn_add.x += -20;
                ui.btn_add.y += -34;
            }
#endif
            ui.btn_add.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuyslotUI_Open);
                GameHelper.showGameUI = false;
            });


            SetItemNumber(null);
            SetSlotNumber();
            SetTopCurr();
            // setBtntask();

            ui.btn_pass.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassViewUI_Open); GameHelper.showGameUI = false; });

            //
            ui.btn_gold.SetClick(() =>
            {
                //uiCtrlDispatcher.Dispatch(UICtrlMsg.MainUI_Open);
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open, true);
                GameHelper.showGameUI = false;
            });
            if (SaveData.GetSaveObject().is_autopack_show_day != DateTime.Now.Day)
            {
                SaveData.GetSaveObject().is_autopack_show = false;
            }

            CheckEnd();


            if (!is_first_login_go_to_h5)
            {
                ChangeSlotState();//检测是否死亡
            }
            if (SaveData.GetSaveObject().start_time == 0) SaveData.GetSaveObject().start_time = GameHelper.GetNowTime();
            if ((SaveData.GetSaveObject().battle_pass_time + ConfigSystem.GetConfig<Passportrewards>()[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime())
            {
                SaveData.GetSaveObject().battle_pass_time = (int)GameHelper.GetNowTime();
                GameHelper.ResetGameExp();
                SaveData.GetSaveObject().battle_pass_freelist.Clear();
                SaveData.GetSaveObject().battle_pass_paylist.Clear();
                SaveData.GetSaveObject().is_get_battlepass = false;
            }

            ui.btn_three_day.SetClick(() =>
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            });
            ui.btn_look_ad.SetClick(() => { LookAd(); });
            Setbg();
        }
        private SpriteRenderer game_bg = GameObject.Find("game_bg").GetComponent<SpriteRenderer>();
        public void Setbg(object a = null)
        {
            if (GameHelper.IsGiftSwitch())
            {
                if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal)
                {
                    TextureHelper.setGamebg(ConfigSystem.GetConfig<LevelUnlock>()[GameHelper.GetLevel() - 1].Name);
                }
                else
                {
                    Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel());
                    Debug.Log($"levelunlock_0-----------------:{levelunlock_.config_index} {levelunlock_.type}");
                    if (levelunlock_ != null)
                    {
                        if (levelunlock_.type == 0)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<FreeImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<FreeImageLibrary>().Count - 1;
                            FreeImageLibrary _leveldata = ConfigSystem.GetConfig<FreeImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.setGamebg(_leveldata.Name);

                        }
                        else if (levelunlock_.type == 1)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<ADImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<ADImageLibrary>().Count - 1;
                            ADImageLibrary _leveldata = ConfigSystem.GetConfig<ADImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.setGamebg(_leveldata.Name);
                        }
                        else if (levelunlock_.type == 2)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<SpecialImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<SpecialImageLibrary>().Count - 1;
                            SpecialImageLibrary _leveldata = ConfigSystem.GetConfig<SpecialImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.setGamebg(_leveldata.Name);
                        }
                        else if (levelunlock_.type == 3)
                        {
                            if (levelunlock_.config_index >= ConfigSystem.GetConfig<VIPImageLibrary>().Count) levelunlock_.config_index = ConfigSystem.GetConfig<VIPImageLibrary>().Count - 1;
                            VIPImageLibrary _leveldata = ConfigSystem.GetConfig<VIPImageLibrary>()[levelunlock_.config_index];
                            TextureHelper.setGamebg(_leveldata.Name);
                        }
                    }
                    else
                    {
                        if (game_bg && game_bg.sprite && game_bg.sprite.texture.name != "")
                        {
                            return;
                        }
                        if (GameHelper.GetLevel() - 1 < ConfigSystem.GetConfig<LevelUnlock>().Count)
                        {
                            TextureHelper.setGamebg(ConfigSystem.GetConfig<LevelUnlock>()[GameHelper.GetLevel() - 1].Name);
                        }
                        else
                        {
                            TextureHelper.setGamebg(ConfigSystem.GetConfig<LevelUnlock>()[ConfigSystem.GetConfig<LevelUnlock>().Count - 1].Name);
                        }
                    }
                }
            }
        }
        private void CheckEnd(object a = null)
        {
            if (out_list.Count == 0)//是否通关
            {
                bool all_clear = CheckSuccess();
                if (all_clear)
                {
                    //通关成功
                    float[] ch_array = GameHelper.GetRewardValue(2);

                    // var temp = new { IsWin = true, ch_number = 0, rate = 2, IsLevelSuccess = true, IsH5Reward = false };


                    DOVirtual.DelayedCall(0.5f, () =>
                    {

                        var temp = new SuccessData();
                        temp.IsWin = true;
                        temp.ch_number = ch_array[0];
                        temp.rate = (int)ch_array[1];
                        temp.IsLevelSuccess = true;
                        temp.IsH5Reward = false;
                        temp.boost_array = GameHelper.GetRewardBoost(0);
                        temp.level = GameHelper.GetLevel();
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Open, temp);
                    });
                }
            }
        }
        private void checkThreeGift(object obj = null)
        {
            // if (SaveData.GetSaveObject().is_get_ThreeDaysGift) {
            var isToday = GameHelper.InToday(SaveData.GetSaveObject().last_got_three_gift_time, 0, true);
            int three_gift_got_index = SaveData.GetSaveObject().three_gift_got_index;
            if (three_gift_got_index > (int)rewardState.day3)
            {
                ui.btn_three_day.visible = false;
            }
            else if (!isToday)
            {
                ui.btn_three_day.GetChild("red").visible = true;
            }
            else
            {
                ui.btn_three_day.GetChild("red").visible = false;
            }
            // }
        }

        private decimal updateTime;
        private SaveingPotClass _makeupTaskData = SaveData.GetSaveObject().saveingpot_history[^1];

        void Resurgence(object state)
        {
            OutFunc(true);
            GameHelper.IsTemporaryEnd = false;
        }

        private void RefreshRed(object a = null)
        {
            ui.btn_pass.red.visible = SaveData.getRed();
            ui.btn_chat.GetChild("red").visible = ChatHelper.GetChatRed();
        }

        void ad_success(object a = null)
        {

            // var start = GameHelper.GetUICenterPosition(ui.btn_look_ad);
            // var end = GameHelper.GetUICenterPosition(ui.money.number_text);

            float ch = (float)a;
            if (GameHelper.IsGiftSwitch())
            {
                var start = GameHelper.GetUICenterPosition(ui.btn_look_ad);
                var end = GameHelper.GetUICenterPosition(ui.btn_gold.GetChild("text_gold"));
                GameHelper.GetRewardOnly1(101, (decimal)ch, RewardOrigin.Play, new Vector2(start.x - 200, start.y - 150), new Vector2(end.x - 300, end.y - 140), isScucess =>
                {
                    var startNum = DataMgr.Coin.Value - (decimal)ch;

                    DOVirtual.Float((float)startNum, (float)DataMgr.Coin.Value, 1,
                        value => { ui.btn_gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
                });
            }
            ui.btn_look_ad.visible = false;
        }
        private int btn_look_ad_showtime = 0;

        void LookAd()
        {

            //PlayerPrefs .SetInt("adCoolDownTime",Convert.ToInt32( GameHelper.GetNowTime()));
            if (ad_numbers >= 3 && (GameHelper.GetNowTime() <= PlayerPrefs.GetInt("ad_time") + ad_cool_down))
            {
                return;

            }
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardboxUI_Open);
            GameHelper.showGameUI = false;
            ui.btn_look_ad.visible = false;
        }
        private List<Paidcoins> Paidcoins_list = ConfigSystem.GetConfig<Paidcoins>();

        void CreateGoldtimeList()
        {
            // 获取保存对象
            var saveObject = SaveData.GetSaveObject();

            // 检查_goldtime是否为null或者长度与Paidcoins_list.Count不相等
            if (saveObject._goldtime == null || saveObject._goldtime.Length != Paidcoins_list.Count)
            {
                // 重置_goldtime，并创建一个新的数组，长度为Paidcoins_list.Count
                saveObject._goldtime = new int[Paidcoins_list.Count];
            }
        }

        void upData()
        {

            com_gold btn_gold = ui.btn_gold as com_gold;
            btn_gold.state.selectedIndex = 1;
            for (int i = 0; i < Paidcoins_list.Count; i++)
            {
                if (!Paidcoins_list[i].is_paid)
                {
                    int time = SaveData.GetSaveObject()._goldtime[i];
                    if (time + Paidcoins_list[i].receive_CD < GameHelper.GetNowTime())
                    {
                        btn_gold.state.selectedIndex = 2;
                    }
                }
            }
            ui.btn_pass.red.visible = SaveData.getRed();
            checkThreeGift();
            Setbg();
            if ((!SaveData.GetSaveObject().is_get_packreward || !SaveData.GetSaveObject().is_get_removead) && !SaveData.GetSaveObject().is_autopack_show
             && GameHelper.showGameUI && Time.time > ConfigSystem.GetCommonConf().Activetimes * 60)
            {
                Window Popup = GRoot.inst.GetChild("Popup") as Window;
                if (Popup.GetChildren().Length > 0)
                    return;
                GameHelper.isAutoPop = true;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LuckyPackUI_Open);
                SaveData.GetSaveObject().is_autopack_show = true;
                SaveData.GetSaveObject().is_autopack_show_day = DateTime.Now.Day;
                SaveData.SaveDataFunc();

            }
            btn_look_ad_showtime++;
            if (btn_look_ad_showtime > 15) ui.btn_look_ad.visible = false;

            var head = ui.btn_head as btn_head;
            if (head != null)
            {
                var vipLevel = GameHelper.GetVipLevel();
                if (vipLevel > 0)
                {
                    head.vip_loader.visible = true;
                    head.vip_loader.url = $"ui://LG_Common/vip_{vipLevel}";
                }
                else
                {
                    head.vip_loader.visible = false;
                }
            }
        }

        void RefreshGame(object obj = null)
        {
            GameHelper.is_first_login = false;
            first_reset = false;
            ChangeSlotState();//检测是否死亡
        }

        // void setBtntask()
        // {
        //     ui.btn_pass.number_text.text = "Lv." + GameHelper.GetBattleLv();
        //     if (GameHelper.GetBattleLv() >= ConfigSystem.GetConfig<PassportrewardsModel>().DataList.Count)
        //     {
        //         ui.btn_pass.progress.value = 100;
        //     }
        //     else
        //     {
        //         ui.btn_pass.progress.value =
        //          ((float)GameHelper.GetGameExp() / ConfigSystem.GetConfig<PassportrewardsModel>().DataList[GameHelper.GetBattleLv()].Eliminating_quantity) * 100;
        //     }
        // }
        private void PlayPropEffect()
        {
            for (int i = 0; i < 3; i++)
            {
                btn_prop btn_ = null;
                if (i == 0) btn_ = ui.btn_back;
                else if (i == 1) btn_ = ui.btn_remove;
                else if (i == 2) btn_ = ui.btn_refresh;
                var prop_effect = FXManager.Instance.SetFx<SkeletonAnimation>(btn_.ani_parent, Fx_Type.fx_proplight, ref closeCallback);
                prop_effect.state.SetAnimation(0, "animation", true);
                DOVirtual.DelayedCall(3, () =>
                {
                    GameObject.Destroy(prop_effect);
                });


            }
        }

        public void SetTopCurr(object a = null)
        {
            var btn_gold = ui.btn_gold as com_gold;
            btn_gold.text_gold.text = $"{DataMgr.Coin.Value:N0}";



        }
        public void setBtnAds()
        {
            btn_noads btn_ = (ui.btn_noads as btn_noads);
            if (!SaveData.GetSaveObject().is_get_removead && !SaveData.GetSaveObject().is_get_packreward)
            {
                btn_.t0.Play(-1, 0, null);
            }
            else if (SaveData.GetSaveObject().is_get_removead && SaveData.GetSaveObject().is_get_packreward)
            {
                btn_.t0.Stop();
                // btn_.visible = false;
                btn_.img_pack.visible = false;
                btn_.img_ad.visible = true;
            }
            else if (SaveData.GetSaveObject().is_get_packreward)
            {
                btn_.t0.Stop();
                btn_.t1.Play();
                //ui.btn_noads.state.selectedIndex = 0;
                btn_.img_pack.visible = false;
                btn_.img_ad.visible = true;

            }
            else if (SaveData.GetSaveObject().is_get_removead)
            {
                btn_.t0.Stop();
                btn_.t1.Play();
                btn_.img_pack.visible = true;
                btn_.img_ad.visible = false;
                //ui.btn_noads.state.selectedIndex = 1;
            }

        }

        void ReceiveRemakState(object state)
        {

            if ((bool)state)
            {//复活
                GameHelper.IsTemporaryEnd = false;
                OutFunc(true);
            }
            else
            {//重置
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open);


            }

        }
        void SetItemNumber(object a = null)
        {
            int numbers = GameHelper.GetItemNumber(0);
            if (numbers == 0)
            {
                ui.btn_remove.number_text.visible = false;
                ui.btn_remove.img_add.visible = true;
                ui.btn_remove.SetClick(() =>
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepwindowUI_Open, 0);
                    GameHelper.showGameUI = false;
                });
            }
            else
            {
                ui.btn_remove.number_text.text = numbers.ToString();
                ui.btn_remove.number_text.visible = true;
                ui.btn_remove.img_add.visible = false;
                ui.btn_remove.SetClick(() =>
                {
                    OutFunc();
                });
            }
            numbers = GameHelper.GetItemNumber(1);
            if (numbers == 0)
            {
                ui.btn_back.number_text.visible = false;
                ui.btn_back.img_add.visible = true;
                ui.btn_back.SetClick(() =>
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepwindowUI_Open, 1);
                    GameHelper.showGameUI = false;
                });
            }
            else
            {
                ui.btn_back.number_text.text = numbers.ToString();
                ui.btn_back.number_text.visible = true;
                ui.btn_back.img_add.visible = false;
                ui.btn_back.SetClick(() =>
                {
                    BackFunc();
                });
            }
            numbers = GameHelper.GetItemNumber(2);
            if (numbers == 0)
            {
                ui.btn_refresh.number_text.visible = false;
                ui.btn_refresh.img_add.visible = true;
                ui.btn_refresh.SetClick(() =>
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepwindowUI_Open, 2);
                    GameHelper.showGameUI = false;
                });
            }
            else
            {
                ui.btn_refresh.number_text.text = numbers.ToString();
                ui.btn_refresh.number_text.visible = true;
                ui.btn_refresh.img_add.visible = false;
                ui.btn_refresh.SetClick(() =>
                {
                    RefreshFunc();
                });
            }

        }
        void SetSlotNumber(object a = null)
        {
            if (!SaveData.GetSaveObject().have_slot)
            {
                slot_max = 7;
                ui.btn_add.visible = true;
            }
            else
            {
                slot_max = 8;
                ui.btn_add.visible = false;
            }


        }
        void SetLeveldiff()
        {
            int level = GameHelper.GetLevel();
            ui.com_stage.text_level.text = level.ToString();

            // if (level > type_array.Length) level = type_array.Length;

            // card_type_max = type_array[level - 1];
            // card_layer = layer_array[level - 1];
            // all_card_numbers = all_array[level - 1];

            extra_max = 0;
        }
        private bool first_reset = true;
        void ReSetGame(object a = null)
        {
            (ui.btn_album as btn_albums).t0.Play();
            (ui.btn_live as btn_live).t0.Play();
            if (first_reset)
            {
                first_reset = false;
                return;
            }
            if (a != null && !(bool)a) SendLog(false);
            SetLeveldiff();
            slot_list.Clear();
            out_list.Clear();
            SaveData.GetSaveObject().all_card_numbers = 0;
            SaveData.GetSaveObject().card_layer = 2;

            InitPosList();
            CreatCard();
            RefreshCardState(true);
            GameHelper.SetLevelstate(3);
            GameHelper.IsTemporaryEnd = false;
            SaveData.GetSaveObject().clear_number = 0;
            for (int i = 0; i < SaveData.GetSaveObject().usePropsNum.Length; i++)
            {
                SaveData.GetSaveObject().usePropsNum[i] = 0;
            }

            Setbg();
            CheckFeature();
            if (GameHelper.IsGiftSwitch() && GameHelper.GetCommonModel().Assitant == 1 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().AssitantPreview)
            {
                ui.btn_chat.visible = true;
            }

        }

        private void CheckFeature()
        {
            if (!ui.btn_live.visible && GameHelper.GetCommonModel().Live == 1 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().LivePreview)
            {
                ui.btn_live.visible = true;
            }
            if (!ui.btn_secret.visible && GameHelper.GetCommonModel().Secret == 1 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().SecretPreview)
            {
                ui.btn_secret.visible = true;
            }

            var commonModel = GameHelper.GetCommonModel();
            int currentLevel = GameHelper.GetLevel();
            Debug.Log($"[Game End1]  {currentLevel}/{commonModel.UnlockSecret[1]}/{DataMgr.IsUnlockSecret.Value}");
            if (!GameHelper.GetVipPrivilege(Subscription.UnlockSecret.As<int>()) && DataMgr.IsUnlockSecret.Value < 0 && currentLevel >= commonModel.UnlockSecret[1] && GameHelper.GetCommonModel().Secret == 1 && GameHelper.GetCommonModel().Live == 1)
            {
                DataMgr.IsUnlockSecret.Value = 0;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockTipsUI_Open, 1);
            }

            Debug.Log($"[Game End2]  {currentLevel}/{commonModel.UnlockLive[1]}/{DataMgr.IsUnlockLive.Value}");
            if (!GameHelper.GetVipPrivilege(Subscription.UnlockLive.As<int>()) && DataMgr.IsUnlockLive.Value < 0 && currentLevel >= commonModel.UnlockLive[1] && GameHelper.GetCommonModel().Secret == 1 && GameHelper.GetCommonModel().Live == 1)
            {
                DataMgr.IsUnlockLive.Value = 0;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockTipsUI_Open, 2);
            }
        }

        void RefreshFunc()
        {
            int item_num = GameHelper.GetItemNumber(2);
            if (item_num <= 0) return;
            List<Card_item> temp_list = new List<Card_item>();
            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].in_slot && !card_item_list[i][j].is_out)
                    {
                        temp_list.Add(card_item_list[i][j]);
                        refresh_list.Add(new Vector3(card_item_list[i][j].pos_x, card_item_list[i][j].pos_y, card_item_list[i][j]._layer));
                    }
                }
            }
            for (int i = 0; i < temp_list.Count; i++)
            {
                card_item_list[(int)refresh_list[i].z].Remove(temp_list[i]);
            }

            for (int i = 0; i < temp_list.Count; i++)
            {
                int index = Random.Range(0, refresh_list.Count);
                temp_list[i].pos_x = refresh_list[index].x;
                temp_list[i].pos_y = refresh_list[index].y;
                temp_list[i]._layer = (int)refresh_list[index].z;
                card_item_list[(int)refresh_list[index].z].Add(temp_list[i]);
                refresh_list.RemoveAt(index);

                // GTweener tweener = temp_list[i].sheep_card.TweenMove(new Vector2(temp_list[i].pos_x, temp_list[i].pos_y), 0.2f); // 位置从当前值渐变到新的坐标
                // tweener.SetEase(EaseType.Linear);
                temp_list[i].sheep_card.transform.DOLocalMove(new Vector3(temp_list[i].pos_x, temp_list[i].pos_y, 300 - temp_list[i]._layer), 0.2f);
            }


            for (int i = 0; i < card_item_list.Count; i++)
            {
                for (int j = 0; j < card_item_list[i].Count; j++)
                {
                    int k = i;
                    int l = j;
                    var temp_ = card_item_list[k][l];
                    // card_item_list[k][l].sheep_card.SetClick(() =>
                    // {
                    //     cardClick(temp_);
                    // });

                }
            }
            DOVirtual.DelayedCall(0.5f, () => { RefreshCardState(); });
            GameHelper.SetItemNumber(2, item_num - 1);
            SetItemNumber();

            SaveData.GetSaveObject().usePropsNum[2]++;

        }
        void OutFunc(bool isfree = false)
        {
            if (slot_list.Count > 0)
            {
                int item_num = GameHelper.GetItemNumber(0);
                if (item_num <= 0 && !isfree) return;
                int out_list_layer = 0;
                for (int i = 0; i < out_list.Count; i++)
                {
                    if (out_list_layer < (out_list[i].out_layer + 1)) out_list_layer = out_list[i].out_layer + 1;
                }
                for (int i = 0; i < 3; i++)
                {
                    if (i < slot_list.Count)
                    {
                        out_list.Add(slot_list[i]);
                        slot_list[i].in_slot = false;
                        slot_list[i].can_click = true;

                        slot_list[i].out_layer = out_list_layer;

                        if (slot_list[i] == last_card_item) last_card_item = null;

                        slot_list[i].sheep_card.transform.DOLocalMove(new Vector3((i - 1) * card_width_slot, -22.5f + out_list_layer * 0.5f, 300 - out_list_layer), 0.2f);

                        slot_list[i].pos_x = (i - 1) * card_width_slot;
                        slot_list[i].pos_y = -22.5f + out_list_layer * 0.5f;

                        card_item_list[slot_list[i]._layer].Remove(slot_list[i]);
                        if (out_list_layer >= card_item_list.Count) card_item_list.Add(new List<Card_item>());
                        card_item_list[out_list_layer].Add(slot_list[i]);
                        slot_list[i]._layer = out_list_layer;

                        slot_list[i].is_out = true;
                    }
                }
                for (int i = 0; i < 3; i++)
                {
                    if (slot_list.Count > 0) slot_list.RemoveAt(0);
                }


                for (int k = 0; k < slot_list.Count; k++)
                {
                    slot_list[k].sheep_card.transform.DOLocalMove(new Vector3(k * (card_width_slot) + bg_x, bg_y, 1), 0.2f);
                }
                if (!isfree) GameHelper.SetItemNumber(0, item_num - 1);
                RefreshCardState();
                SetItemNumber();

                SaveData.GetSaveObject().usePropsNum[0]++;

            }


        }
        void BackFunc()
        {
            if (slot_list.Count == 0) last_card_item = null;

            if (last_card_item != null)
            {

                int item_num = GameHelper.GetItemNumber(1);
                if (item_num <= 0) return;

                slot_list.Remove(last_card_item);
                last_card_item.in_slot = false;
                last_card_item.can_click = true;
                ChangeSlotState();

                if (!last_card_item.is_out)
                {
                    last_card_item.sheep_card.transform.DOScale(new Vector3(card_scale, card_scale, 1), 0.2f);
                }
                last_card_item.sheep_card.transform.DOLocalMove(new Vector3(last_card_item.pos_x, last_card_item.pos_y, 300 - last_card_item._layer), 0.2f).OnComplete(() =>
                {
                    RefreshCardState();
                    last_card_item = null;
                });

                for (int k = 0; k < slot_list.Count; k++)
                {
                    slot_list[k].sheep_card.transform.DOLocalMove(new Vector3(k * (card_width_slot) + bg_x, bg_y, 1), 0.2f);
                }

                GameHelper.SetItemNumber(1, item_num - 1);
                SetItemNumber();
                SaveData.GetSaveObject().usePropsNum[1]++;
            }
            else
            {
                GameHelper.ShowTips("no_undone", true);
            }


        }
        void CardClick(object obj = null)
        {
            if (GameHelper.IsTemporaryEnd)
            {
                return;
            }

            string name = (string)obj;
            Card_item card_self = null;

            for (int i = 0; i < card_item_list.Count; i++)
            {
                if (card_item_list[i].Count == 0) continue;
                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;
                    if (card_item_list[i][j].sheep_card.gameObject.name == name)
                    {
                        card_self = card_item_list[i][j];
                        break;
                    }
                }
            }
            if (card_self == null) return;
            is_resurgence = false;
            if (AudioManager.Instance.IsOpenEffect)
            {
                AudioManager.Instance.PlayDynamicEffect(AudioConst.UIButtonDefault);
            }
            if (card_self.can_click && !card_self.in_slot)
            {
                int insert_indet = -1;
                for (int i = 0; i < slot_list.Count; i++)
                {
                    if (slot_list[i].card_type == card_self.card_type)
                    {
                        insert_indet = i + 1;
                    }
                }
                if (insert_indet < 0) insert_indet = slot_list.Count;

                slot_list.Insert(insert_indet, card_self);
                card_self.in_slot = true;
                card_self.can_click = false;
                card_self.pos_x = card_self.sheep_card.transform.position.x;
                card_self.pos_y = card_self.sheep_card.transform.position.y;
                if (card_self.is_out)
                {
                    out_list.Remove(card_self);
                    //card_self.is_out = false;
                }

                // ui.SetChildIndex(card_self.sheep_card, ui.GetChildrenCount());

                RefreshCardState();
                if (insert_indet < slot_list.Count)
                {
                    for (int i = insert_indet + 1; i < slot_list.Count; i++)
                    {
                        slot_list[i].sheep_card.transform.DOLocalMove(new Vector3(i * card_width_slot + bg_x, bg_y, 1), 0.2f);
                    }
                }

                last_card_item = card_self;
                ChangeSlotState();

                // card_self.sheep_card.transform.DOMoveZ(110, 0);
                card_self.sheep_card.GetComponent<SpriteRenderer>().sortingOrder = 1000;
                card_self.sheep_card.transform.DOScale(new Vector3(card_scale * 1.2f, card_scale * 1.2f, 1), 0.1f)
                .OnComplete(() =>
                {
                    card_self.sheep_card.transform.DOScale(new Vector3(card_slot_scale, card_slot_scale, 1), 0.2f);

                    card_self.sheep_card.transform.DOLocalMove(new Vector3(bg_x + insert_indet * card_width_slot, bg_y, 1), 0.2f).OnComplete(() =>
                    {
                        card_self.sheep_card.GetComponent<SpriteRenderer>().sortingOrder = 0;
                    });



                });
                if (slot_list.Count == (slot_max - 1))
                {
                    PlayPropEffect();
                }
                // card_self.sheep_card.tobig.Play(() =>
                // {
                //     card_self.sheep_card.tosmall.Play();
                //     GTweener tweener = card_self.sheep_card.TweenMove(new Vector2((insert_indet) * (card_width - 1) + ui.slot.x + 8, ui.slot.y + 13), 0.2f); // 位置从当前值渐变到新的坐标
                //     tweener.SetEase(EaseType.Linear); // 设置缓动类型
                //     if (insert_indet < slot_list.Count)
                //     {
                //         for (int i = insert_indet + 1; i < slot_list.Count; i++)
                //         {
                //             GTweener tweener1 = slot_list[i].sheep_card.TweenMove(new Vector2((i) * (card_width - 1) + ui.slot.x + 8, ui.slot.y + 13), 0.2f); // 位置从当前值渐变到新的坐标
                //             tweener1.SetEase(EaseType.Linear);
                //         }
                //     }
                //     tweener.OnComplete(() =>
                //     {
                //         changeSlotState();
                //         Debug.Log("111111111111");
                //     });
                // });
                RefreshRed();
            }
        }

        public List<GameBoard> GetGameConfig()
        {
            var conf_num = PlayerPrefs.GetInt("game_conf_num", 1);
            var GameConfig = ConfigLoader.Instance.GetConfig<GameConfigModel>();

            conf_num = conf_num != GameHelper.conf_num ? conf_num : GameHelper.conf_num;

            List<GameBoard> configData = GameConfig.game_conf[1];

            Debug.Log($"GetGameConfig==== {conf_num}, exist== {GameConfig.game_conf.ContainsKey(conf_num)}");
            if (GameConfig.game_conf.ContainsKey(conf_num))
            {
                configData = GameConfig.game_conf[conf_num];
            }

            // PlayerPrefs.SetString("game_config_data",configData);

            return configData;
        }

        void InitPosList()
        {
            map_list.Clear();
            left_extra_list.Clear();
            right_extra_list.Clear();

            float parent_x = 0 - (3) * card_width;
            float parent_y = 0 + (3) * card_height + 2;


            var level = GameHelper.GetLevel();

            var GameConfig = GetGameConfig();

            if (level > GameConfig.Count) level = GameConfig.Count;

            var stackedConf = new StackedModel
            { dataList = SerializeUtil.ToObject<List<Stacked>>(GameConfig[level - 1].stacked) };
            var boardConf = new BoardModel
            { dataList = SerializeUtil.ToObject<List<Board>>(GameConfig[level - 1].board) };

            card_layer = boardConf.dataList.Count;
            card_type_max = GameConfig[level - 1].item_type;

            // Debug.Log($"boardConf.dataList.Count {boardConf.dataList.Count}");

            if (stackedConf.dataList.Count > 0)
            {
                var leftData = stackedConf.dataList[0];
                for (int i = 0; i < leftData.num; i++)
                {
                    left_extra_list.Add(new Vector2(parent_x + (leftData.site[0] - 1) * card_width + i * 0.5f, parent_y - (leftData.site[1] - 1) * card_height));
                }

                var rightData = stackedConf.dataList[1];
                for (int i = 0; i < rightData.num; i++)
                {
                    right_extra_list.Add(new Vector2(parent_x + (rightData.site[0] - 1) * card_width - i * 0.5f, parent_y - (rightData.site[1] - 1) * card_height));
                }

                int stacked_count = leftData.num >= rightData.num ? leftData.num : rightData.num;
                card_layer = card_layer >= stacked_count ? card_layer : stacked_count;
            }

            SaveData.GetSaveObject().card_layer = card_layer;

            var count = 0;
            for (int k = boardConf.dataList.Count; k > 0; k--)
            {
                count++;
                var oneLayer = boardConf.dataList[k - 1];
                var vector2 = oneLayer.vector2;
                // Debug.Log($"vector2: {JsonConvert.SerializeObject(vector2)}");
                List<Vector2> single_ = new List<Vector2>();

                InitOffset(oneLayer.offset, out var x_offset, out var y_offset);
                for (int i = 0; i < vector2.Length; i++)
                {
                    if (i >= width_max) continue;

                    for (int j = 0; j < vector2[i].Length; j++)
                    {
                        if (j >= height_max) continue;

                        if (vector2[i][j] != 0)
                        {
                            single_.Add(new Vector2(parent_x + i * card_width + x_offset,
                                parent_y - j * card_height + y_offset));
                        }
                    }
                }

                map_list.Add(single_);
            }

            int map_count = 0;
            for (int i = 0; i < map_list.Count; i++)
            {
                map_count += map_list[i].Count;
            }
            // Debug.Log($"map_count:    {map_count}, left_extra_list:    {left_extra_list.Count}, right_extra_list:    {right_extra_list.Count}" );
            all_card_numbers = (map_count + left_extra_list.Count + right_extra_list.Count) / 3;
            // Debug.Log($"all_card_numbers2:{all_card_numbers}");
            SaveData.GetSaveObject().all_card_numbers = all_card_numbers;

        }

        void InitOffset(int[] offset, out float x_offset, out float y_offset)
        {
            // Debug.Log($"offset:{JsonConvert.SerializeObject(offset)}");
            x_offset = 0;
            y_offset = 0;
            if (offset.Length < 4) return;

            x_offset = offset[1] != 0 ? offset[1] : -offset[3];
            x_offset *= real_card_width / 2 - (real_card_width - card_width) / 2;

            y_offset = offset[0] != 0 ? offset[0] : -offset[2];
            y_offset *= real_card_height / 2 - (real_card_height - card_height) / 2;

            // Debug.Log($"x_offset:{x_offset},y_offset:{y_offset}");
        }


        void CreatCard(object a = null)
        {

            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 != null)
                    {
                        MonoBehaviour.Destroy(card_item_list[i][j].sheep_card);
                    }
                }
            }
            card_item_list = CreatAnimalCard.instance.CreatCardNew(all_card_numbers, card_type_max, card_layer, extra_max, map_list, left_extra_list, right_extra_list);
        }

        int GetExtra()
        {
            int pos = Random.Range(0, pool_list.Count);
            if (pool_list[pos].is_extra)
            {
                pos = GetExtra();
            }
            return pos;
        }

        int GetMaplayer()
        {
            int layer = Random.Range(0, map_list.Count);//确定层数
            if (map_list[layer].Count == 0)
            {
                layer = GetMaplayer();
            }
            return layer;
        }
        private int name_index = 0;
        public Camera orthoCamera;
        private bool is_resurgence = false;
        void ChangeSlotState(object a = null)
        {
            float start_card = 0;
            int hide_type = -1;
            bool all_clear = false;
            for (int i = 0; i < slot_list.Count; i++)
            {
                int same_numbers = 0;
                for (int j = i + 1; j < slot_list.Count; j++)
                {
                    if (slot_list[j].card_type == slot_list[i].card_type)
                    {
                        same_numbers++;
                    }

                    if (same_numbers >= 2)
                    {
                        hide_type = slot_list[j].card_type;
                        break;
                    }

                }
            }


            if (hide_type >= 0)
            {
                if (AudioManager.Instance.IsOpenEffect)
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.dissolve);
                }
                int index = 0;
                for (int j = 0; j < slot_list.Count; j++)
                {

                    if (slot_list[j].card_type == hide_type)
                    {
                        if (index == 1)
                        {
                            start_card = ui.slot.x + 28 + j * 124;
                        }
                        slot_list[j].in_slot = false;
                        GameObject temp = slot_list[j].sheep_card;
                        card_item_list[slot_list[j]._layer].Remove(slot_list[j]);
                        //slot_list[j].sheep_card.gameObjectName = name_index.ToString();

                        DOVirtual.DelayedCall(0.3f, () =>
                        {

                            temp.transform.DOScale(new Vector3(card_scale * 1.1f, card_scale * 1.1f, 1), 0.15f).OnComplete(() =>
                            {
                                temp.transform.DOScale(new Vector3(1, 1, 1), 0.15f);
                            });
                            temp.transform.DOLocalRotate(new Vector3(0, 0, 17), 0.15f).OnComplete(() =>
                            {
                                temp.transform.DOScale(new Vector3(0, 0, 0), 0.15f).OnComplete(() =>
                                {
                                    if (hide_type % 2 == 0)
                                    {
                                        CreatAnimalCard.instance.creatSpine(1, temp.transform.position);
                                    }
                                    else
                                    {
                                        CreatAnimalCard.instance.creatSpine(2, temp.transform.position);
                                    }
                                    MonoBehaviour.Destroy(temp);

                                });
                            });
                        });

                        card_item_list[slot_list[j]._layer].Remove(slot_list[j]);
                        index++;
                    }
                }
                name_index++;
                if (last_card_item != null && last_card_item.card_type == hide_type) last_card_item = null;
                slot_list.RemoveAll((Card_item a) =>
                    a.card_type == hide_type
                );

                for (int k = 0; k < slot_list.Count; k++)
                {
                    int l = k;
                    DOVirtual.DelayedCall(0.5f, () =>
                           {
                               //   GTweener tweener = slot_list[l].sheep_card.TweenMove(new Vector2(l * (card_width - 1) + ui.slot.x + 8, ui.slot.y + 13), 0.2f); // 位置从当前值渐变到新的坐标
                               //   tweener.SetEase(EaseType.Linear); // 设置缓动类型
                               slot_list[l].sheep_card.transform.DOLocalMove(new Vector3(l * card_width_slot + bg_x, bg_y, 1), 0.2f);

                           });

                }
                GameHelper.AddGameExp(3);
                SaveData.GetSaveObject().clear_number += 3;
                // setBtntask();
                if (GameHelper.IsGiftSwitch() && (Random.Range(0, 100) < ConfigSystem.GetCommonConf().roomrewardrate) && !ui.btn_look_ad.visible)
                {
                    ui.btn_look_ad.visible = true;
                    btn_look_ad_showtime = 0;

                }
                all_clear = CheckSuccess();


                if (!all_clear)
                {
                    if (hide_type >= 0)
                    {
                        if (hide_type == 15)
                        {

                            float[] cash_array = GameHelper.GetRewardValue(0);
                            var temp = new SuccessData();
                            temp.IsWin = true;
                            temp.ch_number = cash_array[0];
                            temp.rate = (int)cash_array[1];
                            temp.IsLevelSuccess = false;
                            temp.IsH5Reward = false;
                            temp.boost_array = GameHelper.GetRewardBoost(0);
                            temp.level = GameHelper.GetLevel();

                            DOVirtual.DelayedCall(0.55f, () =>
                            {
                                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Open, temp);
                                clearSpinepool?.Invoke();
                            });
                        }
                    }
                }
            }


            if (out_list.Count == 0)
            {




                if (all_clear)
                {
                    SendLog(true);



                    float[] ch_array = GameHelper.GetRewardValue(2);
                    var temp = new SuccessData();
                    temp.IsWin = true;
                    temp.ch_number = ch_array[0];
                    temp.rate = (int)ch_array[1];
                    temp.IsLevelSuccess = true;
                    temp.IsH5Reward = false;
                    temp.boost_array = GameHelper.GetRewardBoost(2);
                    temp.level = GameHelper.GetLevel();
                    DOVirtual.DelayedCall(0.5f, () =>
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Open, temp);
                    });

                    return;
                }
            }

            if (slot_list.Count >= slot_max)
            {
                GameHelper.IsTemporaryEnd = true;
                float complte_progress = showResurgence();
                if (GameHelper.GetLevelstate() != 0)
                {
                    // if ((complte_progress > ((float)ConfigSystem.GetConfig<CommonModel>().FailedGiftProgress / 100)) && !is_resurgence)
                    // {
                    //
                    //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, complte_progress);
                    //     is_resurgence = true;
                    //     return;
                    // }
                    DOVirtual.DelayedCall(0.75f, () =>
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ChoosePropUI_Open);
                    });


                    // TimerHelper.mEasy.AddTimer(1.0f, () =>
                    // {
                    // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ChoosePropUI_Open);
                    // });
                }
                else
                {
                    // if ((complte_progress > ((float)ConfigSystem.GetConfig<CommonModel>().FailedGiftProgress / 100)) && !is_resurgence)
                    // {
                    //
                    //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, complte_progress);
                    //     is_resurgence = true;
                    //     return;
                    // }
                    //通关失败
                    float[] ch_array = GameHelper.GetRewardValue(2);

                    var temp = new SuccessData();
                    temp.IsWin = false;
                    temp.ch_number = ch_array[0];
                    temp.IsLevelSuccess = true;
                    temp.IsH5Reward = false;
                    temp.boost_array = GameHelper.GetRewardBoost(2);
                    temp.level = GameHelper.GetLevel();
                    DOVirtual.DelayedCall(0.5f, () =>
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Open, temp);
                    });
                }
                if (AudioManager.Instance.IsOpenEffect)
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.fail);
                }
            }

        }
        float showResurgence()
        {
            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++;
                }
            }
            Debug.Log(surplus_item);
            Debug.Log(SaveData.GetSaveObject().all_card_numbers * 3);
            //  if ((1 - (float)surplus_item / (float)(SaveData.GetSaveObject().all_card_numbers * 3)))
            //   {
            return 1 - (float)surplus_item / (float)(SaveData.GetSaveObject().all_card_numbers * 3);
            //  }

            //    return 0;
        }
        bool CheckSuccess()
        {

            bool all_clear = true;
            for (int i = 0; i < card_item_list.Count; i++)
            {
                if (!all_clear) break;
                for (int j = 0; j < card_item_list[i].Count; j++)
                {

                    all_clear = false;
                    break;

                }
            }
            return all_clear;

        }



        void RefreshCardState(bool is_first = false)
        {

            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;


                    bool can_click = true;
                    if (card_item_list[i][j].in_slot) continue;

                    for (int k = i + 1; k < card_item_list.Count; k++)
                    {
                        bool is_break = false;
                        for (int l = 0; l < card_item_list[k].Count; l++)
                        {

                            if (card_item_list[k][l].in_slot) continue;
                            var card_distance = card_item_list[k][l].is_out && card_item_list[i][j].is_out ? 0.9f : 0.1f;
                            // Debug.Log($"card_distance=========: {card_distance}");
                            if (Vector2.Distance(new Vector2(card_item_list[k][l].pos_x, card_item_list[k][l].pos_y),
                       new Vector2(card_item_list[i][j].pos_x, card_item_list[i][j].pos_y)) <= (card_width - card_distance))
                            {
                                is_break = true;
                                can_click = false;
                                break;
                            }
                        }
                        if (is_break) break;
                    }
                    //}

                    if (is_first)
                    {
                        if (can_click)
                        {
                            // card_item_list[i][j].sheep_card.tolight_notween.Play();
                            card_item_list[i][j].sheep_card.GetComponent<SpriteRenderer>().color = white_color;
                        }
                        else
                        {
                            // card_item_list[i][j].sheep_card.todark_notween.Play();
                            card_item_list[i][j].sheep_card.GetComponent<SpriteRenderer>().color = dark_color;
                        }
                    }
                    else
                    {
                        if (card_item_list[i][j].can_click != can_click)
                        {
                            if (can_click)
                            {
                                // card_item_list[i][j].sheep_card.tolight.Play();
                                SpriteRenderer temp = card_item_list[i][j].sheep_card.GetComponent<SpriteRenderer>();
                                temp.DOColor(white_color, 0.25f);
                            }
                            else
                            {
                                // card_item_list[i][j].sheep_card.todark.Play();
                                SpriteRenderer temp = card_item_list[i][j].sheep_card.GetComponent<SpriteRenderer>();
                                temp.DOColor(dark_color, 0.25f);

                            }
                        }
                    }


                    card_item_list[i][j].can_click = can_click;
                }
            }
            List<Card_item> order_list = new List<Card_item>();
            for (int i = 0; i < card_item_list.Count; i++)
            {
                for (int j = 0; j < card_item_list[i].Count; j++)
                {
                    card_item_list[i][j].sheep_card.GetComponent<SpriteRenderer>().sortingOrder = 0;
                    if (card_item_list[i][j].can_click && !card_item_list[i][j].in_slot && !card_item_list[i][j].is_out)
                    {
                        order_list.Add(card_item_list[i][j]);
                    }
                }
            }
            order_list.Sort((x, y) => y.pos_y.CompareTo(x.pos_y));
            for (int i = 0; i < order_list.Count; i++)
            {
                order_list[i].sheep_card.GetComponent<SpriteRenderer>().sortingOrder = i;
            }

        }
        public Color white_color = new Color(1, 1, 1, 1);
        public Color dark_color = new Color(128f / 255f, 128f / 255f, 128f / 255f, 1f);

        public void SaveJson(object a = null)
        {

            Debug.Log($"SaveJson---------------------{card_item_list.Count}");

            var json = JsonConvert.SerializeObject(card_item_list);

            Debug.Log($"SaveJson---------------------{json}");

            DataMgr.LevelData.Value = json;
        }

        void CreatSaveItem()
        {
            card_item_list = JsonConvert.DeserializeObject<List<List<Card_item>>>(jsonstr);

            jsonstr = null;
            int slot_list_index = 0;
            CreatAnimalCard.instance.creatSaveCard(card_item_list);
            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].in_slot)
                    {
                        slot_list.Add(card_item_list[i][j]);
                        slot_list_index++;
                    }

                    if (card_item_list[i][j].is_out)
                    {
                        out_list.Add(card_item_list[i][j]);

                    }
                    pool_list.Add(card_item_list[i][j]);
                }

            }
            slot_list.Sort((x, y) => x.card_type.CompareTo(y.card_type));
            for (int i = 0; i < slot_list.Count; i++)
            {
                slot_list[i].sheep_card.transform.position = new Vector3(i * card_width_slot + bg_x, bg_y, 101);
                slot_list[i].sheep_card.GetComponent<SpriteRenderer>().color = new Color(1, 1, 1, 1);

            }

        }
        private void LoadData()
        {

            var json = DataMgr.LevelData.Value;
            Debug.Log($"LoadData========= {json}");
            if (!string.IsNullOrEmpty(json))
            {
                jsonstr = json;
                // DataMgr.LevelData.Value = string.Empty;
            }
            else
            {
                Debug.Log("Data file not found!");
            }
        }

        private void SendLog(bool success)
        {
            // SetLeveldiff();
            var test = new RequestStageData();
            test.Level = GameHelper.GetLevel();
            test.Layer = SaveData.GetSaveObject().card_layer;
            test.ItemType = SaveData.GetSaveObject().this_time_cardtype;
            test.TotalItem = SaveData.GetSaveObject().all_card_numbers * 3;
            test.RemoveItem = SaveData.GetSaveObject().clear_number;
            test.Pass = success;
            test.BeginTime = (int)SaveData.GetSaveObject().start_time;
            test.EndTime = (int)GameHelper.GetNowTime();
            test.ItemCosts = SaveData.GetSaveObject().usePropsNum;



            NetApi.SettleUp(1, test, (isSuccess) =>
            {
                Debug.Log($"send log=  {isSuccess}=========== {GameHelper.GetLoginModel().Uid}");
            });

            SaveData.GetSaveObject().clear_number = 0;
            SaveData.GetSaveObject().start_time = GameHelper.GetNowTime();
            SaveData.SaveDataFunc();


        }
    }

}

public class SettleUp
{
    public int type;
    public string result;
}

public class PlayLog
{
    public int level;
    public int layer;
    public int item_type;
    public int total_item;
    public int remove_item;
    public bool pass;
    public long begin_time;
    public long end_time;
    public int[] item_costs = new int[3];
}

public class Card_item
{
    public int card_type;
    public float pos_x;
    public float pos_y;
    public int _layer;
    public bool can_click = false;
    public bool in_slot;
    // public bool is_hide;
    public bool is_out;
    public bool is_gray;
    public int out_layer;
    [JsonIgnore]
    public GameObject sheep_card;
    public bool is_extra;
}

public class SuccessData
{
    public bool IsWin;
    public float ch_number;
    public bool IsLevelSuccess;
    public bool IsH5Reward;
    public int rate;
    public int[] boost_array;
    public int level;
}
