using System;
using System.Linq;
using UnityEngine;
using FairyGUI;
using DG.Tweening;
using FGUI.A000_common;
using FGUI.G018_GameHome;
using Newtonsoft.Json;
using Roy.Datas;
using Spine.Unity;
using SGame;
using Random = UnityEngine.Random;

namespace ScrewsMaster
{
    public class LevelSuccessUI : BaseUI
    {
        private LevelSuccessUICtrl ctrl;
        private LevelSuccessModel model;
        private FGUI.G008_reward.com_lvsuccess ui;
        private bool is_success;
        private bool is_level_success;
        private bool is_h5_reward;

        private SettlementData _data;
        private string _broadTextTemplate;

        public LevelSuccessUI(LevelSuccessUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.LevelSuccessUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期
        protected override void OnInit()
        {
            model = ModuleManager.Instance.GetModel(ModelConst.LevelSuccessModel) as LevelSuccessModel;
        }

        protected override void OnClose()
        {
            closeCallback?.Invoke();
            if (is_level_success && !GameHelper.is_first_login)
            {
                // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, is_success);
            }
            GameHelper.SetCloseResult(false);
            if (is_h5_reward)
            {
                // WebviewManager.Instance.ShowH5View(true);
                GameDispatcher.Instance.Dispatch(GameMsg.resetH5progress);
            }


        }
        private Action closeCallback;
        protected override void OnBind()
        {
            ui = baseUI as FGUI.G008_reward.com_lvsuccess;
        }

        protected override void OnOpenBefore(object args)
        {
            if (args is SettlementData settlementData)
            {
                is_success = settlementData.is_success;
                _cashNumber = settlementData.cash_number;
                is_level_success = settlementData.is_level_success;
                is_h5_reward = settlementData.is_h5_reward;
                _rate = is_success ? (int)settlementData.rate : 1;
            }
            if (Screen.safeArea.y != 0)
            {//刘海屏
                ui.gold.y += Screen.safeArea.y;
                ui.top_money.y += Screen.safeArea.y;
                ui.tips_bg.y += Screen.safeArea.y;
                ui.tips_text.y += Screen.safeArea.y;
            }
            _isGiftSwitch = GameHelper.IsGiftSwitch();

            ui.switchgift.selectedIndex = _isGiftSwitch ? ui._Switchgift_b : ui._Switchgift_a;
            ui.state.selectedIndex = is_success ? ui._State_win : ui._State_lose;
            if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.btn_adclaim.GetChild("img_saveingpot") as GImage).visible = true;
            PlayDynamicEffect();

            // (ui.btn_adclaim as btn_tabad).color.selectedIndex = 1;

            ui.top_money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102());

            if (is_success)
            {
                ui.btn_adclaim.GetChild("title").text = "Claim X" + _rate;
                var sk = FXManager.Instance.SetFx<SkeletonAnimation>(ui.bg_parent, Fx_Type.fx_win, ref closeCallback);
                sk.state.SetAnimation(0, "out", false);

                sk = FXManager.Instance.SetFx<SkeletonAnimation>(ui.bg_parent, Fx_Type.fx_win_light, ref closeCallback);
                sk.state.SetAnimation(0, "animation", true);

            }
            else
            {
                ui.bg_parent.y += 200;
                var sk = FXManager.Instance.SetFx<SkeletonAnimation>(ui.bg_parent, Fx_Type.fx_lose, ref closeCallback);
                sk.state.SetAnimation(0, "animation", false);
                GameHelper.SetCloseResult(true);
            }
            GameHelper.PlayGameTimeEvent(3, () =>
            {
                GameHelper.RequestGameConfig();
            });
            InitView();
            ShowScrews.Instance.TrackGameCompletion(is_success);
        }

        #region 新版代码（测试）

        private float _cashNumber;
        private int _rate;
        private bool _isGiftSwitch;
        private MakeupTaskData _makeupTaskData;

        private const int RewardNum = 40;

        private com_success_cash _com_cash;
        private float _progressBarWidth = -1;

