using System;
using FairyGUI;
using DG.Tweening;
using UnityEngine;
using BingoBrain.Core;
using BingoBrain.HotFix;
using System.Collections.Generic;
using FGUI.JRewardPop;
using Newtonsoft.Json;

namespace BingoBrain
{
    public class ExtraItemUI : BaseUI
    {
        private ExtraItemUICtrl ctrl;
        private ExtraItemModel model;
        private FGUI.JRewardPop.com_extraItem ui;
        private RewardedVal data;
        public int curRatio;
        public List<int> ratioList = new();
        public List<float> chanceList = new();
        public Action<bool> onfinish;
        private int type;
        private bool isRead;
        private float duration = 3;
        private float backDuration = 0.3f;
        private int round = 7;
        private float sizeX = 150;
        private bool isDouble;

        public ExtraItemUI(ExtraItemUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.ExtraItemUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期

        protected override void OnInit()
        {
        }

        protected override void OnClose()
        {
            ui?.FadeOut();
            onfinish?.Invoke(isRead);
            if (type != ui._Extra_extraCoin)
            {
                if (type != ui._Extra_extraCard)
                {
                    data.Release();
                }
            }
        }

        protected override void OnBind()
        {
            ui = baseUI as com_extraItem;
        }

        protected override void OnOpenBefore(object args)
        {
            Audio.Instance.PlayDynamicEffect("pop_open");
        }

        protected override void OnOpen(object args)
        {

            ui?.FadeIn();
            data = args as RewardedVal;

            if (data.Id == 102) ui.curr_type.selectedIndex = 1;
            if (data != null)
            {
                curRatio = 1;
                onfinish = data.onfinish;
                type = data.cont_index;

                var adRewardVo = GameHelper.GetChanceByIdAndNum(data.Id, (int)data.Sum);
                Debug.Log(JsonConvert.SerializeObject(adRewardVo));
                if (adRewardVo != null)
                {
                    foreach (var chance in adRewardVo.probability)
                    {
                        chanceList.Add(chance);
                    }

                    foreach (var ratio in adRewardVo.ratio)
                    {
                        ratioList.Add(ratio);
                    }
                }

                if (ui != null)
                {
                    ui.cont_extra.selectedIndex = data.cont_index;
                    ui.com_roll.list_roll.numItems = ratioList.Count;
                    ui.com_roll.list_roll.SetVirtualAndLoop();
                    ui.com_roll.list_roll.itemRenderer = OnItemRender;
                    ui.btn_more.SetClick(OnBtnMoreClick);
                    ui.btn_claim.SetClick(OnBtnClaimClick);
                    ui.closeButton.SetClick(OnBtnClaimClick);

                    ui.com_roll.list_roll.touchable = false;
                    ui.com_roll.list_roll.numItems = ratioList.Count;

                    var posX = GetPosByIndex(0);
                    ui.com_roll.list_roll.scrollPane.SetPosX(posX, false);
                    if (data.cont_index == ui._Extra_extraCoin)
                    {
                        ui.text_num.text = $"+{GameHelper.GetNoDecimalUnitStr(data.Sum)}";
                    }
                    else if (data.cont_index == ui._Extra_extraCard)
                    {
                        ui.text_cardnum.text = $"+{data.Sum}";
                    }

                    if (type != ui._Extra_extraball)
                    {
                        GameHelper.DelayedShowGObject(this, ui.closeButton, ui.btn_claim);
                    }

                    if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1) ui.btn_more.GetChild("img_saveingpot").visible = true;
                }
            }
            if (GameHelper.IsGiftSwitch()) ui.img_diamond.visible = false;
            else ui.img_ch.visible = false;
        }

        private void OpenCloseClick(bool val)
        {
            ui.btn_more.touchable = val;
            ui.btn_claim.touchable = val;
            ui.closeButton.touchable = val;
        }

        private void OnBtnClaimClick()
        {
            // GameHelper.ShowInterstitial("interstitial_skipAd");
            GameHelper.addInterAdnumber();
            OpenCloseClick(false);
            if (data.cont_index == ui._Extra_extraball)
            {
                data.onResult?.Invoke(false);
                isRead = false;
            }
            else
            {
                isRead = true;
                GetReward();
            }

            CtrlCloseUI();
        }

