using Spine.Unity;

namespace ChillConnect
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using DG.Tweening;
    using FairyGUI;
    using FGUI.Common_01;
    using UnityEngine;

    public class RewardUI : BaseUI
    {
        private RewardUICtrl ctrl;
        private RewardModel model;
        private FGUI.Reward_10.com_reward ui;

        private bool isMultiple = false;
        private Action closeCallback;



        public RewardUI(RewardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.RewardUI;
            this.ctrl = ctrl;
        }

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

        protected override void OnInit()
        {
            model = moduleManager.GetModel(ModelConst.RewardModel) as RewardModel;
        }

        protected override void OnClose()
        {
            tween?.Kill();
            CommonHelper.FadeOut(ui);
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.Reward_10.com_reward;
        }

        protected override void OnOpenBefore(object args)
        {

            InitData();
            InitView();
            //  ui.btn_null.SetClick(() => { });
        }

        protected override void OnOpen(object args)
        {
            CommonHelper.FadeIn(ui);
            if (GetRewardOrigin() == RewardOrigin.H5Icon)
            {
                uiMask.touchable = false;
            }
        }

        private void InitData()
        {
            foreach (var rewardSingleData in ctrl.rewardInfo.GetRewardDataList()
                         .Where(rewardSingleData => rewardSingleData.multiRate == 1))
            {
                rewardSingleData.multiRate = rewardSingleData.origin == RewardOrigin.Play
                    ? GameHelper.GetQuizRate()
                    : GameHelper.GetVideoRate();
            }


        }

        private void InitView()
        {
            Debug.Log(GetRewardOrigin());
            AudioManager.Instance.PlayDynamicEffect("reward_show");
            if (GetRewardOrigin() == RewardOrigin.H5Icon)
            {
                uiMask.touchable = false;
            }

            var value = GetRewardValue();
            ui.text_num.text = GameHelper.Get101Str(value);
            ui.btn_collect.title = "Claim(<img src='ui://o9974uc5lryfcj'/>" + GameHelper.Get101Str((decimal)value) + ")";
            DOVirtual.DelayedCall(0.2f, () =>
            {
                var gamwin =
                    FXManager.Instance.SetFx<SkeletonAnimation>(ui.fx_place, Fx_Type.gamwin, ref closeCallback);
                gamwin.state.SetAnimation(0, "out", true);
            });

            ui.btn_multi.SetClick(OnClickDouble);
            ui.btn_collect.SetClick(OnClickClaim);
            if (ctrl.rewardInfo.sign_in_days == 6)
            {
                ui.state.selectedIndex = 1;
                setItemUrl(ui.loader_icon0, ConfigSystem.GetConfig<SignDailyRewardModel>().DataList[6].rewards_type[1]);
                ui.text_num1.text = "x" + ConfigSystem.GetConfig<SignDailyRewardModel>().DataList[6].quantity[1];
            }
            SetName();
            SetAvatar();
            Set101();

            //boost_array = GameHelper.GetRewardBoost(2);
            int[] weight_array = null;
            Debug.Log(GetRewardIndex());
            if (GetRewardOrigin() == RewardOrigin.Passview)
            {
                boost_array = ConfigSystem.GetConfig<PassportrewardsModel>().DataList[GetRewardIndex()].Boost;
                weight_array = ConfigSystem.GetConfig<PassportrewardsModel>().DataList[GetRewardIndex()].weight;

            }
            else if (GetRewardOrigin() == RewardOrigin.SignIn)
            {
                boost_array = ConfigSystem.GetConfig<SignDailyRewardModel>().DataList[GetRewardIndex()].Boost;
                weight_array = ConfigSystem.GetConfig<SignDailyRewardModel>().DataList[GetRewardIndex()].weight;

            }
            else if (GetRewardOrigin() == RewardOrigin.LuckyWheel)
            {
                boost_array = ConfigSystem.GetConfig<TurntableModel>().DataList[GetRewardIndex()].Boost;
                weight_array = ConfigSystem.GetConfig<TurntableModel>().DataList[GetRewardIndex()].weight2;

            }
            int rate_all = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                rate_all += weight_array[i];
            }
            int random_ = UnityEngine.Random.Range(0, rate_all);
            int int_ = 0;
            for (int i = 0; i < weight_array.Length; i++)
            {
                int_ += weight_array[i];
                if (random_ < int_)
                {
                    rate = boost_array[i];
                    break;
                }
            }
            cash_num = value;

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

            list_1 = new List<item_wheel>() { (ui.wheel.GetChild("wheel_") as wheel_).item_0, (ui.wheel.GetChild("wheel_") as 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" + boost_array[i % boost_array.Length];
            }
            if (SaveData.GetSaveObject().LargeRewardNum < GameHelper.GetCommonModel().FreeClaims)
            {
                (ui.btn_multi as FGUI.Common_01.btn_claim3).state.selectedIndex = 1;
            }

        }
        void setItemUrl(GLoader loader, int urltype)
        {
            if (urltype == 0) loader.url = "ui://ZM_Common_01/cards_gold";  //jinbi
            else if (urltype == 1) loader.url = "ui://Common_01/spin_remove";   //yichu
            else if (urltype == 2) loader.url = "ui://Common_01/spin_undo";   //chehui
            else if (urltype == 3) loader.url = "ui://Common_01/spin_refresh";  //shuaxin
        }
        private Tween tween;

        public void Set101(decimal ch = -1)
        {
            if (ch < 0)
            {
                ch = GameHelper.Get101();
            }

            // ui.text_num1.text = $"{GameHelper.Get101Str(ch)}";
        }

        private void SetAvatar()
        {
            // GameHelper.SetSelfAvatar(((btn_avatar)ui.btn_av).loader_avatar);
        }

        private void SetName()
        {
            // GameHelper.SetName(ui.text_name);
        }

        private RewardSingleData GetRewardData(int index = 0)
        {
            return ctrl.rewardInfo.GetRewardDataList()[index];
        }

        private decimal GetRewardValue(int index = 0)
        {
            return GetRewardData(index).value;
        }

        private RewardOrigin GetRewardOrigin(int index = 0)
        {
            return GetRewardData(index).origin;
        }
        private int GetRewardIndex(int index = 0)
        {
            return GetRewardData(index).index;
        }
        private void OnClickClaim()
        {
            if (ctrl.rewardInfo.condition == RewardCondition.AD)
            {
                GameHelper.ShowInterstitial("interstitial_skipDouble");
            }
            ctrl.GetReward();
            CtrlCloseUI();
        }

        private void OnClickDouble()
        {

            if (SaveData.GetSaveObject().LargeRewardNum < GameHelper.GetCommonModel().FreeClaims)
            {
                StartScroll();
                ui.btn_collect.touchable = ui.btn_multi.touchable = false;
            }
            else
            {
                GameHelper.ShowVideoAd("RewardBox", isSuccess =>
                {
                    if (isSuccess)
                    {
                        StartScroll();
                        ui.btn_collect.touchable = ui.btn_multi.touchable = false;
                    }
                });
            }
        }

        private decimal cash_num;
        private int[] boost_array;
        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 void StartScroll()
        {
            ui.btn_multi.SetClick(() => { });
            (ui.wheel.GetChild("wheel_") as 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(boost_array[(scroll_number + i) % boost_array.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];
                }

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

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

            }
            else
            {

                scroll_number++;

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

                // bool need_return = false;
                if (((ui.wheel.GetChild("wheel_") as wheel_).t0.timeScale < 2f) && (list_1[4].text_rate.text == ("X" + rate)))
                {
                    //开始领取
                    // float reward = cash_num * rate;
                    // if (DataMgr.VipLevel.Value >= 1)
                    // {
                    //     reward *= 2;
                    // }

                    // GameDispatcher.Instance.Dispatch(GameMsg.Ad_success, reward);

                    ctrl.GetReward(rate);
                    CtrlCloseUI();

                    SaveData.GetSaveObject().LargeRewardNum++;
                    SaveData.saveDataFunc();
                    DOVirtual.DelayedCall(1.5f, () =>
                    {
                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardboxUI_Close);
                    });
                    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;
                // }

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

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

            }

        }
    }
}