        //初始化页面逻辑
        private void InitView()
        {

            _com_cash = ui.com_cash as com_success_cash;
            SetButtonsTouchable(true);
            InitButtons();

            if (_isGiftSwitch)
            {
                InitCashView();
            }
            else
            {
                ui.money_text.text = RewardNum.ToString();
                ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString();
            }
        }


        private void InitCashView()
        {
            ui.money_text.text = is_success
                ? GameHelper.GetPaymentTypeVO().payicon + _cashNumber
                : GameHelper.Get102Str(GameHelper.Get102());

            var exBrPoolModel = ConfigSystem.GetConfig<exBrPoolModel>();
            var configNameList = exBrPoolModel.config_name_list;
            var configMoneyList = exBrPoolModel.config_money_list;
            var nameIndex =
                Random.Range(0, configNameList.Count);
            var moneyIndex =
                Random.Range(0, configMoneyList.Count);


            if (_com_cash == null) return;

            if (string.IsNullOrEmpty(_broadTextTemplate))
            {
                _broadTextTemplate = _com_cash.broad.cast_text.text;
            }

            if (_progressBarWidth < 0)
            {
                _progressBarWidth = _com_cash.progress.width;
            }

            _com_cash.broad.cast_text.text = string.Format(
                _broadTextTemplate,
                configNameList[nameIndex],
                configMoneyList[moneyIndex]);


            _makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
            var vo = ConfigSystem.GetConfig<MakeupModel>().GetData(_makeupTaskData.tableId);
            Debug.Log(JsonConvert.SerializeObject(vo));

            string cashTextStr;
            var progressWidth = 676f;
            string progressTextStr;

            if (GameHelper.GetLevel() <= vo.levels_need)
            {
                cashTextStr = "Withdrawals can be made through level " + vo.levels_need;
                progressWidth = _progressBarWidth * (GameHelper.GetLevel() - 1) / vo.levels_need;
                progressTextStr = (GameHelper.GetLevel() - 1) + "/" + vo.levels_need;
            }
            else if ((float)GameHelper.Get102() < vo.item_need)
            {
                cashTextStr = "Collect " + GameHelper.Get102Str(vo.item_need) + " to cash out";
                progressWidth = _progressBarWidth * ((float)GameHelper.Get102() / vo.item_need);
                progressTextStr = GameHelper.Get102Str(GameHelper.Get102()) + "/" +
                                  GameHelper.Get102Str(vo.item_need);
            }
            else if ((float)PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need)
            {
                cashTextStr = "Cumulataive " + (vo.task_need / 60) + @" minutes in ""Game"" to cash out";
                progressWidth = _progressBarWidth * ((float)PreferencesMgr.Instance.MakeupTaskH5Time / vo.task_need);
                progressTextStr = Math.Round(((float)(PreferencesMgr.Instance.MakeupTaskH5Time / 60)), 2) + "/" +
                                  (vo.task_need / 60);
            }
            else if (_makeupTaskData.videoCount < vo.ad_need)
            {
                cashTextStr = "Watch " + vo.ad_need + " Reward Ads  to cash out";
                progressWidth = _progressBarWidth * ((float)_makeupTaskData.videoCount / vo.ad_need);
                progressTextStr = _makeupTaskData.videoCount + "/" + vo.ad_need;
            }
            else
            {
                cashTextStr = "Watch " + vo.ad_need + " Reward Ads  to cash out";
                progressWidth = _makeupTaskData.videoCount > vo.ad_need
                    ? _progressBarWidth
                    : _progressBarWidth * ((float)_makeupTaskData.videoCount / vo.ad_need);
                progressTextStr = _makeupTaskData.videoCount > vo.ad_need
                    ? vo.ad_need + "/" + vo.ad_need
                    : _makeupTaskData.videoCount + "/" + vo.ad_need;
            }

            _com_cash.cash_text.text = cashTextStr;
            _com_cash.progress.width = progressWidth;
            _com_cash.progress_text.text = progressTextStr;

            HallManager.Instance.UpdateSecondEvent += TimeEvent;
        }


