using System;
using FairyGUI;
using FGUI.G007_makeup;
using Newtonsoft.Json;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using FGUI.A000_common;
using FGUI.G018_GameHome;
using DontConfuse;

namespace ScrewsMaster
{
    public class MakeupConfirmUI : BaseUI
    {
        private MakeupConfirmUICtrl ctrl;
        private MakeupConfirmModel model;
        private com_confirm ui;

        public int ad_cool_down = 120;
        private long userUid;


        private MakeupTaskData makeupTaskData;
        private bool is_pt = false;

        public MakeupConfirmUI(MakeupConfirmUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.MakeupConfirmUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "G007_makeup";
            uiInfo.assetName = "com_confirm";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = true;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

        #region 生命周期

        protected override void OnInit()
        {

        }

        protected override void OnClose()
        {
            HallManager.Instance.UpdateSecondEvent -= updateSpeedCD;

            GameHelper.showGameUI = true;
            SdkManager.Instance.SetDarkThough(true);
            gameDispatcher.Dispatch(GameMsg.MakeUpConfirmUIClosed);
        }

        protected override void OnBind()
        {
            ui = baseUI as com_confirm;
        }

        protected override void OnOpenBefore(object args)
        {

            userUid = GameHelper.GetLoginModel().uid;
            ad_cool_down = ConfigSystem.GetConfig<CommonModel>().WithdrawalaccelerationCD;
            //PreferencesMgr.Instance.MakeupTaskH5Time = 999999999;
            SdkManager.Instance.SetDarkThough(false);
            if (AppConst.isPt())
            {
                ui.lang.selectedIndex = com_confirm.Lang_pt;
            }
            else ui.lang.selectedIndex = com_confirm.Lang_en;

            makeupTaskData = args as MakeupTaskData;
            cash_index = makeupTaskData.tableId - 1;
            ui.btn_pay1.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Open, 1);
            });
            ui.com_task.btn_pay2.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Open, 2);
            });

            ui.btn_watch.SetClick(WatchBtnClick);

            HallManager.Instance.UpdateSecondEvent += updateSpeedCD;
            updateSpeedCD();

            InitView();
            initButtom();
            //PixPayUI.getOrderState();
            GameHelper.SetSelfAvatar((ui.com_pay.btn_menu.GetChild("loader_avatar") as GComponent).GetChild("loader_avatar") as GLoader);
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.PaySuccess, InitView);
        }

        protected override void RemoveListener()
        {
        }

        #endregion

        private void InitView(object a = null)
        {
            if (makeupTaskData == null)
            {
                return;
            }
            initTop();
            ui.btn_close.SetClick(CtrlCloseUI);
            if (makeupTaskData.status == MakeupTaskStatus.None)
            {
                if (PreferencesMgr.Instance.ExchangeAccount == null)
                {
                    OnEnter();
                    return;
                }
                if (GameHelper.needShowLevelstate(now_selectindex))
                {
                    ui.cont_state.selectedIndex = 5;
                    var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);

                    ui.text_cashneedlv.text = string.Format(ui.text_cashneedlv.text, vo.levels_need);
                    ui.text_nowcash.text = GameHelper.Get102Str(PreferencesMgr.Instance.Currency102);
                    ui.Text_Title.text = "Level " + vo.levels_need;
                    if (GameHelper.GetLevel() <= vo.levels_need)
                    {
                        (ui.btn_check_level as btn_tabblue).state.selectedIndex = 1;
                        ui.btn_check_level.SetClick(() =>
                        {
                            GameHelper.ShowTips("withdrawal level not reached.");
                        });
                    }
                    else
                    {
                        ui.btn_check_level.SetClick(() =>
                        {
                            PlayerPrefs.SetInt("cash_lv", vo.id);
                            InitView();
                        });
                    }
                    return;

                }

                OnConfirm();

            }
            else if (makeupTaskData.status == MakeupTaskStatus.Task)
            {
                OnTask();
            }
            else if (makeupTaskData.status == MakeupTaskStatus.Inline)
            {
                OnInline();
            }

        }
        private int now_selectindex = 0;
        private int cash_index = 0;
        void initTop()
        {
            Debug.Log(JsonConvert.SerializeObject(PreferencesMgr.Instance.MakeupTaskHistory));
            List<level_btn> btn_list = new List<level_btn>() { ui.com_cashlevel.btn_0, ui.com_cashlevel.btn_1, ui.com_cashlevel.btn_2 };

            List<Makeup> makeup_list = ConfigSystem.GetConfig<MakeupModel>().dataList;
            now_selectindex = makeupTaskData.tableId - 1;
            for (int i = 0; i < btn_list.Count; i++)
            {
                btn_list[i].text_Level0.text = "Level " + makeup_list[i].levels_need;
                btn_list[i].text_Level1.text = "Level " + makeup_list[i].levels_need;
                btn_list[i].text_Level2.text = "Level " + makeup_list[i].levels_need;
                // btn_list[i].text_level1.text = "Level " + makeup_list[i].levels_need;
                if (i < cash_index)
                {
                    btn_list[i].img_check.visible = true;
                }
                else
                {
                    btn_list[i].img_check.visible = false;
                }
                if (i == now_selectindex)
                {
                    btn_list[i].btn_state.selectedIndex = 1;
                }
                else if (i > cash_index)
                {
                    btn_list[i].btn_state.selectedIndex = 2;
                    int _temp_index = i;
                    btn_list[i].SetClick(() =>
                    {
                        GameHelper.ShowTips("Complete level " + makeup_list[_temp_index].levels_need + " to unlock.");
                    });
                }
                else
                {
                    btn_list[i].btn_state.selectedIndex = 0;
                    int index = i;
                    btn_list[i].SetClick(() =>
                    {
                        for (int i = PreferencesMgr.Instance.MakeupTaskHistory.Count - 1; i >= 0; i--)
                        {
                            if (PreferencesMgr.Instance.MakeupTaskHistory[i].tableId == index + 1)
                            {
                                makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory[i];
                                now_selectindex = index;
                                break;
                            }
                        }

                        InitView();
                    });
                }
            }

        }
        void initButtom()
        {
            int day = DateTime.Now.Day;
            int hour = DateTime.Now.Hour;
            Debug.Log(day);
            if (day != SaveData.GetSaveobject().login_day)
            {
                SaveData.GetSaveobject().login_day = day;
                SaveData.GetSaveobject().login_hour = 0;
                //                 public int cash_people;
                // public float cash_people_1;
                // public float cash_people_2;
                SaveData.GetSaveobject().cash_people = UnityEngine.Random.Range(500, 800);
                SaveData.GetSaveobject().cash_people_1 = UnityEngine.Random.Range(20, 30);
                SaveData.GetSaveobject().cash_people_2 = UnityEngine.Random.Range(3, 6) * 100;
                SaveData.saveDataFunc();
            }
            if (hour != SaveData.GetSaveobject().login_hour)
            {

                SaveData.GetSaveobject().cash_people += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(8, 10);
                SaveData.GetSaveobject().cash_people_1 += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(10, 15);
                SaveData.GetSaveobject().cash_people_2 += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(1, 3) * 100;
                if (hour - SaveData.GetSaveobject().login_hour >= 3) SaveData.GetSaveobject().login_hour = hour;
                SaveData.saveDataFunc();
            }



            ui.text_number0.text = SaveData.GetSaveobject().cash_people.ToString();
            ui.text_number1.text = SaveData.GetSaveobject().cash_people_1.ToString();
            ui.text_number2.text = GameHelper.GetPaymentTypeVO().payicon + SaveData.GetSaveobject().cash_people_2;
            ui.text_cashdate.text = string.Format(ui.text_cashdate.text, DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day);

        }

        private void OnEnter()
        {
            GTextInput enter_input = null;

            ui.Text_Title.SetVar("payer", GameHelper.GetPaymentPayer()).FlushVars();
            ui.text_smaill_title.SetVar("payer", GameHelper.GetPaymentPayer()).FlushVars();
            // if (AppConst.isPt())
            // {
            //     ui.text_title.SetVar("payer", "Pix").FlushVars();
            //     ui.text_smaill_title.SetVar("payer", "Pix").FlushVars();
            // }
            if (GameHelper.GetCurrCountry().ToUpper().Equals("RU"))
            {
                ui.com_info.cont_type.selectedIndex = com_enter.Type_phone;
                enter_input = ui.com_info.enter_phone;
            }
            else
            {
                ui.com_info.cont_type.selectedIndex = com_enter.Type_email;
                enter_input = ui.com_info.enter_email;
            }

            ui.cont_state.selectedIndex = ui._State_enter;
            ui.btn_tab.SetClick(() =>
            {
                var account = enter_input.text.Replace(" ", "");
                if (account == null || account == "")
                {
                    GameHelper.ShowTips("Please enter the correct account information", true);
                    return;
                }

                if (!GameHelper.CheckAccountValidly(account))
                {
                    GameHelper.ShowTips("Please enter the correct account information", true);
                    return;
                }

                var fname = ui.com_fname.enter_fname.text.Replace(" ", "");
                if (!GameHelper.CheckNameValidly(fname))
                {
                    GameHelper.ShowTips("Please enter the correct account information", true);
                    return;
                }

                var lname = ui.com_lname.enter_lname.text.Replace(" ", "");
                if (!GameHelper.CheckNameValidly(lname) && !AppConst.isPt())
                {
                    GameHelper.ShowTips("Please enter the correct account information", true);
                    return;
                }
                PreferencesMgr.Instance.ExchangeAccount = account;
                PreferencesMgr.Instance.ExchangeName = $"{fname} {lname}";
                PreferencesMgr.Instance.short_name = fname;
                PreferencesMgr.Instance.long_name = lname;
                showPaypal();
                //uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupStepUI_Open, makeupTaskData);
                //CtrlCloseUI();
            });

            ui.btn_back.SetClick(() =>
            {
                CtrlCloseUI();
                // GuideCtrl.Instance.Dispatch("second");
            });
        }

        void showPaypal()
        {
            ui.cont_state.selectedIndex = 4;

            if (makeupTaskData == null)
            {
                return;
            }


            ui.com_pay.text_name.text = PreferencesMgr.Instance.ExchangeName;
            ui.com_pay.text_email.text = PreferencesMgr.Instance.ExchangeAccount;

            ui.com_pay.btn_change.SetClick(() =>
            {
                PreferencesMgr.Instance.ExchangeName = null;
                PreferencesMgr.Instance.ExchangeAccount = null;
                ui.cont_state.selectedIndex = 0;

                // uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData);
                // CtrlCloseUI();
            });

            //ui.btn_confirm.touchable = false;
            //GameHelper.PlayFGUIFx(ui.fx_in, true, () => { ui.btn_confirm.touchable = true; });

            ui.btn_confirm.SetClick(() =>
            {
                var info = new
                {
                    email = PreferencesMgr.Instance.ExchangeAccount,
                    first_name = PreferencesMgr.Instance.short_name,
                    last_name = PreferencesMgr.Instance.long_name
                };
                NetworkKit.PostWithHeader<orderState>("shop/payOutUserInfo", info, (isSuccess, obj) =>
                {
                    if (isSuccess)
                    {
                    }
                });
                // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_message, 1);
                InitView();
                // uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData);
                //CtrlCloseUI();
            });

            //TextureHelper.GetCardIcon(true, spr => { ui.loader_payer.texture = spr; });

            // ui.text_warn.SetVar("app", Application.productName).FlushVars();
            // if (GameHelper.GetCurrCountry().ToUpper().Equals("RU"))
            // {
            //     ui.text_warn.SetVar("payer", "Qiwi").FlushVars();
            //     ui.com_info.cont_counrty.selectedIndex = com_info.Counrty_ru;
            //     ui.btn_confirm.country.selectedIndex = btn_confirm.Country_ru;
            //     ui.com_trans.cont_country.selectedIndex = com_trans.Country_ru;
            //     ui.lang.selectedIndex = com_step.Lang_en;
            // }
            // else if (AppConst.isPt())
            // {
            //     ui.text_warn.SetVar("payer", "Pix").FlushVars();
            //     ui.com_info.cont_counrty.selectedIndex = com_info.Counrty_pt;
            //     ui.btn_confirm.country.selectedIndex = btn_confirm.Country_ru;
            //     ui.com_trans.cont_country.selectedIndex = com_trans.Country_pt;
            //     ui.lang.selectedIndex = com_step.Lang_pt;
            // }
            // else
            // {
            //     ui.text_warn.SetVar("payer", "Paypal").FlushVars();
            //     ui.com_info.cont_counrty.selectedIndex = com_info.Counrty_default;
            //     ui.btn_confirm.country.selectedIndex = btn_confirm.Country_default;
            //     ui.com_trans.cont_country.selectedIndex = com_trans.Country_default;
            //     ui.lang.selectedIndex = com_step.Lang_en;
            // }


        }

        private void OnConfirm()
        {
            ui.cont_state.selectedIndex = ui._State_confirm;

            var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);
            if (vo == null)
            {
                return;
            }

            ui.text_condi1.SetVar("cash", GameHelper.Get102Str(vo.item_need)).FlushVars();
            ui.pb_condi1.max = vo.item_need;
            var curValue = Math.Min(GameHelper.Get102(), vo.item_need);
            ui.pb_condi1.value = (double)curValue;
            ui.pay_text1.text =
                String.Format("Pague [color=#18a218][size=44]R${0}[/size][/color] para pular anúncios",
                    (ConfigSystem.GetConfig<CommonModel>().purchase1 + ",00"));
            var textTitle = ui.pb_condi1.GetChild("title");
            if (textTitle != null)
            {
                textTitle.text = $"{GameHelper.Get102Str(curValue)}/{GameHelper.Get102Str(vo.item_need)}";
            }


            var taskTime = (int)((float)vo.task_need / 60 * 100) * 0.01F;
            var completeTaskTime = (int)((float)PreferencesMgr.Instance.MakeupTaskH5Time / 60 * 100) * 0.01F;
            var completeTaskValue = Math.Min(completeTaskTime, taskTime);
            ui.text_condi2.SetVar("hot", taskTime.ToString()).FlushVars();
            ui.pb_condi2.max = taskTime;
            ui.pb_condi2.value = completeTaskValue;
            ui.pb_condi2.title.text = $"{completeTaskValue}/{taskTime}";
            if (PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need && AppConst.isPt())
            {
                ui.show_pay.selectedIndex = com_confirm.Show_pay_true;
            }
            else ui.show_pay.selectedIndex = com_confirm.Show_pay_false;

            ui.text_wallet.SetVar("Payer", GameHelper.GetPaymentPayer()).FlushVars();
            if (AppConst.isPt()) ui.text_wallet.text = "Pix";
            ui.text_cash.text = makeupTaskData.GetAmountStr();
            ui.text_account.text = PreferencesMgr.Instance.ExchangeAccount;

            if (GameHelper.Get102() >= vo.item_need &&
                completeTaskTime >= taskTime)
            {
                ui.cont_confirm.selectedIndex = ui._Confirm_ready;
                (ui.btn_earn as btn_tabblue).state.selectedIndex = 0;
                ui.btn_earn.SetClick(() =>
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone);

                    makeupTaskData.SetStatus(MakeupTaskStatus.Task);
                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                    OnTask();
                });
            }
            else
            {
                ui.cont_confirm.selectedIndex = ui._Confirm_none;
                // (ui.btn_earn as btn_tabblue).state.selectedIndex = 1;
                ui.btn_earn.SetClick(() =>
                {
                    if (UIManager.Instance.IsExistUI(UIConst.GameHomeUI))
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Close);
                        var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ;
                        ShowScrews.Instance.InitLogic(level);
                        AudioManager.Instance.PlayBGM(AudioConst.PlayingBg);
                    }
                    CtrlCloseUI();
                    // AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone);
                    // // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open);
                    // GameDispatcher.Instance.Dispatch(GameMsg.GotoH5);

                    // //GameDispatcher.Instance.Dispatch(GameMsg.MainTab, 1);

                    // CtrlCloseUI();
                    // WebviewManager.Instance.SetDarkThough(true);
                });
            }
        }

        private void OnTask()
        {
            var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);
            if (vo == null)
            {
                return;
            }

            ui.cont_state.selectedIndex = ui._State_task;
            ui.com_task.text_orderid.text = makeupTaskData.orderID;
            ui.com_task.text_task_title.SetVar("ad", vo.ad_need.ToString()).FlushVars();
            ui.com_task.text_ads.text = $"{makeupTaskData.videoCount}/{vo.ad_need}";
            if (AppConst.isPt() && makeupTaskData.videoCount < vo.ad_need) ui.com_task.lang.selectedIndex = com_task.Lang_pt;
            else ui.com_task.lang.selectedIndex = com_task.Lang_en;
            ui.com_task.pay_text1.text = String.Format("Pague [color=#18a218][size=44]R${0}[/size][/color] para pular anúncios",
                (ConfigSystem.GetConfig<CommonModel>().purchase2 + ",00"));
            ui.com_task.text_payer.SetVar("amt", makeupTaskData.GetAmountStr())
                .SetVar("payer", GameHelper.GetPaymentPayer()).FlushVars();
            if (makeupTaskData.videoCount >= vo.ad_need)
            {
                ui.com_task.cont_process.selectedIndex = 1;
            }
            else ui.com_task.cont_process.selectedIndex = 0;
            if (makeupTaskData.videoCount >= vo.ad_need)
            {
                (ui.btn_cashout as btn_tabblue).state.selectedIndex = 0;
                ui.btn_cashout.SetClick(() =>
                {


                    GameHelper.ShowLoading(1, 2, () =>
                    {
                        ConsumeSystem.Consume(vo.item, vo.item_need, isSuccess =>
                        {
                            makeupTaskData.SetStatus(MakeupTaskStatus.Inline);
                            makeupTaskData.inlineInitNum =
                                CommonHelper.RandomRange(ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                    ConfigSystem.GetConfig<CommonModel>().inlineInitNum[1]);
                            makeupTaskData.inlineNum = CommonHelper.RandomRange(
                                ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                makeupTaskData.inlineInitNum);
                            makeupTaskData.order_time = GameHelper.GetNowTime();
                            PreferencesMgr.Instance.SaveMakeupTaskHistory();
                            //OnInline();
                            Debug.Log(JsonConvert.SerializeObject(vo));
                            if (vo.id == 1)
                            {
                                // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash1, 1);
                            }
                            else if (vo.id == 2)
                            {
                                // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash2, 1);
                            }
                            else if (vo.id == 3)
                            {
                                // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash3, 1);
                            }
                            if (vo.id != 3)
                            {
                                cash_index++;
                            }
                            InitView();
                            if (vo.id == 3)
                            {
                                PlayerPrefs.SetInt("cash_lv", 2);
                                makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                            }

                        });
                    });



                });
            }
            else
            {
                //  (ui.btn_cashout as btn_tabblue).state.selectedIndex = 1;
                ui.btn_cashout.SetClick(() =>
                {
                    if (UIManager.Instance.IsExistUI(UIConst.GameHomeUI))
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Close);
                        var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ;
                        ShowScrews.Instance.InitLogic(level);
                        AudioManager.Instance.PlayBGM(AudioConst.PlayingBg);
                    }
                    CtrlCloseUI();
                });
            }

        }

        private void OnInline()
        {
            CheckBtnWatchStatus();

            ui.cont_state.selectedIndex = ui._State_query;

            ui.text_payhint.SetVar("account", PreferencesMgr.Instance.ExchangeAccount).FlushVars();

            ui.text_query.SetVar("cur", makeupTaskData.inlineNum.ToString())
                .SetVar("tol", makeupTaskData.inlineInitNum.ToString()).FlushVars();

            CheckActive(makeupTaskData.tableId);
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
            ui.btn_tab.SetClick(CtrlCloseUI);

            ui.btn_record.SetClick(() =>
            {
                //uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupRecordUI_Open);
                // MainTabUI.getIns().OnGameTab(3);
                CtrlCloseUI();
            });

            RefreshRecordData();
        }

        #region 兑换加速
        private void RefreshRecordData()
        {
            var data = makeupTaskData;
            var com_rank = ui.com_newRecord.com_rank;
            var com_cord = ui.com_newRecord.com_cord;

            com_cord.email_text.text = PreferencesMgr.Instance.ExchangeAccount;
            com_cord.number_text.text = data.inlineNum + "/" + data.inlineInitNum;

            var redeemVOModel = ConfigSystem.GetConfig<MakeupModel>().dataList
                                .FirstOrDefault(redeem => redeem.id == data.tableId);
            if (redeemVOModel == null) return;

            if (redeemVOModel.AD_Limit_times <= data.WatchVideoSpeedNum)
            {
                ui.btn_watch.enabled = false;
                ui.btn_watch.visible = false;
                com_rank.content1.selectedIndex = 1;//com_rank.Content1_complete;
                com_rank.text_rank1.SetVar("rank", data.WatchVideoSpeedNum.ToString()).FlushVars();
            }
            else
            {
                ui.btn_watch.enabled = true;
                ui.btn_watch.visible = true;
                com_rank.content1.selectedIndex = 0;//com_rank.Content1_speeding;
                com_rank.text_rank1.SetVar("rank", redeemVOModel.AD_Down.ToString()).FlushVars();
            }

            if (redeemVOModel.Login_Limit_times <= data.loginSpeedNum)
            {
                com_rank.content2.selectedIndex = 1;//com_rank.Content2_complete;
                com_rank.text_rank2.SetVar("rank", redeemVOModel.Login_Limit_times.ToString()).FlushVars();
            }
            else
            {
                com_rank.content2.selectedIndex = 0;//com_rank.Content2_speeding;
                var loginRans = GameHelper.GetCommonModel().inlineLoginDown[0] + "-" + GameHelper.GetCommonModel().inlineLoginDown[1];
                com_rank.text_rank2.SetVar("rank", loginRans).FlushVars();
            }

            if (redeemVOModel.Active_Limit_times <= data.activeSpeedNum)
            {
                com_rank.content3.selectedIndex = 1;//com_rank.Content3_complete;
                com_rank.text_rank3.SetVar("rank", redeemVOModel.Active_Limit_times.ToString()).FlushVars();
            }
            else
            {
                com_rank.content3.selectedIndex = 0;//com_rank.Content3_speeding;

                com_rank.text_rank3.SetVar("time", redeemVOModel.Active_time.ToString()).FlushVars();
                com_rank.text_rank3.SetVar("rank", redeemVOModel.Active_time_Down.ToString()).FlushVars();

                if (CommonHelper.activeTimes.TryGetValue(data.tableId, out int openTimes))
                {
                    Debug.Log($"openTimes ===== {openTimes}, data.tableId=== activeTimes_{data.tableId}");
                    if (openTimes > 1)
                    {
                        //活跃的分钟数
                        int min_num = ((int)Time.time - data.activeMinute) / 60;

                        //是配置的活跃时间的多少倍
                        int active_times = min_num / redeemVOModel.Active_time;

                        Debug.Log($"min_num=== {min_num} {active_times} ");
                        if (active_times > 0)
                        {
                            data.activeMinute = (int)Time.time;
                            // 可以加速多少排名
                            int rank_num = active_times * redeemVOModel.Active_time_Down;
                            var last = data.activeSpeedNum;
                            data.activeSpeedNum += rank_num;
                            Debug.Log($"rank_num=== {rank_num} {last} {data.activeSpeedNum} {redeemVOModel.Active_Limit_times}");
                            if (data.activeSpeedNum > redeemVOModel.Active_Limit_times)
                            {
                                rank_num = redeemVOModel.Active_Limit_times - last;
                                data.activeSpeedNum = redeemVOModel.Active_Limit_times;
                            }
                            data.inlineNum -= rank_num;

                            Debug.Log($"订单为： {data.tableId} 通过活跃时间减少的排名为：{rank_num}");

                            if (data.inlineNum < GameHelper.GetCommonModel().inlineMin)
                            {
                                data.inlineNum = GameHelper.GetCommonModel().inlineMin;
                            }
                        }
                    }
                    else
                    {
                        data.activeMinute = (int)Time.time;
                    }
                }
            }

            com_cord.text_amt.text = $"+{data.amountStr}";
            if (data.order_time != 0)
            {
                com_cord.time_text.text = DateTimeManager.Instance.TimestampToString(data.order_time);
            }

            com_rank.text_ranks.text = data.inlineNum.ToString();
        }

        void CheckBtnWatchStatus()
        {
            var data = makeupTaskData;

            if (data == null)
            {
                return;
            }
            var CardRedeemVOModel = ConfigSystem.GetConfig<MakeupModel>().dataList
                    .FirstOrDefault(redeem => redeem.id == data.tableId);
            if (CardRedeemVOModel == null) return;

            bool isShow = CardRedeemVOModel.AD_Limit_times > data.WatchVideoSpeedNum && data.inlineNum > GameHelper.GetCommonModel().inlineMin;

            ui.btn_watch.enabled = isShow;

        }

        void updateSpeedCD()
        {
            var lastTimes = PlayerPrefs.GetInt($"speed_ad_cool_times_{userUid}", 0);
            if (GameHelper.GetNowTime() < lastTimes + ad_cool_down)
            {
                ui.btn_watch.enabled = false;
                ui.btn_watch.show_cd.selectedIndex = 1;//btn_watch.Show_cd_cd;
                ui.btn_watch.text_cd.text = CommonHelper.TimeFormat(
                   lastTimes + ad_cool_down - Convert.ToInt32(GameHelper.GetNowTime()),
                   CountDownType.Hour);
            }
            else
            {
                HallManager.Instance.UpdateSecondEvent -= updateSpeedCD;
                ui.btn_watch.enabled = true;
                ui.btn_watch.show_cd.selectedIndex = 0;//btn_watch.Show_cd_none;
            }

        }

        private void CheckActive(int index)
        {
            if (CommonHelper.activeTimes.TryGetValue(index, out int value))
            {
                value++;
                // Debug.Log($"CheckActive2: {index} {value}");
                CommonHelper.activeTimes[index] = value;

            }
            else
            {
                CommonHelper.activeTimes.Add(index, 1);
            }

        }

        void WatchBtnClick()
        {

            HallManager.Instance.UpdateSecondEvent -= updateSpeedCD;
            if (GameHelper.GetNowTime() <= PlayerPrefs.GetInt($"speed_ad_cool_times_{userUid}", 0) + ad_cool_down)
            {
                Debug.Log("not click");
                return;
            }

            GameHelper.ShowVideoAd("reward_OpeningDollarBills", isSuccess =>
                {
                    if (isSuccess)
                    {
                        ui.btn_watch.enabled = false;
                        TimerHelper.mEasy.AddTimer(1.5f, () =>
                        {
                            var ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                            PlayerPrefs.SetInt($"speed_ad_cool_times_{userUid}", ad_times);
                            HallManager.Instance.UpdateSecondEvent += updateSpeedCD;
                            InitView();
                        });

                    }
                });

            // var adNum = PreferencesMgr.Instance.RealWatchVideo;
            // Debug.Log($"adNum========: {adNum}");

        }

        #endregion
    }
}