using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using Dont_Confuse;
using DontConfuse;
using FairyGUI;
using FGUI.Common_01;
using FGUI.tixian;
using IgnoreOPS;
using SGModule.Net;
using SGModule.NetKit;
using Spine.Unity;
using UnityEngine;
using Random = UnityEngine.Random;

namespace ChillConnect
{
    public class SaveingPotUI : BaseUI
    {
        private SaveingPotUICtrl ctrl;
        private SaveingPotModel model;
        private FGUI.tixian.com_saveingpot ui;

        private SaveingPotClass makeupTaskData;
        public int ad_cool_down = 120;
        private int broadtime = 1;

        public SaveingPotUI(SaveingPotUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.SaveingPotUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期
        protected override void OnInit()
        {

        }

        protected override void OnClose()
        {
            AdRedeemManager.Instance.Destroy();
            HallManager.Instance.UpdateSecondEvent -= updateSpeedCD;
            HallManager.Instance.UpdateSecondEvent -= Update;
            closeCallback?.Invoke();
            WebviewManager.ShezhiACT(true);

            GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot);

            if (SaveLocalData.GetSaveLocalObject().rankRewardData.Count > 0 && !HallManager.Instance.isShowRankView)
            {
                HallManager.Instance.isShowRankView = true;
                uiCtrlDispatcher.Dispatch(UICtrlMsg.RankRewardUI_Open);
            }
        }
        protected override void OnBind()
        {
            ui = baseUI as FGUI.tixian.com_saveingpot;
        }

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {//刘海屏
                ui.group_.y += Screen.safeArea.y;
            }

            WebviewManager.ShezhiACT(false);

            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Close);


            SaveingPotHelper.TestingClearTime();
            makeupTaskData = SaveData.GetSaveObject().saveingpot_history[SaveData.GetSaveObject().saveingpot_history.Count - 1];
            makeupTaskData.H5Time = 99999999;
            //  SaveData.GetSaveObject().saveingpot_ch = 999;  //zhushi
            ske_pot = FXManager.Instance.SetFx<SkeletonAnimation>(ui.ani_potparent, Fx_Type.fx_saving, ref closeCallback);
            ske_pot.state.SetAnimation(0, "edie", true);
            ui.btn_close.SetClick(() =>
            {
                CtrlCloseUI();
            });
            InitView();

            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
            {
                ui.btn_watch.GetChild("img_saveingpot").visible = true;
            }

            ui.btn_watch.SetClick(WatchBtnClick);
            AdRedeemManager.Instance.SetWatchAd(AdRedeemManager.SavingPotMakeupAd, ui.btn_task_watch as btn_watchAd, () => { });
            AdRedeemManager.Instance.Start();

            ad_cool_down = ConfigSystem.GetConfig<CommonModel>().WwalaccelerationCD;
            HallManager.Instance.UpdateSecondEvent += updateSpeedCD;
            HallManager.Instance.UpdateSecondEvent += Update;
            updateSpeedCD();
            InitBroadCast();

        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

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

        #region 消息
        protected override void AddListener()
        {
        }
        protected override void RemoveListener()
        {
        }
        #endregion