        /// <summary>
        /// 初始化按钮点击事件
        /// </summary>
        private void InitButtons()
        {
            ui.btn_restart.SetClick(OnClickRestart);
            ui.btn_adclaim.SetClick(OnClickAdClaim);
            ui.btn_claim.SetClick(OnClickClaim);
            ui.top_money.GetChild("btn_cashout").SetClick(OnClickCashout);

            if (_com_cash == null) return;
            _com_cash.btn_cash.SetClick(OnClickCash);
        }

        /// <summary>
        /// 禁用界面上所有按钮点击
        /// </summary>
        /// <param name="enable"></param>
        private void SetButtonsTouchable(bool enable)
        {
            ui.btn_restart.touchable = enable;
            ui.btn_adclaim.touchable = enable;
            ui.btn_claim.touchable = enable;
            ui.com_cash.touchable = enable;
            ui.top_money.GetChild("btn_cashout").touchable = enable;
        }

        /// <summary>
        /// 点击重新开始
        /// </summary>
        private void OnClickRestart()
        {
            if (!GameHelper.GetCloseResult()) return;
            SetButtonsTouchable(false);
            GameHelper.AddInterAdNumber();
            // if (!is_success) ShowScrews.instance.OnRestartBtnClick(); //GameHelper.setLevelstate(3);

            ClosePanelLogic(0);
        }

        private void OnClickCashout()
        {
            if (!GameHelper.GetCloseResult()) return;
            SetButtonsTouchable(false);
            _com_cash.btn_cash.FireClick(false, true);
        }

        /// <summary>
        /// 点击广告Claim
        /// </summary>
        private void OnClickAdClaim()
        {
            if (!GameHelper.GetCloseResult()) return;
            SetButtonsTouchable(false);
            GameHelper.ShowVideoAd("reward_lobby", isSuccess =>
            {
                if (!isSuccess)
                {
                    SetButtonsTouchable(true);
                    return;
                }

                var start = GameHelper.GetUICenterPosition(ui.btn_adclaim);
                var end = GameHelper.GetUICenterPosition(_isGiftSwitch
                    ? ui.top_money.GetChild("number_text")
                    : ui.gold.GetChild("number_text"));

                var startNum = 0f;
                var endNum = 0f;
                GObject numText;

                reward_data temp = new reward_data() { start = start, end = end };
                if (_isGiftSwitch)
                {
                    var changeNum = _cashNumber * _rate;
                    temp.change = changeNum;
                    temp.type = 111;
                    GameHelper.AddMoney(temp.change);

                    startNum = (float)GameHelper.Get102() - changeNum;
                    endNum = (float)GameHelper.Get102();
                    numText = ui.top_money.GetChild("number_text") as GTextField;

                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
                }
                else
                {

                    startNum = GameHelper.GetGoldNumber();
                    temp.change = RewardNum * _rate;
                    temp.type = 101;
                    GameHelper.AddGoldNumber((int)temp.change);

                    endNum = GameHelper.GetGoldNumber();
                    numText = ui.gold.GetChild("number_text");

                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                }

                DOVirtual.DelayedCall(1, () =>
                {
                    DOVirtual.Float(startNum, endNum, 1f,
                        value =>
                        {
                            var str = _isGiftSwitch ? GameHelper.Get102Str((decimal)value) : ((int)value).ToString();
                            if (numText != null)
                                numText.text = str;
                        });
                });

                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
                ClosePanelLogic();
            });
        }

