using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DG.Tweening;
using FairyGUI;
using FGUI.Common_01;
using FGUI.Game_04;
using IgnoreOPS;
using Newtonsoft.Json;
using SGModule.Net;
using SGModule.NetKit;
using Spine.Unity;
using Unity.VisualScripting;
using UnityEngine;
using Random = UnityEngine.Random;

namespace ChillConnect
{
    public class RainPlayUI : BaseUI
    {
        private RainPlayUICtrl ctrl;
        private RainPlayModel model;
        private com_game ui;

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

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "Game_04";
            uiInfo.assetName = "com_game";
            uiInfo.layerType = UILayerType.Bottom;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = false;
            uiInfo.isTickUpdate = true;
        }
        private Action closeCallback;
        private Action closeCallback1;
        private Action Callback;
        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 = 7.1f;
        private readonly float card_height = 7.2f;

        private float real_card_width = 7.1f;  //视觉宽度
        private float real_card_height = 7.2f;  //视觉高度

        private readonly float card_width_slot = 6.5f;

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

        private int card_layer = 2;

        private int all_card_numbers;
        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;
        private float bg_x = -22.8f;
        private float bg_y = GameObject.Find("card_bg").transform.position.y + 0.32f;

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

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

        }

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

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

        }

        void UpdateEvent()
        {
            long t = SaveData.GetSaveObject().failed_pack_time;

            if (t > GameHelper.GetNowTime())
            {
                ui.btn_failpack.visible = true;
                long time_ = t * 1000 - GameHelper.getNowTimeByMillisecond();
                DateTime oldDate = new DateTime(1970, 1, 1);
                oldDate = oldDate.AddMilliseconds(time_);
                ui.btn_failpack.GetChild("lab_time").text = DateTimeManager.Instance.DateTimeToFFFString(oldDate);
            }
            else
            {
                ui.btn_failpack.visible = false;
                // HallManager.Instance.UpdateEvent -= UpdateEvent;
            }
        }

        private decimal updateTime;
        SaveingPotClass makeupTaskData = SaveData.GetSaveObject().saveingpot_history[SaveData.GetSaveObject().saveingpot_history.Count - 1];
        public override void OnUpdate()
        {
            //             updateTime += (decimal)Time.deltaTime;
            //             if (updateTime >= 1)
            //             {
            //                 DataMgr.MakeupTaskH5Time += updateTime;
            //
            //                 if (makeupTaskData != null && makeupTaskData.status == SaveingPotTaskStatus.None)
            //                 {
            //                     if (DataMgr.ExchangeAccount != null)
            //                     {
            //                         makeupTaskData.H5Time += (float)updateTime;
            //                     }
            //
            //                 }
            //                 updateTime = 0;
            //             }
        }

        protected override void OnOpenBefore(object args)
        {

            if (Screen.safeArea.y != 0)
            {
                 ui.btn_gold.y += 68;

            }


            if (GameHelper.IsGiftSwitch())
            {
                ui.btn_money.visible = true;
            }

            var anim_paly = FXManager.Instance.SetFx<SkeletonAnimation>(ui.btn_gold.GetChild("gold_anim") as GGraph, Fx_Type.fx_coin, ref closeCallback1);
            anim_paly.state.SetAnimation(0, "animation", true);

            GameHelper.IsShowFirstReward();

            CreateGoldtimeList();

            layer_array = new[] { 19, };
            type_array = new[] { 14, };
            all_array = new[] { 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.GetConfig<CommonModel>().lobbyrewrdtime * 60;



            // ui.btn_head.SetClick(() =>
            // {
            //     // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open);
            //     GameHelper.showGameUI = false;
            // });
            // ui.btn_game_menu.SetClick(() => {
            //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open);
            // });
            ui.btn_close.SetClickDownEffect(1.0f);
            ui.btn_close.SetClick(() =>
            {
                //OnBackToHall();
                uiCtrlDispatcher.Dispatch(UICtrlMsg.GameMenuUI_Open);
            });
            SetAvatar();
            SetName();

            HallManager.Instance.UpdateSecondEvent += timeEvent;
            HallManager.Instance.UpdateSecondEvent += GameHelper.AddGameTime;
            HallManager.Instance.UpdateSecondEvent += GameHelper.SetGameTimes;
            HallManager.Instance.UpdateEvent += UpdateEvent;
            timeEvent();
            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)
            {
                PlayerPrefs.SetInt("_time", 0);
                SaveData.GetSaveObject().time_task_record = new List<int>();
                GameHelper.SetGameday();
            }

            ui.btn_noads.SetClick(() =>
            {
                if (!SaveData.GetSaveObject().is_get_packreward && !SaveData.GetSaveObject().is_get_removead)
                {
                    if (ui.btn_noads.GetChild("img_ad").visible)
                    {
                        PackRewardData param = new PackRewardData();
                        param.isAutoPop = false;
                        param.isNeedScroll = true;
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param);
                    }
                    else
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open);
                    }

                }
                else if (SaveData.GetSaveObject().is_get_packreward)
                {
                    PackRewardData param = new PackRewardData();
                    param.isAutoPop = false;
                    param.isNeedScroll = true;
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param);
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open);
                }
                GameHelper.showGameUI = false;
            });

            SetLevelProgress();
            (ui.btn_money as com_money).btn_ch.title = GameHelper.getDesByKey("ch_out_1");

        }

        void timeEvent()
        {
            if (SaveData.GetSaveObject().addview_off_time > GameHelper.GetNowTime() && GameHelper.IsGiftSwitch())
            {
                if (!effect_show)
                    ui.btn_add.type.selectedIndex = 1;
                ui.btn_add.type.selectedIndex = 1;
                ui.btn_add.text_offtime.text = CommonHelper.TimeFormat(SaveData.GetSaveObject().addview_off_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
            }
            else
            {
                ui.btn_add.type.selectedIndex = 0;
            }

            int time = SaveData.GetSaveObject()._goldtime[0];
            com_gold btn_gold = ui.btn_gold as com_gold;
            if (time + Paidcoins_list[0].receive_CD < GameHelper.GetNowTime())
            {
                btn_gold.state.selectedIndex = 2;
                // btn_gold.red.visible = true;
            }
            else btn_gold.state.selectedIndex = 1;

            ui.btn_task_pass.GetChild("red").visible = SaveData.battlepassred();
            // ui.btn_task.red.visible = SaveData.getRed();
            if (!GameHelper.IsGiftSwitch()) return;


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

            if ((!SaveData.GetSaveObject().is_get_packreward || !SaveData.GetSaveObject().is_get_removead) && !SaveData.GetSaveObject().is_autopack_show
             && (Time.time > (ConfigSystem.GetConfig<CommonModel>().Activetimes * 60)))
            {
                Window Popup = GRoot.inst.GetChild("Popup") as Window;
                if (Popup.GetChildren().Length > 0) return;
                PackRewardData param = new PackRewardData();
                param.isAutoPop = true;
                param.isNeedScroll = false;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param);
                SaveData.GetSaveObject().is_autopack_show = true;
                SaveData.GetSaveObject().is_autopack_show_day = DateTime.Now.Day;
                SaveData.saveDataFunc();

            }
            if (DataMgr.MakeupTaskHistory.Value.Count < 1)
                return;
            MakeupTaskData data = DataMgr.MakeupTaskHistory.Value[DataMgr.MakeupTaskHistory.Value.Count - 1];
            if (data.status != MakeupTaskStatus.Level)
            {
                (ui.btn_money as com_money).group_tips.visible = false;
                return;
            }
            if (data.ch_time > GameHelper.GetNowTime())
            {
                (ui.btn_money as com_money).text_time.text = "Only " + CommonHelper.TimeFormat((int)data.ch_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
            }
            else
            {
                (ui.btn_money as com_money).group_tips.visible = false;
                return;
            }

            time_number++;
            if (time_number > 15)
            {
                (ui.btn_money as com_money).group_tips.visible = true;
            }
            if (time_number > 20)
            {
                (ui.btn_money as com_money).group_tips.visible = false;
                time_number = 0;
            }
        }
        private int time_number = 0;
        public void setBtnAds(object a = null)
        {
            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_.img_pack.visible = false;
                btn_.img_ad.visible = true;
                //  btn_.visible = false;
            }
            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;
            }

        }

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

                }
            }
            SaveJson();


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

        private void SetLevelProgress()
        {
            // float level_progress = ShowResurgence();
            // ui.progress_level.max = 1;
            // ui.progress_level.value = level_progress;
        }

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

        private void OnChangeAvatar(ChangeValue<int> obj)
        {
            SetAvatar();
        }


        private void SetAvatar()
        {
            // GameHelper.SetSelfAvatar(ui.btn_head.GetChild("load_avatar") as GLoader);
        }
        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);
            GameDispatcher.Instance.AddListener(GameMsg.Ad_success, ad_success);
            GameDispatcher.Instance.AddListener(GameMsg.sendLog, SendLog);
            GameDispatcher.Instance.AddListener(GameMsg.reset_game, ReSetGame);
            GameDispatcher.Instance.AddListener(GameMsg.card_click, CardClick);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshGame, RefreshGame);
            GameDispatcher.Instance.AddListener(GameMsg.Update102, SetTopCurr);
            GameDispatcher.Instance.AddListener(GameMsg.Update101, SetTopCurr);
            GameDispatcher.Instance.AddListener(GameMsg.ExitGame, OnBackToHall);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshRedDot, RefreshRed);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshHallRank, RefreshRed);
            GameDispatcher.Instance.AddListener(GameMsg.resurgence, Resurgence);
            GameDispatcher.Instance.AddListener(GameMsg.resurgence_close, ChangeSlotState);
            GameDispatcher.Instance.AddListener(GameMsg.ThreeDaysGiftUIClose, checkThreeGift);
            GameDispatcher.Instance.AddListener(GameMsg.noads_refresh, setBtnAds);
            GameDispatcher.Instance.AddListener(GameMsg.add_points, AddPoints);
            // 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);
            GameDispatcher.Instance.RemoveListener(GameMsg.reset_game, ReSetGame);
            GameDispatcher.Instance.RemoveListener(GameMsg.Ad_success, ad_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.sendLog, SendLog);
            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.ThreeDaysGiftUIClose, checkThreeGift);
            GameDispatcher.Instance.RemoveListener(GameMsg.noads_refresh, setBtnAds);
            GameDispatcher.Instance.RemoveListener(GameMsg.add_points, AddPoints);


        }
        #endregion


        //初始化页面逻辑
        private void InitView()
        {
            ui.fairyBatching = true;

            int level = GameHelper.GetLevel();
            ui.text_level.text = level.ToString();

            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_failpack.SetClick(() =>
            {
                float complte_progress = showResurgence();
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, complte_progress);
            });

            ui.btn_task_pass.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassViewUI_Open); });

            ui.btn_look_ad.SetClick(LookAd);
            ui.btn_three_day.SetClick(() =>
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open);
            });

            if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch())
            {
                ui.btn_saveingpot.visible = true;
            }
            ui.btn_saveingpot.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_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.AddViewoffUI_Open); return;//zhushi

                // GameHelper.ShowTips("Coming Soon!");
                if (SaveData.GetSaveObject().addview_off_time > GameHelper.GetNowTime() && GameHelper.IsGiftSwitch())
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Open);
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuyslotUI_Open);
                }
                GameHelper.showGameUI = false;
            });

            SetItemNumber();
            SetSlotNumber();
            SetTopCurr();
            setBtnAds();

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


            if (out_list.Count == 0)//是否通关
            {
                bool all_clear = CheckSuccess();
                if (all_clear)
                {
                    //通关成功
                    float[] cash_array = GameHelper.GetRewardValue(2);

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


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

                        var temp = new SuccessData();
                        temp.IsWin = true;
                        temp.cash_number = cash_array[0];
                        temp.rate = (int)cash_array[1];
                        temp.IsLevelSuccess = true;
                        temp.IsH5Reward = false;
                        temp.boost_array = GameHelper.GetRewardBoost(2);
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp);
                    });
                }
            }

            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<PassportrewardsModel>().DataList[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;
            }

            checkThreeGift();
            if (!SaveData.GetSaveObject().have_slot && GameHelper.IsGiftSwitch())
            {
                ui.btn_add.t0.Play(() =>
                {
                    effect_show = false;
                });
            }
            RankSystemMgr.Instance.checkUsers();
            ui.btn_rank.visible = GameHelper.IsGiftSwitch();
            ui.btn_rank.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RankUI_Open); });
            if (GameHelper.IsGiftSwitch())
            {
                var data = SaveData.GetRankData().rankRewardData;
                if (data.Count > 0 && !HallManager.Instance.isShowRankView)
                {
                    HallManager.Instance.isShowRankView = true;
                    float delay = 2.5f;
                    if (GameHelper.IsShowLevelTips())
                    {
                        delay = 3.5f;
                    }
                    DOVirtual.DelayedCall(delay, () =>
                    {
                        uiCtrlDispatcher.Dispatch(UICtrlMsg.RankRewardUI_Open);
                    });
                }
            }
            RefreshRed();

            // Debug.Log($"barry initView==== {SaveData.GetSaveObject().card_layer}  {SaveData.GetSaveObject().all_card_numbers}");

        }

        private void AddPoints(object a = null)
        {
            int addPoints = RankSystemMgr.Instance.getAddPoints();
            if (addPoints > 0)
            {
                btn_rank btn_rank = ui.btn_rank as btn_rank;
                com_add_points add_Points = btn_rank.GetChild("add_points") as com_add_points;
                add_Points.visible = true;
                add_Points.lab_addPoints.text = "+" + addPoints;
                btn_rank.t0.Play();
            }
        }

        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;
                // btn_.t0.Play();
                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);
                });


            }
        }
        private void RefreshRed(object a = null)
        {

            try
            {
                ui.btn_rank.GetChild("red").visible = SaveData.GetRankData().rankRewardData.Count > 0;
            }
            catch
            {
                Debug.LogWarning("红点报错");
            }
        }
        private bool effect_show = true;
        void ad_success(object a = null)
        {

            var start = GameHelper.GetUICenterPosition(ui.btn_look_ad, true);
            var end = GameHelper.GetUICenterPosition(ui.btn_money, true);

            float cash = (float)a;
            start.x -= 20;
            start.y -= 50;

            // reward_data temp = new reward_data() { start = start, end = end, change = cash, type = 111 };

            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
            // GameHelper.addMoney(cash);
            // DOVirtual.DelayedCall(1, () =>
            // {
            //     DOVirtual.Float(0, (float)DataMgr.Coin.Value, 1,
            //         value => { ui.money.number_text.text = GameHelper.Get101Str((decimal)value); });
            // });


            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(102, (decimal)cash, RewardOrigin.Play)
            {
                startPosition = start,
                endPosition = new Vector2(end.x - 110, end.y - 110)
            };

            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted(success =>
            {
                if (success)
                {
                    // RefreshGold((decimal)awardNum);

                    // DOVirtual.DelayedCall(0.7f, () =>
                    // {
                    //     CtrlCloseUI();
                    // });
                }
            });

            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
            // DOVirtual.DelayedCall(1, () =>
            // {
            //     DOVirtual.Float(0, (float)DataMgr.Ticket.Value, 1,
            //         value => { ui.btn_money.GetChild("text_gold").text = ((decimal)value).ToString("0.00"); });
            // });



            ui.btn_look_ad.visible = false;


            ad_numbers++;
            if (ad_numbers == 3)
            {
                ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                PlayerPrefs.SetInt("ad_time", ad_times);
            }
            if (ad_numbers > 3)
            {
                ad_numbers = 1;
            }
            PlayerPrefs.SetInt("ad_number", ad_numbers);

        }

        private int btn_look_ad_showtime;

        private int time_count = 11;
        private com_broadcast_text1 text_ui;

        private List<Paidcoins> Paidcoins_list = ConfigSystem.GetConfig<PaidcoinsModel>().DataList;

        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 LookAd()
        {

            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardboxUI_Open);
            GameHelper.showGameUI = false;
            ui.btn_look_ad.visible = false;
        }

        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;
            }
            // }
        }

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


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

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

            com_money btn_money = ui.btn_money as com_money;
            btn_money.text_gold.text = DataMgr.Ticket.Value.ToString("0.00");
            // btn_money.btn_ch.SetClick(() =>
            // {
            //     popMakeup();
            // });
            btn_money.SetClick(() =>
            {
                popMakeup();
            });

        }

        void popMakeup()
        {
            var makeupTaskData = DataMgr.MakeupTaskHistory.Value.Last();
            var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);
            if (vo == null)
            {
                return;
            }
            GameHelper.showGameUI = false;
            uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData);
        }

        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.bg.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.bg.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.bg.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.bg.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.bg.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.bg.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.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)
        {
            if (first_reset)
            {
                first_reset = false;
                return;
            }

            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;
            }
            // SetLevelProgress();
        }
        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, -26.2f + 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 = -26.2f + 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("There are no actions that can be undone");
            }


        }
        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;
            is_showslot = false;
            if (AudioManager.Instance.IsOpenEffect)
            {
                AudioManager.Instance.PlayDynamicEffect(AudioConst.gameclick);
            }
            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);
                    }
                }

                {  //记录失败次数
                    int hide_type = -1;
                    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 (slot_list.Count == (slot_max - 1))
                        {
                            PlayPropEffect();
                        }
                        else if (slot_list.Count >= slot_max)
                        {
                            SaveData.GetSaveObject().game_fail_off_number++;
                            //  if (SaveData.GetSaveObject().addview_off_time < GameHelper.GetNowTime()) {
                            SaveData.GetSaveObject().game_fail_number++;
                            //  }
                        }
                    }

                }

                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;
                    });



                });
                RefreshRed();
                // SetLevelProgress();
            }
        }

        public List<GameBoard> GetGameConfig()
        {
            var conf_num = PlayerPrefs.GetInt("game_conf_num", 1);
            var GameConfig = ConfigSystem.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()
        {

            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;
        public Camera orthoCamera;

        private bool is_resurgence;
        private bool is_showslot;
        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)
                {
                    DOVirtual.DelayedCall(0.3f, () =>
                    {
                        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(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);
                RankSystemMgr.Instance.addGameExp(addPointType.eliminate);
                SaveData.GetSaveObject().clear_number += 3;
                if (GameHelper.IsGiftSwitch() && (Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().roomrewardrate) && !ui.btn_look_ad.visible)
                //if (GameHelper.IsGiftSwitch() && (Random.Range(0, 100) < 100) && !ui.btn_look_ad.visible)
                {
                    ui.btn_look_ad.visible = true;
                    btn_look_ad_showtime = 0;

                }


                all_clear = CheckSuccess();
                if (GameHelper.IsGiftSwitch() && !all_clear)
                {
                    if (hide_type >= 0 && Random.Range(0, 100) < ConfigSystem.GetConfig<CommonModel>().Smallrewardsrate)
                    {
                        if (hide_type != 15)
                        {//普通小额钞票


                            // 转换为FGUI坐标（这里需要根据您的FGUI设置进行调整）
                            //         Vector2 fguiPosition = new Vector2(start_card, ui.slot.y + 50);
                            //         var start = fguiPosition;
                            //         var end = GameHelper.GetUICenterPosition(ui.money.GetChild("number_text"));
                            //         float[] cash_array = GameHelper.GetRewardValue(0);
                            //         AwardData temp = new AwardData() { start = start, end = end, change = cash_array[0], type = 111 };
                            //         DOVirtual.DelayedCall(0.5f, () => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); });
                            //         GameHelper.addMoney(cash_array[0]);
                            //         DOVirtual.DelayedCall(1.5f, () =>
                            //         {
                            //             DOVirtual.Float(0, (float)DataMgr.Coin.Value, 1f,
                            // value => { (ui.money.GetChild("number_text") as GTextField).text = GameHelper.Get101Str((decimal)value); });
                            //             clearSpinepool?.Invoke();
                            //         });

                            var rewardData = new RewardData();
                            Vector2 fguiPosition = new Vector2(start_card, ui.slot.y - 60);
                            var start = fguiPosition;
                            var end = GameHelper.GetUICenterPosition(ui.btn_money.GetChild("text_gold"));
                            float[] cash_array = GameHelper.GetRewardValue(0);
                            Debug.Log(cash_array[0]);
                            var rewardSingleData = new RewardSingleData(102, (decimal)cash_array[0], RewardOrigin.AdTask)
                            {
                                startPosition = start,
                                endPosition = new Vector2(end.x - 135, end.y - 135)
                            };

                            rewardData.AddReward(rewardSingleData);
                            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
                            // rewardData.AddCompleted(success =>
                            // {
                            //     if (success)
                            //     {
                            //         // RefreshGold(awardNum);

                            //     }
                            // });
                            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);

                        }


                    }

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

                            float[] cash_array = GameHelper.GetRewardValue(1);
                            var temp = new SuccessData();
                            temp.IsWin = true;
                            temp.cash_number = cash_array[0];
                            temp.rate = (int)cash_array[1];
                            temp.IsLevelSuccess = false;
                            temp.IsH5Reward = false;
                            temp.boost_array = GameHelper.GetRewardBoost(1);
                            DOVirtual.DelayedCall(0.55f, () =>
                            {
                                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp);
                                clearSpinepool?.Invoke();
                            });


                        }

                    }
                }
            }


            if (out_list.Count == 0)
            {




                if (all_clear)
                {
                    SendLog(true);

                    GameHelper.SetLevel(GameHelper.GetLevel() + 1);
                    //通关成功
                    float[] cash_array = GameHelper.GetRewardValue(2);

                    var temp = new SuccessData();
                    temp.IsWin = true;
                    temp.cash_number = cash_array[0];
                    temp.rate = (int)cash_array[1];
                    temp.IsLevelSuccess = true;
                    temp.IsH5Reward = false;
                    temp.boost_array = GameHelper.GetRewardBoost(2);
                    DOVirtual.DelayedCall(0.5f, () =>
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp);
                    });

                    return;
                }
            }

            if (slot_list.Count >= slot_max)
            {
                GameHelper.IsTemporaryEnd = true;
                float complte_progress = showResurgence();
                if (GameHelper.GetLevelstate() != 0)
                {
                    if (SaveData.GetSaveObject().game_fail_off_number >= ConfigSystem.GetConfig<CommonModel>().AddDiscountLevel && !is_showslot && !SaveData.GetSaveObject().have_slot && GameHelper.IsGiftSwitch())
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Open);
                        SaveData.GetSaveObject().game_fail_off_number = 0;
                        if (SaveData.GetSaveObject().addview_off_time < GameHelper.GetNowTime())
                        {
                            SaveData.GetSaveObject().addview_off_time = (int)GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().AddDiscountCD;
                        }
                        is_showslot = true;

                        return;
                    }

                    if (SaveData.GetSaveObject().game_fail_number >= ConfigSystem.GetConfig<CommonModel>().AddSpaceLevel && !is_showslot && !SaveData.GetSaveObject().have_slot)
                    {

                        if (SaveData.GetSaveObject().addview_off_time > GameHelper.GetNowTime() && GameHelper.IsGiftSwitch())
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Open);
                        else
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuyslotUI_Open);
                        SaveData.GetSaveObject().game_fail_number = 0;
                        is_showslot = true;
                        return;
                    }

                    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 (SaveData.GetSaveObject().game_fail_off_number >= ConfigSystem.GetConfig<CommonModel>().AddDiscountLevel && !is_showslot && !SaveData.GetSaveObject().have_slot && GameHelper.IsGiftSwitch())
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Open);
                        SaveData.GetSaveObject().game_fail_off_number = 0;
                        if (SaveData.GetSaveObject().addview_off_time < GameHelper.GetNowTime())
                        {
                            SaveData.GetSaveObject().addview_off_time = (int)GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().AddDiscountCD;
                        }
                        is_showslot = true;
                        return;
                    }

                    if (SaveData.GetSaveObject().game_fail_number >= ConfigSystem.GetConfig<CommonModel>().AddSpaceLevel && !is_showslot && !SaveData.GetSaveObject().have_slot)
                    {

                        if (SaveData.GetSaveObject().addview_off_time > GameHelper.GetNowTime() && GameHelper.IsGiftSwitch())
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AddViewoffUI_Open);
                        else
                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuyslotUI_Open);
                        SaveData.GetSaveObject().game_fail_number = 0;
                        is_showslot = true;
                        return;
                    }
                    if ((complte_progress > ((float)ConfigSystem.GetConfig<CommonModel>().FailedGiftProgress / 100)) && !is_resurgence)
                    {

                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, complte_progress);
                        is_resurgence = true;
                        return;
                    }
                    //通关失败
                    float[] cash_array = GameHelper.GetRewardValue(2);

                    var temp = new SuccessData();
                    temp.IsWin = false;
                    temp.cash_number = cash_array[0];
                    temp.IsLevelSuccess = true;
                    temp.IsH5Reward = false;
                    temp.boost_array = GameHelper.GetRewardBoost(2);
                    DOVirtual.DelayedCall(0.5f, () =>
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp);
                    });
                }
                if (AudioManager.Instance.IsOpenEffect)
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.fellshort);
                }
            }

        }

        private float ShowResurgence()
        {
            if (SaveData.GetSaveObject().all_card_numbers == 0)
            {
                int all_num = 0;
                for (int i = 0; i < card_item_list.Count; i++)
                {
                    for (int j = 0; j < card_item_list[i].Count; j++)
                    {
                        all_num++;
                    }
                }
                SaveData.GetSaveObject().all_card_numbers = all_num;
            }

            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);
        }


        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 ? 1.3f : 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)
        {
            string save = JsonConvert.SerializeObject(card_item_list);
            if (File.Exists(jsonFilePath)) File.Delete(jsonFilePath);
            File.WriteAllText(jsonFilePath, save);

            SaveData.saveDataFunc();

        }

        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.localScale = new Vector3(card_slot_scale, card_slot_scale, 1);

                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()
        {
            // Debug.Log($"jsonFilePath========= {jsonFilePath}");
            if (File.Exists(jsonFilePath))
            {
                jsonstr = File.ReadAllText(jsonFilePath);

                File.Delete(jsonFilePath);
                //return JsonUtility.FromJson<MyData>(json);

            }
            else
            {
                Debug.Log("Data file not found!");
                //  return null;
            }
        }

        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++;
                }
            }
            // if ((1 - (float)surplus_item / (SaveData.GetSaveObject().all_card_numbers * 3)) >= ((float)ConfigSystem.GetConfig<CommonModel>().FailedGiftProgress / 100))
            //{
            return 1 - (float)surplus_item / (SaveData.GetSaveObject().all_card_numbers * 3);
            //  }

            //  return 0;
        }

        private void SendLog(object 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 = (bool)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();
            for (int i = 0; i < SaveData.GetSaveObject().usePropsNum.Length; i++)
            {
                SaveData.GetSaveObject().usePropsNum[i] = 0;
            }
            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;
    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 cash_number;
    public bool IsLevelSuccess;
    public bool IsH5Reward;
    public int rate;
    public int[] boost_array;
}
