using UnityEngine;
using DG.Tweening;
using System;
using FGUI.ZM_Common_01;
using FairyGUI;
using Spine.Unity;

namespace RedHotRoast
{
    public class GameResultUI : BaseUI
    {
        private GameResultUICtrl ctrl;
        private GameResultModel model;
        private FGUI.ZM_GameResult_08.com_end ui;
        private bool IsWin;
        private bool IsLevelSuccess;
        private bool IsH5Reward;

        private float AwardGoldNum = 20;
        private Action closeCallback;

        private int AwardRate = 1;

        public GameResultUI(GameResultUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.GameResultUI;
            this.ctrl = ctrl;
        }

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

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

        protected override void OnClose()
        {
            GameHelper.SetCloseResult(false);
            closeCallback?.Invoke();
            if (IsLevelSuccess && !GameHelper.is_first_login) UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, IsWin);
            if (IsH5Reward)
            {

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


        }
        //
        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_GameResult_08.com_end;
        }

        protected override void OnOpenBefore(object args)
        {
            ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";


            var data = args as SuccessData;
            IsH5Reward = data.IsH5Reward;
            IsLevelSuccess = data.IsLevelSuccess;

            if (GameHelper.IsGiftSwitch() && IsLevelSuccess && !IsH5Reward) {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Open);

                GameHelper.PlayGameTimeEvent(1, () => {
                    GameHelper.RequestGameConfig();
                });
            } else {
                GameHelper.SetCloseResult(true);
            }


            if (Screen.safeArea.y != 0)
            {
                ui.btn_gold.y += Screen.safeArea.y;
            }

            // AwardNum = data.ch_number;
            IsWin = data.IsWin;
            if (IsWin)
            {
                if (AudioManager.Instance.IsOpenEffect)
                {
                    AudioManager.Instance.PlayDynamicEffect(AudioConst.Victoriously);
                }

            }

            if (IsWin)
            {
                ui.win_lose.selectedIndex = ui._Win_lose_win;
            }
            else
            {
                ui.win_lose.selectedIndex = ui._Win_lose_lose;
            }

            ui.btn_restart.SetClick(() =>
            {
                if (!GameHelper.GetCloseResult()) return;

                GameHelper.addInterAdnumber();
                if (!IsWin) GameHelper.SetLevelstate(3);
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Close);
            });

            float ch_number = Mathf.Floor(data.ch_number);
            //背景动画
            var anim_bg = FXManager.Instance.SetFx<SkeletonAnimation>(ui.GetChild("bg_parent") as GGraph, Fx_Type.fx_end_bg, ref closeCallback);
            if (IsWin)
            {
                AwardRate = data.rate;
                ui.btn_mult.GetChild("title").text = Language.GetContentParams("exchange_succ", AwardRate);
                anim_bg.state.SetAnimation(0, "win", false);
                anim_bg.state.Complete += (trackEntry) =>
                {
                    anim_bg.state.SetAnimation(0, "win_stop", true);
                };

                var fireworks = FXManager.Instance.SetFx<SkeletonAnimation>(ui.GetChild("congra_parent") as GGraph, Fx_Type.fx_win, ref closeCallback);
                fireworks.state.SetAnimation(0, "out", true);

                var coin = FXManager.Instance.SetFx<SkeletonAnimation>(ui.GetChild("coin_parent") as GGraph, Fx_Type.fx_wins, ref closeCallback);
                coin.state.SetAnimation(0, "animation", true);
                coin.state.Complete += (trackEntry) =>
                {
                    coin.state.SetAnimation(0, "animation2", true);
                };
            }
            else
            {
                anim_bg.state.SetAnimation(0, "lose", false);
                anim_bg.state.Complete += (trackEntry) =>
                {
                    anim_bg.state.SetAnimation(0, "lose_stop", true);
                };
            }

            InitView();

            if (GameHelper.IsGiftSwitch())
            {
                if (IsWin) ui.text_award.text = GameHelper.Get102Str((decimal)ch_number);
                else
                {
                    ui.text_award.text = GameHelper.Get102Str(DataMgr.Coin.Value);
                }

                ui.btn_mult.SetClick(() =>
                     {
                        if (!GameHelper.GetCloseResult()) return;

                         GameHelper.ShowVideoAd("reward_lobby", isSuccess =>
                         {
                             if (isSuccess)

                             {
                                 ui.btn_claim.SetClick(() => { });
                                 ui.btn_mult.SetClick(() => { });
                                 float reward = ch_number * AwardRate;
                                 GetReward(reward, ui.btn_mult);

                                 GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
                             }
                         });
                     });
                ui.btn_claim.SetClick(() =>
                {
                    if (!GameHelper.GetCloseResult()) return;

                    ui.btn_claim.SetClick(() => { });
                    ui.btn_mult.SetClick(() => { });
                    DOVirtual.DelayedCall(2f, () =>
                   {
                       GameHelper.addInterAdnumber();
                   });
                    GetReward(ch_number,ui.btn_claim);
                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);

                });

            }
            else
            {

                ui.text_award.text = AwardGoldNum.ToString();
                ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";

                ui.btn_mult.SetClick(() =>
                     {
                        if (!GameHelper.GetCloseResult()) return;

                         GameHelper.ShowVideoAd("reward_lobby", isSuccess =>
                         {
                             if (isSuccess)

                             {
                                 ui.btn_claim.SetClick(() => { });
                                 ui.btn_mult.SetClick(() => { });

                                 GetReward(AwardGoldNum * AwardRate,  ui.btn_mult);

                                 GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                             }
                         });
                     });
                ui.btn_claim.SetClick(() =>
                {
                    if (!GameHelper.GetCloseResult()) return;

                    ui.btn_claim.SetClick(() => { });
                    ui.btn_mult.SetClick(() => { });

                    GetReward(AwardGoldNum, ui.btn_claim);
                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                });
            }
        }

        private void GetReward(float awardNum, GObject obj)
        {
            var startObj = obj;
            var endObj =  ui.btn_gold;

            var pos = GameHelper.GetUICenterPosition(endObj);

            var rewardData = new RewardData();
            var rewardSingleData = new RewardSingleData(101, (decimal)awardNum, RewardOrigin.Play)
            {
                startPosition = GameHelper.GetUICenterPosition(startObj),
                endPosition = new Vector2(pos.x - 260, pos.y - 136)
            };

            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted(success =>
            {
                if (success)
                {
                    RefreshAwardNum((decimal)awardNum, 101);

                    DOVirtual.DelayedCall(1.5f, () =>
                    {
                        CtrlCloseUI();
                    });
                }
            });
            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
        }

        private void RefreshAwardNum(decimal num = -1, int id = 101)
        {
            if (num < 0)
            {
                num = DataMgr.Coin.Value;
            }
            var btnCoin = ui.btn_gold as com_gold;

            GTextField gTextField =  btnCoin.text_gold;
            CommonHelper.ShowNumAnim(gTextField, num, id);
        }

        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()
        {


        }
    }
}