        private void OnBtnMoreClick()
        {
            isRead = true;
            var val = string.Empty;
            if (data.cont_index == ui._Extra_extraCoin)
            {
                val = "reward_extraCoin";
            }
            else if (data.cont_index == ui._Extra_extraCard)
            {
                val = "reward_extraCard";
            }
            else if (data.cont_index == ui._Extra_extraball)
            {
                val = "reward_extraBall";
            }
            else if (data.cont_index == ui._Extra_extracash3)
            {
                val = "reward_extraCashProp3";
            }
            else if (data.cont_index == ui._Extra_extracash5)
            {
                val = "reward_extraCashProp5";
            }

            GameHelper.GetVideo(val, isSuccess =>
            {
                if (isSuccess)
                {
                    OpenCloseClick(false);
                    isDouble = true;
                    var index = GlobalHarmony.GetChanceList(chanceList);
                    curRatio = ratioList[index];
                    Debug.Log("x" + curRatio);
                    Audio.Instance.PlayDynamicEffect("extra_ad");
                    MoveToListPosByIndex(ui.com_roll.list_roll, index, GetReward);
                }
            });
        }

        void MoveToListPosByIndex(GList list, int index, Action onfinish)
        {
            var posX = GetPosByIndex(index);
            var originX = GetPosByIndex(0);
            var targetX = posX + sizeX * ratioList.Count * round;
            var targetOffset = targetX + sizeX / 2;
            DOVirtual.Float(originX, targetOffset, duration, (prg) =>
            {
                while (prg > sizeX * ratioList.Count)
                {
                    prg -= sizeX * ratioList.Count;
                }

                list.scrollPane.SetPosX(prg, false);
            }).SetEase(Ease.OutSine);

            DOVirtual.DelayedCall(duration + Time.deltaTime, delegate
            {
                DOVirtual.Float(targetOffset, targetX, backDuration, (prg) =>
                {
                    while (prg > sizeX * ratioList.Count)
                    {
                        prg -= sizeX * ratioList.Count;
                    }

                    list.scrollPane.SetPosX(prg, false);
                }).SetEase(Ease.OutSine).OnComplete(() =>
                {
                    DOVirtual.DelayedCall(1.5f, () => { onfinish?.Invoke(); });
                });
            });
        }

        float GetPosByIndex(int index)
        {
            return GetPosByIndex(index, ratioList.Count, sizeX, ui.com_roll.list_roll.width / 2);
        }

        public static float GetPosByIndex(int index, int count, float size, float viewCenter)
        {
            return size * (count - 3 + index) + (viewCenter);
        }

        private void GetReward()
        {
            data.onResult?.Invoke(true);
            if (data.cont_index == ui._Extra_extraCoin)
            {
                // 显示金币变化            
                ui.text_num.text = "+" + GameHelper.GetNoDecimalUnitStr(data.Sum * curRatio);
                data.Sum *= curRatio;

                GameHelper.GetRewardOnly(data.Id, (decimal)data.Sum, RewardOrigin.Play);
            }
            else if (data.cont_index == ui._Extra_extraCard)
            {
                data.Sum *= curRatio;
                GameHelper.GetRewardOnly(data.Id, (decimal)data.Sum, RewardOrigin.Play);
            }
            else if (data.cont_index == ui._Extra_extracash3)
            {
                // 3个钞票格子
                var count = data.cont_index * data.cont_index;
                GameDispatcher.Instance.Dispatch(BingoInfo.AddMoneyCell, count);
            }
            else if (data.cont_index == ui._Extra_extracash5)
            {
                // 5个钞票格子
                var count = (int)data.Sum * curRatio;
                GameDispatcher.Instance.Dispatch(BingoInfo.AddMoneyCell, count);
            }
            else if (data.cont_index == ui._Extra_extraball)
            {
                // 加剩余球
                var val = curRatio * (int)data.Sum;
                val = Mathf.Clamp(val, 0, 5);
                gameDispatcher.Dispatch(BingoInfo.AddBallSum, val);
                BingoCell.AddCallSum++;
            }

            CtrlCloseUI();
        }

        private void OnItemRender(int index, GObject item)
        {
            if (item is com_multi tmpItem)
            {
                tmpItem.text_multi.text = "X" + ratioList[index];
            }
        }

        #endregion
    }
}