        private void Update()
        {
            if (ui.type.selectedIndex == 4)
            {
                OnTask();
            }
        }
        private SkeletonAnimation ske_pot;
        private Action closeCallback;
        //初始化页面逻辑
        private void InitView()
        {
            Debug.Log(DataMgr.ExchangeAccount);
            Makeup_2 makeupVo = ConfigSystem.GetConfig<MakeupModel_2>().GetData(makeupTaskData.tableId);
            ui.text_ad.text = string.Format(GameHelper.getDesByKey("saving_pot_5"), makeupVo.ADIncrease);
            string str = string.Format(GameHelper.getDesByKey("saving_pot_2"), makeupVo.PayIncrease);
            ui.text_pay.text = str;
            initTop();

            ske_pot.SetActive(false);
            string val = $"{SaveData.GetSaveObject().saveingpot_ch:N}";
            ui.text_lose.SetVar("num", val).FlushVars();
            // ui.text_lose.text = string.Format(ui.text_lose.text, SaveingPotHelper.getChString(SaveData.GetSaveObject().saveingpot_ch));
            if (makeupTaskData.needShowAni)
            {
                ui.type.selectedIndex = 0;

                ui.text_chprogress.text = SaveingPotHelper.getChNumber(SaveData.GetSaveObject().saveingpot_ch) + "/" + SaveingPotHelper.getChNumber(makeupTaskData.amount);
                ui.progress_ch.value = (SaveData.GetSaveObject().saveingpot_ch / makeupTaskData.amount) * 100;
                ske_pot.SetActive(true);
                Debug.Log("iiiiiiiiiiiiiiiiiiiii");
                if (SaveData.GetSaveObject().saveingpot_ch < makeupTaskData.amount)
                {
                    ui.btn_ch.title = "Go";
                    ui.btn_ch.SetClick(() =>
                    {
                        // if (UIManager.Instance.IsExistUI(UIConst.HallUI))
                        // {
                        //     GameDispatcher.Instance.Dispatch(GameMsg.MainTab, 1);
                        // }
                        // else
                        // {
                        //     buygoldParam param = new buygoldParam()
                        //     {
                        //         isShow1 = false,
                        //         is_in_game = true
                        //     };
                        //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open, param);
                        // }
                        CtrlCloseUI();
                    });

                }

                else
                {
                    ui.btn_ch.SetClick(() =>
                    {
                        makeupTaskData.needShowAni = false;
                        SaveData.saveDataFunc();
                        InitView();
                    });
                }
                if (SaveData.GetSaveObject().saveingpot_ch > SaveData.GetSaveObject().last_saveingpot_ch)
                {
                    DOVirtual.Float(SaveData.GetSaveObject().last_saveingpot_ch, SaveData.GetSaveObject().saveingpot_ch, 1,
                        value => { ui.text_nowch.text = GameHelper.Get102Str((decimal)value); });
                    ske_pot.state.SetAnimation(0, "getcash", false);
                    ske_pot.state.Complete += (a) =>
                    {
                        ske_pot.state.SetAnimation(0, "edie", true);
                    };
                }
                else ui.text_nowch.text = GameHelper.Get102Str((decimal)SaveData.GetSaveObject().saveingpot_ch);
                SaveData.GetSaveObject().last_saveingpot_ch = SaveData.GetSaveObject().saveingpot_ch;
                SaveData.saveDataFunc();
            }
            else if (makeupTaskData.status == SaveingPotTaskStatus.None)
            {
                if (DataMgr.ExchangeAccount == null)
                {
                    Debug.Log("enter");
                    OnEnter();
                }
                else
                {
                    OnConfirm();
                }
            }
            else if (makeupTaskData.status == SaveingPotTaskStatus.Task)
            {
                OnTask();
            }
            else if (makeupTaskData.status == SaveingPotTaskStatus.Inline)
            {
                // makeupTaskData.status = SaveingPotTaskStatus.ticket;
                //                 DataMgr.MakeupTaskHistory.Save();
                // InitView();
                // return;
                OnInline();
                Debug.Log("inline");
            }
            else if (makeupTaskData.status == SaveingPotTaskStatus.ticket)
            {
                onTicket();
            }
            else if (makeupTaskData.status == SaveingPotTaskStatus.code)
            {
                onCode();
            }

        }
        void WatchBtnClick()
        {

            if (GameHelper.GetNowTime() <= PlayerPrefs.GetInt($"speed_ad_cool_times_pot", 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_pot", ad_times);
                        InitView();
                        //                    });
                    }
                });

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

        }
        void updateSpeedCD()
        {
            broadtime++;
            BroadCast();
            if (makeupTaskData.needShowAni)
            {
                ui.text_remaintime.text = CommonHelper.TimeFormat((int)makeupTaskData.clear_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Day);

            }
            if (SaveingPotHelper.TestingClearTime())
            {
                InitView();
            }
            var lastTimes = PlayerPrefs.GetInt($"speed_ad_cool_times_pot", 0);
            if (GameHelper.GetNowTime() < lastTimes + ad_cool_down)
            {
                ui.btn_watch.enabled = false;
                ui.btn_watch.show_cd.selectedIndex = 1;
                ui.btn_watch.text_cd.text = CommonHelper.TimeFormat(
                   lastTimes + ad_cool_down - Convert.ToInt32(GameHelper.GetNowTime()),
                   CountDownType.Hour);
            }
            else
            {

                ui.btn_watch.enabled = true;
                ui.btn_watch.show_cd.selectedIndex = 0;
            }

        }

        private void OnInline()
        {
            CheckBtnWatchStatus();

            ui.type.selectedIndex = 5;


            CheckActive(makeupTaskData.tableId);
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);


            RefreshRecordData();
        }

        private void RefreshRecordData()
        {
            var data = makeupTaskData;
            if (data.inlineNum <= 1)
            {
                if (GameHelper.isRDExchangeMode())
                {
                    ui.cont_confirm.selectedIndex = 0;
                    ui.btn_inline_ok.SetClick(() =>
                    {
                        makeupTaskData.SetStatus(SaveingPotTaskStatus.ticket);
                        SaveData.saveDataFunc();
                        InitView();
                    });
                }
                else
                {
                    ui.cont_confirm.selectedIndex = 0;
                    ui.type.selectedIndex = 6;
                    ui.text_payhint.text = "You will get the " + makeupTaskData.amountStr + " for 90 days";
                    ui.text_query.text = DataMgr.ExchangeAccount.Value;
                    ui.btn_confirm.SetClick(() =>
                    {
                        CtrlCloseUI();
                    });
                }
            }
            else
            {
                ui.cont_confirm.selectedIndex = 1;
            }

            var com_rank = ui.com_newRecord.com_rank;
            com_rank.lab_title_des.text = GameHelper.getDesByKey("saving_pot_3");
            com_rank.lab_rank_tips.text = GameHelper.getDesByKey("saving_pot_4");



            var rdVOModel = ConfigSystem.GetConfig<MakeupModel_2>().DataList
                                .FirstOrDefault(rd => rd.id == data.tableId);
            if (rdVOModel == null) return;

            if (rdVOModel.AD_Limit_times <= data.WatchVideoSpeedNum)
            {
                ui.btn_watch.enabled = false;
                ui.btn_watch.visible = false;
                com_rank.content1.selectedIndex = 1;
                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.text_rank1.SetVar("rank", rdVOModel.AD_Down.ToString()).FlushVars();
            }

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

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

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

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

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

                        //Debug.Log($"min_num=== {min_num} {active_times} ");
                        if (active_times > 0)
                        {
                            data.activeMinute = (int)Time.time;
                            // 可以加速多少排名
                            int rank_num = active_times * rdVOModel.Active_time_Down;
                            var last = data.activeSpeedNum;
                            if (data.activeSpeedNum > rdVOModel.Active_Limit_times)
                            {
                                //  rank_num = rdVOModel.Active_Limit_times - last;
                                data.activeSpeedNum = rdVOModel.Active_Limit_times;
                            }
                            else
                            {
                                if (data.activeSpeedNum + rank_num > rdVOModel.Active_Limit_times) rank_num = rdVOModel.Active_Limit_times - data.activeSpeedNum;
                                data.activeSpeedNum += rank_num;
                                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_rank.text_ranks.text = data.inlineNum.ToString();

        }

        void onTicket()
        {
            var vo = ConfigSystem.GetConfig<MakeupModel_2>().GetData(makeupTaskData.tableId);
            ui.type.selectedIndex = 7;

            if (makeupTaskData.rdData != null && makeupTaskData.rdData.Count > 0)
            {
                makeupTaskData.rdData.Sort((a, b) =>
                {
                    if (a.isClaimed == b.isClaimed)
                    {
                        return b.coupon_mount.CompareTo(a.coupon_mount);
                    }
                    else
                    {
                        return a.isClaimed ? 1 : -1;
                    }
                });
            }
            else
            {
                makeupTaskData.rdData = new List<SaveingPotRdData>();
                int[] arr = ConfigSystem.GetConfig<CommonModel>().PotExchange;
                Array.Sort(arr, (a, b) => b.CompareTo(a));
                int remainValue = vo.item_need;
                List<int> tickets = new List<int>();
                for (int i = 0; i < arr.Length; i++)
                {
                    tickets.Add(remainValue / arr[i]);
                    remainValue = remainValue % arr[i];
                    for (int j = 0; j < tickets[i]; j++)
                    {
                        SaveingPotRdData data = new SaveingPotRdData();
                        data.code = GameHelper.GenerateUniqueKey();
                        data.coupon_mount = arr[i];
                        data.isClaimed = false;
                        makeupTaskData.rdData.Add(data);
                    }
                }
                DataMgr.MakeupTaskHistory.Save();
            }

            int value = 0;
            for (int i = 0; i < makeupTaskData.rdData.Count; i++)
            {
                if (makeupTaskData.rdData[i].isClaimed)
                {
                    value += makeupTaskData.rdData[i].coupon_mount;
                }
            }

            ui.lab_mn.text = GameHelper.Get101Str(vo.item_need - value);

            ui.list_kicket.itemRenderer = refreshItem;
            ui.list_kicket.numItems = makeupTaskData.rdData.Count;
        }

        private void refreshItem(int index, GObject obj)
        {
            com_ticket_item item = (com_ticket_item)obj;
            item.lab_num.text = GameHelper.getPrice(makeupTaskData.rdData[index].coupon_mount);

            if (makeupTaskData.rdData[index].isClaimed)
            {
                item.btn_claim.state.selectedIndex = 1;
                item.btn_claim.title = "Claimed";
            }
            else
            {
                item.btn_claim.state.selectedIndex = 0;
                item.btn_claim.title = "Claim";
            }

            item.btn_claim.SetClick(() =>
            {
                makeupTaskData.SetStatus(SaveingPotTaskStatus.code);
                makeupTaskData.rdData[index].isClaimed = true;
                makeupTaskData.lastRdData = makeupTaskData.rdData[index];
                onCode();
               // DataMgr.ImmediateSendSave();
                DataMgr.MakeupTaskHistory.Save();
                GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot);
                SaveData.saveDataFunc();
            });
        }

        void onCode()
        {
            if (makeupTaskData.lastRdData == null)
            {
                ui.type.selectedIndex = 7;
                makeupTaskData.SetStatus(SaveingPotTaskStatus.ticket);
                return;
            }
            ui.type.selectedIndex = 8;

            int value = 0;
            for (int i = 0; i < makeupTaskData.rdData.Count; i++)
            {
                if (makeupTaskData.rdData[i].isClaimed)
                {
                    value += makeupTaskData.rdData[i].coupon_mount;
                }
            }

            var vo = ConfigSystem.GetConfig<MakeupModel_2>().GetData(makeupTaskData.tableId);
            ui.lab_mn2.text = GameHelper.Get101Str(vo.item_need - value);
            ui.lab_ticket.text = GameHelper.GetPriceInt(makeupTaskData.lastRdData.coupon_mount);
            ui.lab_code.text = makeupTaskData.lastRdData.code;

            ui.btn_back.SetClick(() =>
            {
                ui.type.selectedIndex = 7;
                makeupTaskData.SetStatus(SaveingPotTaskStatus.ticket);
                InitView();
            });

            ui.btn_copy.SetClick(() =>
            {
                GameHelper.CopyText(ui.lab_code.text);
            });

            ui.btn_contact_us.SetClick(() =>
            {
                GameHelper.OpenEmail();
            });

        }

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

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

        }
        void CheckBtnWatchStatus()
        {
            var data = makeupTaskData;

            if (data == null)
            {
                return;
            }
            var CardRdVOModel = ConfigSystem.GetConfig<MakeupModel_2>().DataList
                    .FirstOrDefault(rd => rd.id == data.tableId);
            if (CardRdVOModel == null) return;

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

            ui.btn_watch.enabled = isShow;

        }
        private void OnConfirm()
        {
            ui.type.selectedIndex = 3;

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

            // ui.text_condi1.text = GameHelper.Get101Str(vo.item_need);
            // ui.pb_condi1.max = vo.item_need;
            // var curValue = Math.Min(SaveData.GetSaveObject().saveingpot_ch, vo.item_need);
            // ui.pb_condi1.value = (double)curValue;
            //  var textTitle = ui.pb_condi1.GetChild("title");
            // if (textTitle != null)
            // {
            //     textTitle.text = GameHelper.Get102Str((decimal)curValue) + "/" + GameHelper.Get102Str(vo.item_need);
            // }


            var taskTime = (int)((float)vo.task_need / 60 * 100) * 0.01F;
            // var completeTaskTime = (int)((float)makeupTaskData.H5Time / 60 * 100) * 0.01F;
            // var completeTaskValue = Math.Min(completeTaskTime, taskTime);
            // ui.text_condi2.text = taskTime.ToString();
            // ui.pb_condi2.max = taskTime;
            // ui.pb_condi2.value = completeTaskValue;
            // ui.pb_condi2.title.text = $"{completeTaskValue}/{taskTime}";
            // if (DataMgr.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", "$").FlushVars();
            // if (AppConst.isPt()) ui.text_wallet.text = "Pix";
            ui.text_ch.text = GameHelper.Get102Str((decimal)makeupTaskData.amount);
            if (!GameHelper.isRDExchangeMode()) ui.card_.visible = false;
            ui.text_account.text = DataMgr.ExchangeAccount.Value;

            if (SaveData.GetSaveObject().saveingpot_ch >= vo.item_need)
            {
                ui.cont_confirm.selectedIndex = 0;
                ui.btn_confirm.SetClick(() =>
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone);

                    makeupTaskData.SetStatus(SaveingPotTaskStatus.Task);
                    SaveData.saveDataFunc();
                    OnTask();
                });
            }
            else
            {
                ui.cont_confirm.selectedIndex = 1;
                ui.btn_confirm.SetClick(() =>
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone);
                    //  UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open);
                    //GameDispatcher.Instance.Dispatch(GameMsg.MainTab, 1);

                    CtrlCloseUI();
                });
            }
        }
        private void OnTask()
        {
            var vo = ConfigSystem.GetConfig<MakeupModel_2>().GetData(makeupTaskData.tableId);
            if (vo == null)
            {
                return;
            }
            ui.type.selectedIndex = 4;
            ui.com_task.text_task.text = "get gift card";
            ui.com_task.text_payer.text = "{amt=$0.5} directly to your gift card";
            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}";
            ui.com_task.text_payer.SetVar("amt", makeupTaskData.GetAmountStr()).FlushVars();

            if (makeupTaskData.videoCount >= vo.ad_need)
            {
                ui.com_task.cont_process.selectedIndex = 1;
                ui.cont_confirm.selectedIndex = 0;

            }
            else
            {
                ui.com_task.cont_process.selectedIndex = 0;
                ui.cont_confirm.selectedIndex = 1;
            }

            if (makeupTaskData.videoCount >= vo.ad_need)
            {
                ui.btn_confirm.state.selectedIndex = 0;
                ui.btn_confirm.visible = true;
                ui.btn_confirm.SetClick(() =>
                 {
                     if (makeupTaskData.videoCount >= vo.ad_need)
                     {
                         GameHelper.ShowLoading(1, 2, () =>
                         {
                             ConsumeSystem.Consume(vo.item, vo.item_need, isSuccess =>
                             {
                                 makeupTaskData.SetStatus(SaveingPotTaskStatus.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();
                                 // DataMgr.MakeupTaskHistory.Save();
                                 //OnInline();
                                 SaveData.GetSaveObject().saveingpot_ch -= vo.item_need;
                                 SaveingPotHelper.CreatSaveingPotItem();
                                 //  Debug.Log(JsonConvert.SerializeObject(vo));
                                 if (vo.id == 1)
                                 {
                                     TrackKit.SendEvent(Property.withdraw_Event,Property.withdraw_cash1);
                                 }
                                 else if (vo.id == 2)
                                 {
                                     TrackKit.SendEvent(Property.withdraw_Event,Property.withdraw_cash2);
                                 }
                                 else if (vo.id == 3)
                                 {
                                     TrackKit.SendEvent(Property.withdraw_Event,Property.withdraw_cash3);
                                 }
                                 if (vo.id != 3)
                                 {
                                     //  ch_index++;
                                 }
                                 InitView();

                                 if (vo.id == 3)
                                 {
                                     // PlayerPrefs.SetInt("ch_lv", 2);
                                     makeupTaskData = SaveData.GetSaveObject().saveingpot_history.Last();
                                 }

                             });
                         });

                     }
                     else
                     {
                         CtrlCloseUI();
                         // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open);
                         //  MainTabUI.getIns().OnGameTab(1);
                     }
                 });
            }
            else
            {
                ui.btn_confirm.state.selectedIndex = 1;
                ui.btn_confirm.visible = false;
            }

        }
        private void OnEnter()
        {
            GTextInput enter_input = null;

            enter_input = ui.com_info.enter_email;


            ui.type.selectedIndex = 1;
            ui.btn_confirm.SetClick(() =>
            {
                var account = enter_input.text.Replace(" ", "");
                if (account == null || account == "")
                {
                    GameHelper.ShowTips("Please enter the correct account information1", true);
                    return;
                }

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

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

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

        }
        void showPaypal()
        {
            ui.type.selectedIndex = 2;

            if (makeupTaskData == null)
            {
                return;
            }


            ui.com_pay.text_name.text = DataMgr.ExchangeName .Value;
            ui.com_pay.text_email.text = DataMgr.ExchangeAccount .Value;

            ui.com_pay.btn_change.SetClick(() =>
            {
                DataMgr.ExchangeName = null;
                DataMgr.ExchangeAccount = null;
                OnEnter();

            });

            var avatarId = DataMgr.PlayerAvatarId .Value;
            TextureHelper.SetAvatarToLoader(avatarId, ui.com_pay.head.GetChild("load_avatar") as GLoader);
            ui.btn_confirm.SetClick(() =>
            {
                NetApi.PayOutUserInfo<OrderState>(DataMgr.ExchangeAccount.Value,
                    DataMgr.short_name, DataMgr.long_name, (isSuccess, obj) =>
                    {
                        if (isSuccess)
                        {
                        }
                    });

                TrackKit.SendEvent(Property.withdraw_Event,Property.WithdrawMessage);

                InitView();
            });
        }
        public int now_selectindex;
        void initTop()
        {
            // Debug.Log(JsonConvert.SerializeObject(DataMgr.MakeupTaskHistory.Value));

            List<btn_top> btn_list = new List<btn_top>() { ui.btn_level0, ui.btn_level1, ui.btn_level2 };

            List<Makeup_2> makeup_list = ConfigSystem.GetConfig<MakeupModel_2>().DataList;
            now_selectindex = makeupTaskData.tableId - 1;
            List<SaveingPotClass> saveingpot_history = SaveData.GetSaveObject().saveingpot_history;

            for (int i = 0; i < btn_list.Count; i++)
            {
                btn_list[i].text_ch.text = "$" + (int)makeup_list[i].item_need;
                Debug.Log(makeup_list[i].item_need);
                btn_list[i].index.selectedIndex = i;
                if (i >= saveingpot_history.Count)
                {
                    btn_list[i].btn_state.selectedIndex = 2;
                    // btn_list[i].text_type.grayed = true;
                    btn_list[i].text_ch.grayed = true;
                }
                else if (saveingpot_history.Count > i + 1 || ((saveingpot_history.Count == 3) && (saveingpot_history[2].status == SaveingPotTaskStatus.Inline)))
                {
                    btn_list[i].btn_state.selectedIndex = 0;
                }
                else
                {
                    btn_list[i].btn_state.selectedIndex = 1;
                }


                if (i == now_selectindex)
                {
                    btn_list[i].img_outline.visible = true;
                }
                else if (i >= saveingpot_history.Count)
                {
                    btn_list[i].img_outline.visible = false;
                    btn_list[i].SetClick(() =>
                    {
                        GameHelper.ShowTips("To be unlocked");
                    });
                }
                else
                {
                    btn_list[i].img_outline.visible = false;
                    int index = i;
                    btn_list[i].SetClick(() =>
                    {

                        for (int j = saveingpot_history.Count - 1; j >= 0; j--)
                        {
                            Debug.Log(saveingpot_history[j].tableId);
                            Debug.Log(index + 1);
                            Debug.Log(saveingpot_history[j].tableId == index + 1);
                            if (saveingpot_history[j].tableId == index + 1)
                            {
                                makeupTaskData = saveingpot_history[j];
                                now_selectindex = index;

                                break;
                            }
                        }

                        InitView();
                    });
                }
            }

        }
        private List<string> config_name_list = ConfigSystem.GetConfig<exBrPoolModel_2>().config_name_list;
        private List<string> config_money_list = ConfigSystem.GetConfig<exBrPoolModel_2>().config_money_list;
        private List<string[]> broad_list = new List<string[]>();
        private void BroadCast()
        {
            if (broadtime % 3 == 0)
            {
                ui.broad.t1.Play(() =>
                {
                    broad_list.RemoveAt(0);
                    int name_index = UnityEngine.Random.Range(0, config_name_list.Count);
                    int money_index = UnityEngine.Random.Range(0, config_money_list.Count);
                    broad_list.Add(new string[2] { config_name_list[name_index], config_money_list[money_index] });
                    for (int i = 0; i < 4; i++)
                    {
                        if (GameHelper.isRDExchangeMode())
                        {
                            text_list[i].text = "congratulations,[color=#ad4800][size=36] " + broad_list[i][0] + " [/size][/color]Successful exchange[color=#ad4800]<img src='ui://o9974uc5t9w7c3'/>" + broad_list[i][1] + "[/color]";
                        }
                        else
                        {
                            text_list[i].text = "congratulations,[color=#ad4800][size=36] " + broad_list[i][0] + " [/size][/color]Successful exchange[color=#ad4800]$" + broad_list[i][1] + "[/color]";
                        }
                    }
                });


            }

        }
        private List<GTextField> text_list = new List<GTextField>();
        private void InitBroadCast()
        {
            text_list.Add(ui.broad.rich_text0);
            text_list.Add(ui.broad.rich_text1);
            text_list.Add(ui.broad.rich_text2);
            text_list.Add(ui.broad.rich_text3);
            for (int i = 0; i < 4; i++)
            {

                int name_index = UnityEngine.Random.Range(0, config_name_list.Count);
                int money_index = UnityEngine.Random.Range(0, config_money_list.Count);
                broad_list.Add(new string[2] { config_name_list[name_index], config_money_list[money_index] });
                if (GameHelper.isRDExchangeMode())
                {
                    text_list[i].text = "congratulations,[color=#ad4800][size=36] " + broad_list[i][0] + " [/size][/color]Successful exchange[color=#ad4800]<img src='ui://o9974uc5t9w7c3'/>" + broad_list[i][1] + "[/color]";
                }
                else
                {
                    text_list[i].text = "congratulations,[color=#ad4800][size=36] " + broad_list[i][0] + " [/size][/color]Successful exchange[color=#ad4800]$" + broad_list[i][1] + "[/color]";
                }
            }
        }
    }
}
