using UnityEngine;
using FairyGUI;
using Spine.Unity;
using System;
using System.Linq;
using DG.Tweening;
using FGUI.A000_common;
using FGUI.G008_reward;
using FGUI.G009_video;
using Newtonsoft.Json;
using Roy.Datas;
using Random = UnityEngine.Random;
using DontConfuse;

namespace ScrewsMaster
{
    public class GetTaskRewardUI : BaseUI
    {
        private GetTaskRewardUICtrl ctrl;
        private GetTaskRewardModel model;
        private FGUI.G009_video.com_gettaskreward ui;
        
        private float _rewardNum;
        private float _rateNum;
        private SettlementData _settlementData;
        private bool _isTaskReward;
        private bool _isGiftSwitch;
        private string _broadTextTemplate;
        
        public GetTaskRewardUI(GetTaskRewardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.GetTaskRewardUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose()
        {
            
            HallManager.Instance.UpdateSecondEvent -= TimeEvent;
            closeCallback?.Invoke();
            if (_settlementData != null && _settlementData.is_h5_reward)
            {
                SdkManager.Instance.ShowH5View(true);
                GameDispatcher.Instance.Dispatch(GameMsg.resetH5progress);
            }
            
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.G009_video.com_gettaskreward;
        }
        
        private Action closeCallback;
        
        protected override void OnOpenBefore(object args)
        {
            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;
            }
            
            _rateNum = 2;
            if (args is SettlementData settlementData)
            {
                _settlementData = settlementData;
                _rewardNum = _settlementData.cash_number;
                _rateNum = _settlementData.rate;

                if (_settlementData.is_h5_reward)
                {
                    SdkManager.Instance.ShowH5View(false);
                }

                _isTaskReward = false;
                
            }
            else if (args is int num)
            { 
                _rewardNum = num;
                _isTaskReward = true;
                
            }

            _isGiftSwitch = GameHelper.IsGiftSwitch();
            InitView();
        }

        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 InitView()
        {
            ui.switchgift.selectedIndex = _isGiftSwitch && !_isTaskReward ? 1 : 0;
            
            if (_isGiftSwitch)
            {
                InitCashView();
            }
            ui.top_money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102());
            ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString();
            
            //添加特效动画
            // var sk = FXManager.Instance.SetFx<SkeletonAnimation>(baseUI.GetChild("bg_parent") as GGraph, Fx_Type.fx_win, ref closeCallback);
            // sk.state.SetAnimation(0, "out", true);
                
            var sk = FXManager.Instance.SetFx<SkeletonAnimation>(baseUI.GetChild("bg_parent") as GGraph, Fx_Type.fx_win_light, ref closeCallback);
            sk.state.SetAnimation(0, "animation", true);
             if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) (ui.btn_adclaim.GetChild("img_saveingpot") as GImage).visible = true;
            
            // int number = (int)args;
            ui.money_text.text = _rewardNum.ToString();
            ui.btn_adclaim.text = $"Claim X{_rateNum}";
            
            // ((btn_tabad)ui.btn_adclaim).color.selectedIndex = 1;
            
            ui.btn_claim.SetClick(() =>
            {
                SetButtonsTouchable(false);
                DistributeReward(false);
            });
            
            ui.btn_adclaim.SetClick(() =>
            {
                SetButtonsTouchable(false);
                GameHelper.ShowVideoAd("reward_lobby", isSuccess =>
                {
                    if (isSuccess)
                    {
                        DistributeReward(true);
                    }
                    else
                    {
                        SetButtonsTouchable(true);
                    }
                });

            });
            
        } 
        
        /// <summary>
        /// 禁用界面上所有按钮点击
        /// </summary>
        /// <param name="enable"></param>
        private void SetButtonsTouchable(bool enable)
        {
            ui.btn_adclaim.touchable = enable;
            ui.btn_claim.touchable = enable;
            ui.com_cash.touchable = enable;
            ui.top_money.GetChild("btn_cashout").touchable = enable;
        }
        
        private MakeupTaskData _makeupTaskData;
        private com_success_cash _com_cash;
        private float _progressBarWidth = -1;
        private void InitCashView()
        {
            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);
              
            _com_cash = ui.com_cash as com_success_cash;
            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;
            float progressWidth;
            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;
            
            _com_cash.btn_cash.SetClick(OnClickCash);
            
            HallManager.Instance.UpdateSecondEvent += TimeEvent;
        }
        
        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();
                });
            }
        
        }
        /// <summary>
        /// 点击CashOUt按钮
        /// </summary>
        private void OnClickCash()
        {
            SetButtonsTouchable(false);
            DistributeReward(false);
            uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData);
        }

        private void DistributeReward(bool isMultiRewardEnabled)
        {
            if (_isTaskReward)
            {
                GameDispatcher.Instance.Dispatch(GameMsg.GetTaskReward, isMultiRewardEnabled);
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Close);
                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};
            var changeNum = _rewardNum * (isMultiRewardEnabled ? _rateNum : 1);
            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);
        
            
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp);
            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;
                    });

                DOVirtual.DelayedCall(1.5f, () =>
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Close);
                    if (!isMultiRewardEnabled)
                    {
                        GameHelper.AddInterAdNumber();
                    }
                });

            });

        }
    }
}