using System;
using System.Collections.Generic;
using System.Linq;
using BingoBrain;
using BingoBrain.Core;
using BingoBrain.HotFix;
using FairyGUI;
using FGUI.ACommon;
using FGUI.Common_01;
using FGUI.tixian;
using Newtonsoft.Json;
using UnityEngine;

namespace BingoBrain
{
    public class MakeupConfirmUI : BaseUI
    {
        private MakeupConfirmUICtrl ctrl;
        private MakeupConfirmModel model;
        private FGUI.tixian.com_confirm ui;
        private MakeupTaskData makeupTaskData;
        public int ad_cool_down = 120;
        private long userUid;
        public MakeupConfirmUI(MakeupConfirmUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.MakeupConfirmUI;
            this.ctrl = ctrl;
        }

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


        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.MakeupConfirmModel) as MakeupConfirmModel;
        }

        protected override void OnClose()
        {
            Hall.Instance.UpdateSecondEvent -= updateSpeedCD;
            Hall.Instance.UpdateSecondEvent -= Update;
            Hall.Instance.UpdateSecondEvent -= upTaskWatchAdsBtn;
            Hall.Instance.UpdateSecondEvent -= upLvWatchAdsBtn;

            GameHelper.showGameUI = true;
            // WebviewManager.ShezhiACT(true);



            if (UnityEngine.Random.Range(0, 100) < 50)
            {
                if (UnityEngine.Random.Range(0, 50) < 25)
                {
                    //  UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.FAQUI_Open);
                }
                else
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RecordViewUI_Open);
                }
            }
        }

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

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {//刘海屏
                ui.group_.y += Screen.safeArea.y;
            }
            userUid = GameHelper.GetLoginModel().uid;
            ad_cool_down = ConfigSystem.GetConfig<CommonModel>().WwalaccelerationCD;
            PreferencesMgr.Instance.MakeupTaskH5Time = 999999999;



            //    WebviewManager.ShezhiACT(false);

            makeupTaskData = args as MakeupTaskData;
            ch_index = makeupTaskData.tableId - 1;

            //   PreferencesMgr.Instance.Currency102 = 999999999;  //zhushi
            // makeupTaskData.LvVideoCount = 999;//zhushi
            // makeupTaskData.videoCount = 999;//zhushi

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

            // AdRdManager.Instance.SetWatchAd(AdRdManager.MakeupAd, ui.btn_task_watch as btn_watchAd, () =>{});
            // AdRdManager.Instance.SetWatchAd(AdRdManager.MakeupLVAd, ui.btn_watchad as btn_watchAd, () =>{});
            // AdRdManager.Instance.Start();

            Hall.Instance.UpdateSecondEvent += updateSpeedCD;
            Hall.Instance.UpdateSecondEvent += Update;
            Hall.Instance.UpdateSecondEvent += upTaskWatchAdsBtn;
            ui.text_chdate3.text = GameHelper.getDesByKey("makeup_11");

            InitView();
            initButtom();
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }





        protected override void AddListener()
        {

        }

        protected override void RemoveListener()
        {
        }

        private void Update()
        {
            if (ui.cont_state.selectedIndex == 5)
            {
                Debug.Log("???????kkkkkkkkk");
                ui.text_leveltime.text = GameHelper.TimeFormat((int)makeupTaskData.ch_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                if ((GameHelper.isRDExchangeMode() && SaveData.GetSaveobject().ExchangeProcessMode == 1) || (!GameHelper.isRDExchangeMode() && SaveData.GetSaveobject().CHProcessMode == 1))
                {
                    ui.text_leveltime.visible = ui.text_cashneedlv.visible = false;
                    ui.level_state.selectedIndex = 0;
                }
                else
                {
                    if (makeupTaskData.ch_time > GameHelper.GetNowTime())
                    {
                        ui.level_state.selectedIndex = 0;
                    }
                    else
                    {
                        if (ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock == 0)
                        {
                            makeupTaskData.ch_time = GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().BalanceExpired * 3600;
                            PreferencesMgr.Instance.SaveMakeupTaskHistory();
                        }
                        else ui.level_state.selectedIndex = 1;
                    }
                }

            }
        }

        private void InitView(object a = null)
        {
            if (makeupTaskData == null)
            {
                return;
            }
            if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 1)
            {
                //   ui.group_.visible = true;
            }
            else
            {
                if (PreferencesMgr.Instance.MakeupTaskHistory[0].status >= MakeupTaskStatus.Level) ui.group_.visible = true;
            }

            initTop();
            ui.btn_close.SetClick(CtrlCloseUI);

            if ((GameHelper.isRDExchangeMode() && SaveData.GetSaveobject().ExchangeProcessMode == 1) || (!GameHelper.isRDExchangeMode() && SaveData.GetSaveobject().CHProcessMode == 1))
            {
                if (makeupTaskData.status == MakeupTaskStatus.Level)
                {
                    Debug.Log("00000000000000000003");
                    ui.cont_state.selectedIndex = 5;
                    Update();
                    var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);

                    string str = string.Format(GameHelper.getDesByKey("makeup_6"), vo.levels_need);
                    ui.text_chneedlv.text = str;
                    ui.lab_lv_need_des.SetVar("num", ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock.ToString()).FlushVars();
                    Debug.Log(ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock);
                    str = string.Format("Owner ADs: {0}/{1}", makeupTaskData.LvVideoCount, ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock);
                    ui.lab_ads.text = str;
                    ui.text_nowch.text = GameHelper.Get102Str(PreferencesMgr.Instance.Currency102);
                    ui.text_ch_title.text = "Level " + vo.levels_need;
                    if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                    {
                        (ui.btn_watchad.GetChild("img_saveingpot") as GImage).visible = true;
                    }
                    if (GameHelper.GetLevel() <= vo.levels_need)
                    {
                        ui.btn_check_level.title = "Go";
                        // if (UIManager.Instance.IsExistUI(UIConst.RainPlayUI))
                        // {
                        //     ui.btn_check_level.SetClick(() =>
                        //     {
                        //         CtrlCloseUI();
                        //     });
                        // }
                        // else
                        // {
                        //     ui.btn_check_level.SetClick(() =>
                        //     {
                        //         GameDispatcher.Instance.Dispatch(BingoInfo.OpenGame);
                        //         CtrlCloseUI();
                        //     });
                        // }

                    }
                    else
                    {
                        ui.btn_check_level.title = GameHelper.getDesByKey("ch_out_2");
                        ui.btn_check_level.SetClick(() =>
                        {
                            // PlayerPrefs.SetInt("ch_lv", vo.id);
                            makeupTaskData.SetStatus(MakeupTaskStatus.None);
                            PreferencesMgr.Instance.SaveMakeupTaskHistory();
                            InitView();
                        });
                    }
                }
                else if (makeupTaskData.status == MakeupTaskStatus.None)
                {
                    Debug.Log("0000000000000000000");
                    OnConfirm();
                }
                else if (string.IsNullOrEmpty(makeupTaskData.ExchangeAccount) && !GameHelper.isRDExchangeMode())
                {
                    Debug.Log("00000000000000000001");
                    OnEnter();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.Task)
                {
                    Debug.Log("00000000000000000002");
                    OnTask();
                }

                else if (makeupTaskData.status == MakeupTaskStatus.Inline)
                {
                    OnInline();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.editAccount)
                {
                    Debug.Log("00000000000000000004");
                    OnEnter();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.ticket)
                {
                    onTicket();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.code)
                {
                    onCode();
                }

            }
            else
            {
                if (makeupTaskData.status == MakeupTaskStatus.None)
                {
                    Debug.Log("0000000000000000000");
                    OnConfirm();
                }
                else if (string.IsNullOrEmpty(makeupTaskData.ExchangeAccount) && !GameHelper.isRDExchangeMode())
                {
                    Debug.Log("00000000000000000001");
                    OnEnter();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.Task)
                {
                    Debug.Log("00000000000000000002");
                    OnTask();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.Level)
                {
                    Debug.Log("00000000000000000003");
                    ui.cont_state.selectedIndex = 5;
                    Update();
                    var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(makeupTaskData.tableId);

                    string str = string.Format(GameHelper.getDesByKey("makeup_6"), vo.levels_need);
                    ui.text_chneedlv.text = str;
                    ui.lab_lv_need_des.SetVar("num", ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock.ToString()).FlushVars();
                    Debug.Log(ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock);
                    str = string.Format("Owner ADs: {0}/{1}", makeupTaskData.LvVideoCount, ConfigSystem.GetConfig<CommonModel>().ExpiryUnlock);
                    ui.lab_ads.text = str;
                    ui.text_nowch.text = GameHelper.Get102Str(PreferencesMgr.Instance.Currency102);
                    ui.text_ch_title.text = "Level " + vo.levels_need;
                    if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                    {
                        (ui.btn_watchad.GetChild("img_saveingpot") as GImage).visible = true;
                    }

                    if (GameHelper.GetLevel() <= vo.levels_need)
                    {
                        ui.btn_check_level.title = "Go";
                        // if (UIManager.Instance.IsExistUI(UIConst.RainPlayUI))
                        // {
                        //     ui.btn_check_level.SetClick(() =>
                        //     {
                        //         CtrlCloseUI();
                        //     });
                        // }
                        // else
                        // {
                        //     ui.btn_check_level.SetClick(() =>
                        //     {
                        //         GameDispatcher.Instance.Dispatch(BingoInfo.OpenGame);
                        //         CtrlCloseUI();
                        //     });
                        // }

                    }
                    else
                    {
                        ui.btn_check_level.title = GameHelper.getDesByKey("ch_out_2");
                        ui.btn_check_level.SetClick(() =>
                        {
                            // PlayerPrefs.SetInt("ch_lv", vo.id);
                            SaveData.GetSaveobject().chout_lv = vo.id;
                            SaveData.saveDataFunc();
                            GameHelper.ShowLoading(1, 2, () =>
                            {
                                TuSystem.Consume(vo.item, vo.item_need, isSuccess =>
                                {
                                    makeupTaskData.SetStatus(MakeupTaskStatus.Inline);
                                    makeupTaskData.inlineInitNum =
                                        UnityEngine.Random.Range(ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                            ConfigSystem.GetConfig<CommonModel>().inlineInitNum[1]);
                                    makeupTaskData.inlineNum = UnityEngine.Random.Range(
                                        ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                        makeupTaskData.inlineInitNum);
                                    makeupTaskData.order_time = GameHelper.GetNowTime();
                                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                                    GameDispatcher.Instance.Dispatch(BingoInfo.Update102);
                                    //OnInline();
                                    // Debug.Log(JsonConvert.SerializeObject(vo));
                                    // if (vo.id == 1)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 1);

                                    // }
                                    // else if (vo.id == 2)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 2);
                                    // }
                                    // else if (vo.id == 3)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 3);
                                    // }
                                    if (vo.id != 3)
                                    {
                                        ch_index++;
                                    }
                                    InitView();
                                    if (vo.id == 3)
                                    {
                                        // PlayerPrefs.SetInt("ch_lv", 2);
                                        SaveData.GetSaveobject().chout_lv = 2;
                                        SaveData.saveDataFunc();
                                        makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                                    }

                                });
                            });
                            InitView();
                        });
                    }
                }
                else if (makeupTaskData.status == MakeupTaskStatus.Inline)
                {
                    OnInline();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.editAccount)
                {
                    Debug.Log("00000000000000000004");
                    OnEnter();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.ticket)
                {
                    onTicket();
                }
                else if (makeupTaskData.status == MakeupTaskStatus.code)
                {
                    onCode();
                }

            }
            upTaskWatchAdsBtn();
            updateSpeedCD();
            Update();

        }
        private int now_selectindex = 0;
        private int ch_index = 0;
        void initTop()
        {
            //   Debug.Log(JsonConvert.SerializeObject(DataMgr.MakeupTaskHistory.Value));
            List<level_btn> btn_list = new List<level_btn>() { ui.com_chlevel.btn_0, ui.com_chlevel.btn_1, ui.com_chlevel.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;
                if (i < ch_index)
                {
                    btn_list[i].img_check.visible = true;
                    // btn_list[i].text_level0.y = 4;
                    //  btn_list[i].text_level1.y = 4;

                }
                else
                {
                    btn_list[i].img_check.visible = false;
                    //  btn_list[i].text_level0.y = 38;
                    //  btn_list[i].text_level1.y = 38;
                }

                if (i == now_selectindex)
                {
                    btn_list[i].btn_state.selectedIndex = 1;
                }
                else if (i > ch_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 ch_people;
                // public float ch_people_1;
                // public float ch_people_2;
                SaveData.GetSaveobject().ch_people = UnityEngine.Random.Range(500, 800);
                SaveData.GetSaveobject().ch_people_1 = UnityEngine.Random.Range(20, 30);
                SaveData.GetSaveobject().ch_people_2 = UnityEngine.Random.Range(3, 6) * 100;
                SaveData.saveDataFunc();
            }
            if (hour != SaveData.GetSaveobject().login_hour)
            {

                SaveData.GetSaveobject().ch_people += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(8, 10);
                SaveData.GetSaveobject().ch_people_1 += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(10, 15);
                SaveData.GetSaveobject().ch_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().ch_people.ToString();
            ui.text_number1.text = SaveData.GetSaveobject().ch_people_1.ToString();
            ui.text_number2.text = (GameHelper.isRDExchangeMode() ? "<img src='ui://pmf3wbji112epi7'/>" : "") + GameHelper.Get102Str_new((decimal)SaveData.GetSaveobject().ch_people_2);
            ui.text_chdate.text = string.Format(ui.text_chdate.text, DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day);

        }

        private void OnEnter()
        {
            GTextInput enter_input = null;
            enter_input = ui.com_info.enter_email;

            ui.cont_state.selectedIndex = 0;
            ui.text_title.text = GameHelper.getDesByKey("makeup_9");
            ui.text_smaill_title.text = GameHelper.getDesByKey("makeup_10");
            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))
                {
                    GameHelper.ShowTips("Please enter the correct account information", true);
                    return;
                }

                makeupTaskData.ExchangeAccount = account;
                makeupTaskData.ExchangeName = $"{fname} {lname}";
                makeupTaskData.short_name = fname;
                makeupTaskData.long_name = lname;
                if (GameHelper.isRDExchangeMode())
                {
                    makeupTaskData.SetStatus(MakeupTaskStatus.ticket);
                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                    InitView();
                }
                else
                {
                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                    showPaypal();
                }
            });

        }

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

            if (makeupTaskData == null)
            {
                return;
            }


            ui.com_pay.text_name.text = makeupTaskData.ExchangeName;
            ui.com_pay.text_email.text = makeupTaskData.ExchangeAccount;
            // var avatarId = DataMgr.PlayerAvatarId.Value;
            // TextureHelper.SetAvatarToLoader(avatarId, ui.com_pay.head.GetChild("load_avatar") as GLoader);

            ui.com_pay.btn_change.SetClick(() =>
            {
                makeupTaskData.ExchangeName = null;
                makeupTaskData.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(() =>
            {
                // NetApi.PayOutUserInfo<OrderState>(makeupTaskData.ExchangeAccount,
                //   makeupTaskData.short_name, makeupTaskData.long_name, (isSuccess, obj) =>
                //    {
                //        if (isSuccess)
                //        {
                //        }
                //    });

                // TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawMessage);
                makeupTaskData.SetStatus(MakeupTaskStatus.Task);
                InitView();
                // uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData);
                //CtrlCloseUI();
            });
        }

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

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

            ui.text_condi1.text = GameHelper.getChString(vo.item_need);
            ui.pb_condi1.max = vo.item_need;
            ui.text_ch_number.text = GameHelper.getChString(PreferencesMgr.Instance.Currency102);
            var curValue = Math.Min(PreferencesMgr.Instance.Currency102, vo.item_need);
            ui.pb_condi1.value = (double)curValue;
            var textTitle = ui.pb_condi1.GetChild("title");
            if (textTitle != null)
            {
                textTitle.text = GameHelper.getChString(curValue) + "/" + GameHelper.getChString(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);

            if (PreferencesMgr.Instance.Currency102 >= vo.item_need &&
                completeTaskTime >= taskTime)
            {
                ui.cont_confirm.selectedIndex = 0;

                ui.btn_earn.SetClick(() =>
                {
                    Audio.Instance.PlayDynamicEffect("makupdone");
                    makeupTaskData.SetStatus(MakeupTaskStatus.Task);
                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                    // OnTask();
                    InitView();
                });
            }
            else
            {
                ui.cont_confirm.selectedIndex = 1;
                (ui.btn_earn as FGUI.tixian.btn_get).state.selectedIndex = 1;
                ui.btn_earn.SetClick(() =>
                {
                    // AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone);
                    // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open);
                    // //GameDispatcher.Instance.Dispatch(BingoInfo.MainTab, 1);

                    CtrlCloseUI();
                    // 
                });
            }
        }

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

            ui.cont_state.selectedIndex = 2;
            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 (GameHelper.isRDExchangeMode())
            {
                ui.com_task.text_task.text = GameHelper.getDesByKey("makeup_12");
            }
            else
            {
                string str = string.Format(GameHelper.getDesByKey("makeup_12"), $"${makeupTaskData.amount:N}");
                ui.com_task.text_task.text = str;
            }
            Debug.Log(GameHelper.getDesByKey("makeup_12"));
            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_chout as FGUI.tixian.btn_get).state.selectedIndex = 0;
                ui.btn_chout.title = GameHelper.getDesByKey("ch_out_2");
                ui.btn_chout.SetClick(() =>
                {
                    if (makeupTaskData.videoCount >= vo.ad_need)
                    {
                        if ((GameHelper.isRDExchangeMode() && SaveData.GetSaveobject().ExchangeProcessMode == 1) || (!GameHelper.isRDExchangeMode() && SaveData.GetSaveobject().CHProcessMode == 1))
                        {
                            // makeupTaskData.SetStatus(MakeupTaskStatus.Inline);
                            // makeupTaskData.ch_time = GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().BalanceExpired * 3600;
                            // PreferencesMgr.Instance.SaveMakeupTaskHistory();
                            // InitView();
                            GameHelper.ShowLoading(1, 2, () =>
                            {
                                TuSystem.Consume(vo.item, vo.item_need, isSuccess =>
                                {
                                    makeupTaskData.SetStatus(MakeupTaskStatus.Inline);
                                    makeupTaskData.inlineInitNum =
                                        UnityEngine.Random.Range(ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                            ConfigSystem.GetConfig<CommonModel>().inlineInitNum[1]);
                                    makeupTaskData.inlineNum = UnityEngine.Random.Range(
                                        ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                        makeupTaskData.inlineInitNum);
                                    makeupTaskData.order_time = GameHelper.GetNowTime();
                                    PreferencesMgr.Instance.Currency102 = PreferencesMgr.Instance.Currency102 - vo.item_need;
                                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                                    GameDispatcher.Instance.Dispatch(BingoInfo.Update102);
                                    //OnInline();
                                    // Debug.Log(JsonConvert.SerializeObject(vo));
                                    // if (vo.id == 1)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 1);

                                    // }
                                    // else if (vo.id == 2)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 2);
                                    // }
                                    // else if (vo.id == 3)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 3);
                                    // }
                                    if (vo.id != 3)
                                    {
                                        ch_index++;
                                    }
                                    InitView();
                                    if (vo.id == 3)
                                    {
                                        // PlayerPrefs.SetInt("ch_lv", 2);
                                        SaveData.GetSaveobject().chout_lv = 2;
                                        SaveData.saveDataFunc();
                                        makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                                    }

                                });
                            });
                        }
                        else
                        {
                            //  makeupTaskData.SetStatus(MakeupTaskStatus.Level);//不要关卡条件了
                            // makeupTaskData.ch_time = GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().BalanceExpired * 3600;
                            // PreferencesMgr.Instance.SaveMakeupTaskHistory();
                            // InitView();
                            SaveData.GetSaveobject().chout_lv = vo.id;
                            SaveData.saveDataFunc();
                            GameHelper.ShowLoading(1, 2, () =>
                            {
                                TuSystem.Consume(vo.item, vo.item_need, isSuccess =>
                                {
                                    makeupTaskData.SetStatus(MakeupTaskStatus.Inline);
                                    makeupTaskData.inlineInitNum =
                                        UnityEngine.Random.Range(ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                            ConfigSystem.GetConfig<CommonModel>().inlineInitNum[1]);
                                    makeupTaskData.inlineNum = UnityEngine.Random.Range(
                                        ConfigSystem.GetConfig<CommonModel>().inlineInitNum[0],
                                        makeupTaskData.inlineInitNum);
                                    makeupTaskData.order_time = GameHelper.GetNowTime();
                                    PreferencesMgr.Instance.Currency102 = PreferencesMgr.Instance.Currency102 - vo.item_need;
                                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                                    GameDispatcher.Instance.Dispatch(BingoInfo.Update102);
                                    //OnInline();
                                    // Debug.Log(JsonConvert.SerializeObject(vo));
                                    // if (vo.id == 1)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 1);

                                    // }
                                    // else if (vo.id == 2)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 2);
                                    // }
                                    // else if (vo.id == 3)
                                    // {
                                    //     TrackKit.SendEvent(Property.withdraw_Event, Property.WithdrawCash, 3);
                                    // }
                                    if (vo.id != 3)
                                    {
                                        ch_index++;
                                    }
                                    InitView();
                                    if (vo.id == 3)
                                    {
                                        // PlayerPrefs.SetInt("ch_lv", 2);
                                        SaveData.GetSaveobject().chout_lv = 2;
                                        SaveData.saveDataFunc();
                                        makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                                    }

                                });
                            });
                            InitView();
                        }
                    }
                    else
                    {
                        CtrlCloseUI();
                        //  UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open);
                        //  MainTabUI.getIns().OnGameTab(1);
                    }
                });
            }
            else
            {
                (ui.btn_chout as FGUI.tixian.btn_get).state.selectedIndex = 1;
                ui.btn_chout.SetClick(() =>
                {
                    GameHelper.ShowTips("The AD viewing task has not been completed.");
                });
            }
        }

        private void OnInline()
        {
            CheckBtnWatchStatus();

            ui.cont_state.selectedIndex = 3;

            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(BingoInfo.RefreshMakeupData);
            ui.btn_tab.SetClick(CtrlCloseUI);



            RefreshRecordData();
        }


        private void RefreshRecordData()
        {
            var data = makeupTaskData;
            if (data.inlineNum <= 1 && GameHelper.isRDExchangeMode())
            {
                ui.cont_confirm.selectedIndex = 0;
                ui.btn_inline_ok.SetClick(() =>
                {
                    makeupTaskData.SetStatus(MakeupTaskStatus.editAccount);
                    PreferencesMgr.Instance.SaveMakeupTaskHistory();
                    InitView();
                });

                // return;
            }
            else
            {
                ui.cont_confirm.selectedIndex = 1;
            }


            var com_rank = ui.com_newRecord.com_rank;
            com_rank.lab_title_des.text = GameHelper.getDesByKey("makeup_7");
            com_rank.lab_rank_tips.text = GameHelper.getDesByKey("makeup_8");

            var rdVOModel = ConfigSystem.GetConfig<MakeupModel>().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 (GameHelper.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 / 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;

                            Debug.Log($"rank_num=== {rank_num} {last} {data.activeSpeedNum} {rdVOModel.Active_Limit_times}");

                            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>().GetData(makeupTaskData.tableId);
            ui.cont_state.selectedIndex = 6;
            ui.lab_mn.text = ui.lab_mn.text;

            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<makeupRdData>();
                int[] arr = ConfigSystem.GetConfig<CommonModel>().BalanceExchange;
                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++)
                    {
                        makeupRdData data = new makeupRdData();
                        data.code = GameHelper.GenerateUniqueKey();
                        data.coupon_mount = arr[i];
                        data.isClaimed = false;
                        makeupTaskData.rdData.Add(data);
                    }
                }
                if (remainValue > 0)
                {
                    makeupRdData data = new makeupRdData();
                    data.code = GameHelper.GenerateUniqueKey();
                    data.coupon_mount = remainValue; // 面额就是剩余值
                    data.isClaimed = false;
                    makeupTaskData.rdData.Add(data);
                }
                PreferencesMgr.Instance.SaveMakeupTaskHistory();
            }

            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(MakeupTaskStatus.code);
                makeupTaskData.rdData[index].isClaimed = true;
                makeupTaskData.lastRdData = makeupTaskData.rdData[index];
                PreferencesMgr.Instance.SaveMakeupTaskHistory();

                onCode();
            });
        }

        void onCode()
        {
            if (makeupTaskData.lastRdData == null)
            {
                ui.cont_state.selectedIndex = 6;
                makeupTaskData.SetStatus(MakeupTaskStatus.ticket);
                return;
            }
            ui.cont_state.selectedIndex = 7;

            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>().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.cont_state.selectedIndex = 6;
                makeupTaskData.SetStatus(MakeupTaskStatus.ticket);
                InitView();
            });

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

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

        }

        void CheckBtnWatchStatus()
        {
            var data = makeupTaskData;

            if (data == null)
            {
                return;
            }
            var CardRdVOModel = ConfigSystem.GetConfig<MakeupModel>().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;

        }

        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;
                ui.btn_watch.text_cd.text = GameHelper.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 CheckActive(int index)
        {
            if (GameHelper.activeTimes.TryGetValue(index, out int value))
            {
                value++;
                // Debug.Log($"CheckActive2: {index} {value}");
                GameHelper.activeTimes[index] = value;

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

        }

        void WatchBtnClick()
        {

            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);
                        InitView();
                        //                    });

                    }
                });

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

        void taskWatchBtnClick()
        {
            GameHelper.ShowVideoAd("taskWatchAd", (issuccess) =>
            {
                if (issuccess)
                {
                    var ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                    SaveData.GetSaveobject()._watch_ad_cd = ad_times + GameHelper.GetCommonModel().exchangeCD;

                    btn_watchAd btn_task_watch = ui.btn_task_watch as btn_watchAd;
                    btn_task_watch.enabled = false;
                    btn_task_watch.can_buy.selectedIndex = 1;
                    btn_task_watch.btn_text.text = GameHelper.TimeFormat(SaveData.GetSaveobject()._watch_ad_cd - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                    Hall.Instance.UpdateSecondEvent += upTaskWatchAdsBtn;

                    OnTask();
                }
            });
        }

        public void upTaskWatchAdsBtn()
        {
            var lastTimes = SaveData.GetSaveobject()._watch_ad_cd;
            btn_watchAd btn_task_watch = ui.btn_task_watch as btn_watchAd;
            btn_task_watch.img_saveingpot.visible = false;
            if (GameHelper.GetNowTime() < lastTimes)
            {
                btn_task_watch.enabled = false;
                btn_task_watch.can_buy.selectedIndex = 1;
                btn_task_watch.btn_text.text = GameHelper.TimeFormat(lastTimes - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
            }
            else
            {
                Hall.Instance.UpdateSecondEvent -= upTaskWatchAdsBtn;
                btn_task_watch.enabled = true;
                btn_task_watch.can_buy.selectedIndex = 0;
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) btn_task_watch.img_saveingpot.visible = true;
            }
        }

        void LvWatchBtnClick()
        {
            GameHelper.ShowVideoAd("LevelWatchAd", (issuccess) =>
            {
                if (issuccess)
                {
                    var ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                    SaveData.GetSaveobject()._watch_ad_cd = ad_times + GameHelper.GetCommonModel().exchangeCD;

                    btn_watchAd btn_watchad = ui.btn_watchad as btn_watchAd;
                    btn_watchad.enabled = false;
                    btn_watchad.can_buy.selectedIndex = 1;
                    btn_watchad.btn_text.text = GameHelper.TimeFormat(SaveData.GetSaveobject()._watch_ad_cd - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                    Hall.Instance.UpdateSecondEvent += upLvWatchAdsBtn;
                    //  makeupTaskData.cash_time = GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().BalanceExpired * 3600;
                    InitView();
                }
            });
        }

        public void upLvWatchAdsBtn()
        {
            var lastTimes = SaveData.GetSaveobject()._watch_ad_cd;
            btn_watchAd btn_watchad = ui.btn_watchad as btn_watchAd;
            btn_watchad.img_saveingpot.visible = false;

            if (GameHelper.GetNowTime() < lastTimes)
            {
                btn_watchad.enabled = false;
                btn_watchad.can_buy.selectedIndex = 1;
                btn_watchad.btn_text.text = GameHelper.TimeFormat(lastTimes - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
            }
            else
            {
                Hall.Instance.UpdateSecondEvent -= upLvWatchAdsBtn;
                btn_watchad.enabled = true;
                btn_watchad.can_buy.selectedIndex = 0;
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) btn_watchad.img_saveingpot.visible = true;
            }
        }
    }
}
public class MakeupTaskData
{
    public int tableId;


    public int id;


    public string amountStr;


    public decimal amount;


    public long makeupTime;


    public int videoCount;


    public int inlineInitNum;


    public int inlineNum;


    public string orderID;


    public MakeupTaskStatus status;

    public long order_time = 0;
    public int WatchVideoSpeedNum = 0;
    public int loginSpeedNum = 0;
    public int activeMinute = 0;
    public int activeSpeedNum = 0;

    public long ch_time;
    public string ExchangeAccount;
    public string ExchangeName;
    public string short_name;
    public string long_name;
    public List<makeupRdData> rdData;
    public makeupRdData lastRdData;
    public int LvVideoCount;
    public void SetStatus(MakeupTaskStatus _status)
    {
        status = _status;
    }

    public string GetAmountStr()
    {
        if (amount <= 0)
        {
            return amountStr;
        }
        else
        {
            return GameHelper.Get101Str(amount);
        }
    }
}

public enum MakeupTaskStatus
{
    None,
    Task,
    Level,
    Inline,
    editAccount,
    ticket,
    code,
}

public class makeupRdData
{
    public int coupon_mount;
    public string code;
    public bool isClaimed;
}