        /// <summary>
        /// 点击Claim按钮
        /// </summary>
        private void OnClickClaim()
        {
            if (!GameHelper.GetCloseResult()) return;
            SetButtonsTouchable(false);
            var start = GameHelper.GetUICenterPosition(ui.btn_claim);
            var end = GameHelper.GetUICenterPosition(_isGiftSwitch
                ? ui.top_money.GetChild("number_text")
                : ui.gold.GetChild("number_text"));

            var startNum = 0f;
            var endNum = 0f;
            GObject numText;

            reward_data temp = new reward_data() { start = start, end = end };
            if (_isGiftSwitch)
            {
                temp.change = _cashNumber;
                temp.type = 111;
                GameHelper.AddMoney(_cashNumber);

                startNum = (float)GameHelper.Get102() - _cashNumber;
                endNum = (float)GameHelper.Get102();
                numText = ui.top_money.GetChild("number_text") as GTextField;

                DOVirtual.DelayedCall(2.5f, () =>
                {
                    GameHelper.AddInterAdNumber();
                    // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Close);
                });

                GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
            }
            else
            {
                temp.change = RewardNum;
                temp.type = 101;
                GameHelper.AddGoldNumber(RewardNum);

                startNum = 0;
                endNum = GameHelper.GetGoldNumber();
                numText = ui.gold.GetChild("number_text");

                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
            }

            DOVirtual.DelayedCall(1, () =>
            {
                DOVirtual.Float(startNum, endNum, 1f,
                    value =>
                    {
                        var str = _isGiftSwitch ? GameHelper.Get102Str((decimal)value) : ((int)value).ToString();
                        if (numText != null) numText.text = str;
                    });
            });

            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
            ClosePanelLogic();
        }

        /// <summary>
        /// 点击CashOUt按钮
        /// </summary>
        private void OnClickCash()
        {
            if (!GameHelper.GetCloseResult()) return;
            SetButtonsTouchable(false);

            if (is_success)
            {
                var start = GameHelper.GetUICenterPosition(ui.btn_claim);
                var end = GameHelper.GetUICenterPosition(ui.top_money.GetChild("number_text"));

                reward_data temp = new reward_data() { start = start, end = end, change = _cashNumber, type = 111 };
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
                GameHelper.AddMoney(_cashNumber);
                DOVirtual.DelayedCall(1, () =>
                {
                    DOVirtual.Float(0, (float)GameHelper.Get102(), 1f,
                        value =>
                        {
                            (ui.top_money.GetChild("number_text") as GTextField).text =
                                GameHelper.Get102Str((decimal)value);
                        });
                });

                DOVirtual.DelayedCall(2f, () =>
                {
                    uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData);
                    GameHelper.AddInterAdNumber();

                });
                GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
            }
            else
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData);
            }

            ClosePanelLogic();
        }

        /// <summary>
        /// 播放音效
        /// </summary>
        private void PlayDynamicEffect()
        {
            AudioManager.Instance.PlayDynamicEffect(is_success ? AudioConst.Victory : AudioConst.Defeat);
        }


        /// <summary>
        /// 关闭界面逻辑
        /// </summary>
        private void ClosePanelLogic(float delayTime = 2f)
        {
            DOVirtual.DelayedCall(delayTime, () =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Close);
                ShowScrews.Instance.InitLogic(ShowScrews.Instance.gameMode == GameHome.Mode_simple ? GameHelper.GetLevel() : ShowScrews.Instance.GetCurMaxLevel());
            });
        }

        #endregion


        private int _timeCount = 0;
        void TimeEvent()
        {
            _timeCount++;

            if (_timeCount > 3)
            {
                _timeCount = 0;
                _com_cash.broad.t0.Play(() =>
                {
                    var exBrPoolModel = ConfigSystem.GetConfig<exBrPoolModel>();
                    var name_index = Random.Range(0, exBrPoolModel.config_name_list.Count);
                    var money_index = Random.Range(0, exBrPoolModel.config_money_list.Count);
                    // System.DateTime oldtime = System.DateTime.Now.AddSeconds(-Random.Range(1 * 3600, 2 * 3600));
                    // var str = "Congratulations, [color=#e3a13a]" +
                    //            exBrPoolModel.config_name_list[name_index] +
                    //            "[/color] withdrew [color=#83c93c]" +
                    //            exBrPoolModel.config_money_list[money_index] +
                    //            "[/color]dollars";
                    var str = string.Format(
                        _broadTextTemplate,
                        exBrPoolModel.config_name_list[name_index],
                        exBrPoolModel.config_money_list[money_index]);
                    _com_cash.broad.cast_text.text = str;
                    _com_cash.broad.t1.Play();
                });
            }

        }
        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()
        {
            HallManager.Instance.UpdateSecondEvent -= TimeEvent;
        }
        #endregion

    }
}