using System;
using System.Collections.Generic;
using FairyGUI;
using FGUI.Common_01;
using FGUI.failpack;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;

namespace ChillConnect
{
    public class ResurgenceUI : BaseUI
    {
        private ResurgenceUICtrl ctrl;
        private ResurgenceModel model;
        private com_resurgence ui;

        public ResurgenceUI(ResurgenceUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.ResurgenceUI;
            this.ctrl = ctrl;
        }
        private float progress_value;

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

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

        }

        protected override void OnClose()
        {
            GameHelper.CallShowTurn();
        }

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

        protected override void OnOpenBefore(object args)
        {

            Debug.Log(args);
            progress_value = (float)args * 100;
            InitView();
            // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_show, 1);
            TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.FailGiftShow);
            InitBroadCast();
            if (GameHelper.IsGiftSwitch())
            {
                ui.broad.visible = true;
            }
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

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

        #region 消息
        protected override void AddListener()
        {
            if (GameHelper.IsAdModelOfPay())
            {
                HallManager.Instance.UpdateSecondEvent += InitView;
            }
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);
            HallManager.Instance.UpdateSecondEvent += updatEevent;
        }
        protected override void RemoveListener()
        {
            if (GameHelper.IsAdModelOfPay())
            {
                HallManager.Instance.UpdateSecondEvent -= InitView;
            }
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            HallManager.Instance.UpdateSecondEvent -= updatEevent;
        }
        #endregion
        private void updatEevent()
        {

            //  ui.text_remain.text=CommonHelper.TimeFormat((int)(SaveData.GetSaveObject().failed_pack_time - Convert.ToInt32(GameHelper.GetNowTime())), CountDownType.Hour);
            broadtime++;
            BroadCast();
        }
        void pay_success(object str)
        {
            string type = (string)str;
            Debug.Log("77777777777777777777777777" + type);
            if (type == PurchasingManager.GetPaySku(PayType.fail_pack))
            {

                var start = GameHelper.GetUICenterPosition(ui.bg);
                //var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("text_gold"));

                // reward_data temp = new reward_data() { start = start, end = end, change = list[1].coins_quantity, type = 101 };
                // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);


                // DOVirtual.DelayedCall(1, () =>
                // {
                //     DOVirtual.Float(0, (float)DataMgr.Coin.Value, 1,
                //         value => { ui.gold.GetChild("text_gold").text = GameHelper.Get101Str((decimal)value); });
                // });

                var rewardData = new RewardData();
                var end = GameHelper.GetUICenterPosition(ui.end_point);

                var rewardSingleData = new RewardSingleData(101, list[2].coins_quantity, RewardOrigin.AdTask)
                {
                    startPosition = start,
                    endPosition = new Vector2(end.x - 110, end.y - 110)
                };

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

                GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                // DataMgr.Coin.Value -= list[1].coins_quantity;
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close);
            }

        }
        private List<Paidgift> list;
        //初始化页面逻辑
        private void InitView()
        {
            if (SaveData.GetSaveObject().failed_pack_time < GameHelper.GetNowTime())
            {
                SaveData.GetSaveObject().failed_pack_time = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().FailedGiftCD;
            }
            ui.btn_back.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close);
                GameDispatcher.Instance.Dispatch(GameMsg.resurgence_close);
            });
            list = ConfigSystem.GetConfig<PaidgiftModel>().DataList;
            int gold_num = list[2].coins_quantity;
            int back_num = list[2].props_quantity[1];
            int out_num = list[2].props_quantity[0];
            int refresh_num = list[2].props_quantity[2];
            ui.text_outnum.text = "x" + out_num;
            ui.text_backnum.text = "x" + back_num;
            ui.text_refreshnum.text = "x" + refresh_num;
            ui.text_goldnum.text = "x" + gold_num;
            ui.text_progress.text = "Completion:" + Math.Round(progress_value) + "%";
            ui.progress_1.value = progress_value;
            if (!GameHelper.IsAdModelOfPay())
            {
                ui.pay_type.selectedIndex = 1;

                decimal price = (decimal)list[2].Paid_price2;
                ui.btn_max_pay.title = GameHelper.getPrice(price);
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = true;
                ui.btn_max_pay.SetClick(() =>
                {
                    ApplePayClass maxPayData = new ApplePayClass
                    {
                        amount = (int)Math.Round(price * 100),
                        sku = PurchasingManager.GetPaySku(PayType.fail_pack),
                        currency = "USD"
                    };
                    MaxPayManager.Instance.Buy(maxPayData);
                });


                return;
            }

            int myAdNum = AdRedeemManager.Instance.GetLookRewardADNum();
            ui.text_have.text = "Owner ADs:" + myAdNum;
            ui.need_text.text = "need " + list[2].Paid_price + " ADs";
            btn_watchAd btn_buy = ui.btn_buy as btn_watchAd;
            btn_buy.img_saveingpot.visible = false;
            // btn_buy.SetClick(() =>
            // {
            //     GameDispatcher.Instance.Dispatch(GameMsg.resurgence);
            //     UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close);
            // });



            if (myAdNum >= list[2].Paid_price)
            {
                btn_buy.buy_state.selectedIndex = 1;
                btn_buy.can_buy.selectedIndex = 0;
                btn_buy.SetClick(() =>
                {
                    ApplePayClass test = new ApplePayClass
                    {
                        sku = PurchasingManager.GetPaySku(PayType.fail_pack),
                    };
                    AdRedeemManager.Instance.SetLookRewardADNum(myAdNum - (int)list[2].Paid_price);
                    // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_buy_success, 1);
                    TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.FailGiftSuccess);
                    GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, PurchasingManager.GetPaySku(PayType.fail_pack));
                });
            }
            else if (SaveData.GetSaveObject()._watch_ad_cd > GameHelper.GetNowTime())
            {
                btn_buy.buy_state.selectedIndex = 0;
                btn_buy.can_buy.selectedIndex = 1;
                btn_buy.btn_text.text = CommonHelper.TimeFormat(SaveData.GetSaveObject()._watch_ad_cd - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
                btn_buy.SetClick(() =>
                {


                });
            }
            else
            {
                btn_buy.buy_state.selectedIndex = 0;
                btn_buy.can_buy.selectedIndex = 0;
                if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) btn_buy.img_saveingpot.visible = true;
                btn_buy.SetClick(() =>
                  {
                      GameHelper.ShowVideoAd("Pass", issuccess =>
                      {
                          if (issuccess)
                          {
                              SaveData.GetSaveObject()._watch_ad_cd = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().exchangeCD;
                              InitView();

                          }
                      });
                      // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_click, 1);    
                      TrackKit.SendEvent(GameHelper.getTrackEvenName(),Property.FailGiftClick);

                  });
            }
        }
        private int broadtime = 1;
        private List<string> config_name_list = ConfigSystem.GetConfig<LevelAttemptsModel>().config_name_list;
        private List<string> config_money_list = ConfigSystem.GetConfig<LevelAttemptsModel>().config_money_list;
        private List<string[]> broad_list = new List<string[]>();
        private void BroadCast()
        {
            if (broadtime % 3 == 0)
            {
                (ui.broad as com_broadcast_new).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++)
                    {
                        text_list[i].text = "Congratulations,User [color=#ad4800][size=36]" + broad_list[i][0] + "[/size][/color] !After purchasing the Failure Gift Package,play [color=#ad4800]" + broad_list[i][1] + "[/color] matcher to clear the level!";
                    }
                });


            }

        }
        private List<GTextField> text_list = new List<GTextField>();
        private void InitBroadCast()
        {
            Debug.Log(text_list);
            Debug.Log(ui.broad);
            Debug.Log((ui.broad as com_broadcast_new));
            text_list.Add((ui.broad as com_broadcast_new).text_0);
            text_list.Add((ui.broad as com_broadcast_new).text_1);
            text_list.Add((ui.broad as com_broadcast_new).text_2);
            text_list.Add((ui.broad as com_broadcast_new).text_3);
            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] });
                text_list[i].text = "Congratulations,User [color=#ad4800][size=36]" + broad_list[i][0] + "[/size][/color] !After purchasing the Failure Gift Package,play [color=#ad4800]" + broad_list[i][1] + "[/color] matcher to clear the level!";

            }
        }
    }
}