using UnityEngine;
using FairyGUI;
using Spine.Unity;
using System;
using System.Collections.Generic;
using FGUI.Common_01;
using Random = UnityEngine.Random;

namespace ChillConnect
{
    public class GetTaskRewardUI : BaseUI
    {
        private GetTaskRewardUICtrl ctrl;
        private GetTaskRewardModel model;
        private FGUI.ZM_Tasks_13.com_task_reward ui;

        public GetTaskRewardUI(GetTaskRewardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.GetTaskRewardUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "ZM_Tasks_13";
            uiInfo.assetName = "com_task_reward";
            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()
        {
            closeCallback?.Invoke();
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_Tasks_13.com_task_reward;
        }
        private Action closeCallback;
        private int rewardNum;
        protected override void OnOpenBefore(object args)
        {

            if (args == null) return;
            var data = (ScrollItemData)args;
            weightList = data.weight;
            boostList = data.Boost;

            rewardNum = data.rewards;
            rate = GetRandomBoost();

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

            InitView();
            // Debug.Log(args);
            int number = data.rewards;
            ui.text_award.text = number.ToString();
            ui.btn_claim.title = "Claim(<img src='ui://o9974uc5lryfcj'/>" + number + ")";
            ui.btn_claim.SetClick(() =>
            {
                GameHelper.addInterAdnumber();
                GameDispatcher.Instance.Dispatch(GameMsg.GetTaskReward, rewardNum);
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Close);
            });
            if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetConfig<CommonModel>().FreeClaims)
            {
                (ui.btn_mult as FGUI.Common_01.btn_claim).state.selectedIndex = 1;
            }
            ui.btn_mult.SetClick(() =>
            {

                if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetConfig<CommonModel>().FreeClaims)
                {
                    StartScroll();
                    SaveData.GetSaveObject().LargeRewardNum++;
                    SaveData.saveDataFunc();
                    ui.btn_claim.touchable = ui.btn_mult.touchable = false;
                }
                else
                {
                    GameHelper.ShowVideoAd("TaskReward", isSuccess =>
                    {
                        if (isSuccess)
                        {
                            StartScroll();
                            ui.btn_claim.touchable = ui.btn_mult.touchable = false;
                            // GameDispatcher.Instance.Dispatch(GameMsg.GetTaskReward, true);
                            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Close);
                        }
                    });
                }


            });

            if (AudioManager.Instance.IsOpenEffect)
            {
                AudioManager.Instance.PlayDynamicEffect(AudioConst.Victoriously);
            }
        }


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

            ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll);
            ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() =>
            {
                rate_idnex++;
                ui.btn_mult.title = "(<img src='ui://o9974uc5lryfck'/>" + +rewardNum * boostList[rate_idnex % 5]+ ")";
            });
            ui.btn_mult.title = "(<img src='ui://o9974uc5lryfck'/>" + +rewardNum * boostList[rate_idnex]+ ")";

            list_1 = new List<item_wheel>() { ((wheel_)ui.wheel.GetChild("wheel_")).item_0, ((wheel_)ui.wheel.GetChild("wheel_")).item_1, (ui.wheel.GetChild("wheel_") as wheel_).item_2, (ui.wheel.GetChild("wheel_") as wheel_).item_3, (ui.wheel.GetChild("wheel_") as wheel_).item_4, (ui.wheel.GetChild("wheel_") as wheel_).item_5, (ui.wheel.GetChild("wheel_") as wheel_).item_6, (ui.wheel.GetChild("wheel_") as wheel_).item_7, };
            //  list_1[2].img_light.visible = true;

            for (int i = 0; i < list_1.Count; i++)
            {
                list_1[i].type.selectedIndex = (i + scroll_number) % 3;
                list_1[i].text_rate.text = "X" + boostList[i % boostList.Length];
            }
        }

        List<item_wheel> list_1;
        private int rate_idnex = 3;
        private int scroll_number;
        List<int> rate_list = new List<int>();
        private int scroll_type = 1;
        private int rate;
        private int[] boostList;
        private void StartScroll()
        {
            ui.btn_mult.SetClick(() => { });
            ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = 5.0f;
            scroll_type = 2;
        }
        private void Scroll()
        {
            if (scroll_type == 1)
            {
                scroll_number++;
                rate_list.Clear();
                for (int i = 0; i < 8; i++)
                {
                    rate_list.Add(boostList[(scroll_number + i) % boostList.Length]);
                }
                for (int i = 0; i < list_1.Count; i++)
                {
                    list_1[i].type.selectedIndex = (i + scroll_number) % 3;
                    list_1[i].text_rate.text = "X" + rate_list[i];
                }

                ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() =>
                {
                    rate_idnex++;
                    ui.btn_mult.title = "(<img src='ui://o9974uc5lryfck'/>" + GameHelper.Get101Str((decimal)rewardNum * boostList[rate_idnex % boostList.Length])+ ")";
                });

                ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll);

            }
            else
            {

                scroll_number++;

                rate_list.Clear();
                for (int i = 0; i < 8; i++)
                {
                    rate_list.Add(boostList[(scroll_number + i) % boostList.Length]);
                }

                // bool need_return = false;

                if (((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale < 2f && list_1[4].text_rate.text == ("X" + rate))
                {
                    Debug.Log($"开始领取2---------------{rewardNum} {rate}");
                    //开始领取
                    int reward = rewardNum * rate;

                    GameDispatcher.Instance.Dispatch(GameMsg.GetTaskReward, reward);

                    CtrlCloseUI();
                    return;
                }
                for (int i = 0; i < list_1.Count; i++)
                {
                    list_1[i].type.selectedIndex = (i + scroll_number) % 3;
                    list_1[i].text_rate.text = "X" + rate_list[i];
                }

                // if (need_return)
                // {
                //     (ui.wheel.GetChild("wheel_") as wheel_).t0.timeScale = 0;
                //     return;
                // }

                ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() =>
                {
                    rate_idnex++;
                    ui.btn_mult.title = "(<img src='ui://o9974uc5lryfck'/>" + GameHelper.Get101Str((decimal)rewardNum * boostList[rate_idnex % boostList.Length]) + ")";
                });

                ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll);
                ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale - 0.3f;

            }

        }

        private int[] weightList;
        public int GetRandomBoost()
        {
            int rate_all = 0;
            for (int i = 0; i < weightList.Length; i++)
            {
                rate_all += weightList[i];
            }

            var videoRewardRate = 0;
            int random_ = Random.Range(0, rate_all);
            int int_ = 0;
            for (int i = 0; i < weightList.Length; i++)
            {
                int_ += weightList[i];
                if (random_ < int_)
                {
                    return boostList[i];
                }
            }

            return videoRewardRate;

        }

    }
}
