using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using DontConfuse;
using FGUI.G004_webview;
using Roy.Datas;
using UnityEngine;
using Random = UnityEngine.Random;

namespace ScrewsMaster
{
    public class H5UI : BaseUI
    {
        private Tween bubbleMoveTween;

        private Action closeCallBack;
        private CountDownKit countDownKit;
        private H5UICtrl ctrl;

        private int currentTabIndex;

        private int flyClickCount;

        private int flyNeedClickCount;

        private int iconClickCount;

        private decimal iconTime;


        private bool isAddFinger;


        private bool isCurrentTaskFinish;


        private bool isCurrentTimeTask;


        private bool isLoadFinish;


        private bool isScrolling;


        private bool isTimeOut = false;

        private decimal makeupTaskH5NeedTime;
        private H5Model model;

        private readonly List<Vector3> movePointList = new();

        private long openTime;


        private decimal scrollOutTime;
        public com_webview ui;

        private decimal updateTime;

        private bool _flySwitch;
        private bool _propSwitch;

        private bool isFlyShow = false;


        public H5UI(H5UICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.H5UI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "G004_webview";
            uiInfo.assetName = "com_webview";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
            uiInfo.uiMaskCustomColor = Color.white;
            uiInfo.isTickUpdate = true;
        }

        public override void OnUpdate()
        {
            if (iconTime < ConfigSystem.GetConfig<CommonModel>().ThroughRewardCD)
            {
                iconTime += (decimal)Time.deltaTime;
                UpdateIcon();
            }

            updateTime += (decimal)Time.deltaTime;
            if (makeupTaskData_saveing.status == SaveingPotTaskStatus.None)
            {
                if (PreferencesMgr.Instance.ExchangeAccount != null)
                {
                    makeupTaskData_saveing.H5Time += (float)updateTime;
                }
            }
            if (makeupTaskH5NeedTime > 0 && PreferencesMgr.Instance.MakeupTaskH5Time < makeupTaskH5NeedTime)
                if (updateTime >= 1)
                {
                    PreferencesMgr.Instance.MakeupTaskH5Time += updateTime;
                    updateTime = 0;
                }

        }

        private void InitData()
        {
            _flySwitch = GameHelper.GetCommonModel().flyswitch == 1;
            _propSwitch = GameHelper.GetCommonModel().propswitch == 1;
            SdkManager.Instance.ShowFlyBtn(true);

            // HallManager.Instance.SetInH5(true);
            model.show102 = GameHelper.Get102();
            flyNeedClickCount = Random.Range(ConfigSystem.GetConfig<CommonModel>().flyAdTime[0],
                ConfigSystem.GetConfig<CommonModel>().flyAdTime[1] + 1);

            if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0)
            {
                var taskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
                if (taskData != null)
                {
                    var cardRedeemModel = ConfigSystem.GetConfig<MakeupModel>();
                    var makeupVo = cardRedeemModel.dataList.FirstOrDefault(redeem => redeem.id == taskData.tableId);
                    if (makeupVo != null) makeupTaskH5NeedTime = makeupVo.task_need;
                }
            }

#if UNITY_EDITOR
            isLoadFinish = true;
#endif
        }

        private void InitView()
        {
            Set101();
            // WebThroughUtil.WebThroughCreate(H5WebThroughType.OnlineH5, ui.btn_icon);
            ui.btn_close.SetClick(() =>
            {
                // uiCtrlDispatcher.Dispatch(UICtrlMsg.MainUI_Open);
                // uiCtrlDispatcher.Dispatch(UICtrlMsg.BackgroundUI_Open);
                // uiCtrlDispatcher.Dispatch(UICtrlMsg.CurrencyUI_Open);
                //CreatSheepCard.instance.SetCameraVisible(true);
              //  CtrlDispatcher.Instance.Dispatch(CtrlMsg.Webview_StateChange, WebUIType.Game);
                uiCtrlDispatcher.Dispatch(UICtrlMsg.H5UI_Close);


                if (GameHelper.is_first_login)
                {
                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshGame);
                }

                // CtrlCloseUI();
            });

            ui.com_fly.visible = false;
            ui.btn_icon.visible = false;

            InitIcon();

            CheckShowFly();
            ui.com_fly.SetClick(OnClickFlyCash);
            DOVirtual.Float(0, (float)GameHelper.Get102(), 1,
                value => { ui.com_top.text_num.text = GameHelper.Get102Str((decimal)value); });
            SetMakeup();

            ui.btn_out.visible = GameHelper.IsGiftSwitch();
            ui.com_top.ContentBox.visible = GameHelper.IsGiftSwitch();
        }

        private void InitIcon()
        {
            ui.btn_icon.cont_state.selectedIndex = btn_icon.State_none;
            ui.btn_icon.fx_ready.Stop();
            ui.btn_icon.SetClick(OnClickIcon);
            ui.btn_icon.visible = false;
            UpdateIcon();
        }
        private SaveingPotClass makeupTaskData_saveing;
        void OnRefreshMakeupData(object obj)
        {
            SetMakeup();
        }

        private void UpdateIcon()
        {

            if (!_propSwitch)
            {
                return;
            }
            float amount = (float)iconTime / ConfigSystem.GetConfig<CommonModel>().ThroughRewardCD;


            SdkManager.Instance.SetIconProgress(amount);

            if (!_propSwitch)
            {
                return;
            }

            // if (_propSwitch && !ui.btn_icon.visible)
            // {
            //     ui.btn_icon.visible = true;
            // }
            ui.btn_icon.pb_time.fillAmount = (float)iconTime / ConfigSystem.GetConfig<CommonModel>().ThroughRewardCD;
            if (iconTime >= ConfigSystem.GetConfig<CommonModel>().ThroughRewardCD)
            {
                if (!ui.btn_icon.fx_ready.playing) ui.btn_icon.fx_ready.Play();

                ui.btn_icon.cont_state.selectedIndex = btn_icon.State_ready;
            }
            else
            {
                ui.btn_icon.fx_ready.Stop();
            }
        }

        private void OnClickIcon()
        {
            // if (UIManager.Instance.IsExistUI(UIConst.DialogRewardUI)) return;

          //  WebThroughUtil.WebThroughClick(H5WebThroughType.OnlineH5, ui.btn_icon);
            if (iconTime < ConfigSystem.GetConfig<CommonModel>().ThroughRewardCD) return;

            // var rewardData = new RewardData();

            // var rewardType = GameHelper.GetCommonModel().ThroughRewardType;
            float[] cash_array = GameHelper.GetRewardValue(2);
            // var temp = new { is_success = true, cash_number = cash_array[0], rate = cash_array[1], is_level_success = false, is_h5_reward = true };
            // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp);

            var temp = new SettlementData { cash_number = cash_array[0], rate = cash_array[1], is_h5_reward = true };
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, temp);

            // decimal rewardValue = GameHelper.GetCommonModel().ThroughReward.RandomInt();

            // var rewardSingleData = new RewardSingleData(rewardType, (decimal)cash_array[0], RewardOrigin.H5Icon)
            // {
            //     startPosition = new Vector2(GameHelper.GetUICenterPosition(ui.btn_icon).x - 250, GameHelper.GetUICenterPosition(ui.btn_icon).y - 50),//GameHelper.GetUICenterPosition(ui.btn_icon),
            //     endPosition = GameHelper.GetUICenterPosition(ui.com_top.icon_101)
            // };
            // rewardData.AddReward(rewardSingleData);
            // rewardData.AddCompleted(isSuccess =>
            // {
            ui.btn_icon.cont_state.selectedIndex = btn_icon.State_none;
            // iconTime = 0;
            // SetMakeup();
            // });
            // rewardData.condition = RewardCondition.AD;
            // rewardData.displayType =
            //     RewardDisplayType.Dialog | RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;

            // GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
        }


        public void Set101(decimal cash = -1)
        {
            if (cash < 0) cash = GameHelper.Get102();

            var cashNumt = GameHelper.Get101String(cash);
            ui.com_top.text_num.text = $"{cashNumt}";
        }

        public void OnLoadFinish()
        {
            isLoadFinish = true;
        }

        private void SetMakeup()
        {
            var comBox = ui.com_top;
            comBox.text_num.text = $"{GameHelper.Get101String()}";
            if (!GameHelper.IsGiftSwitch()) return;
            if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0) return;

            var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last();
            var vo = ConfigSystem.GetConfig<MakeupModel>().dataList
                .FirstOrDefault(redeem => redeem.id == makeupTaskData.tableId);
            if (vo == null) return;

            var leftCash = (double)Math.Max(vo.item_need - GameHelper.Get102(), 0);
            comBox.text_more.SetVar("money", $"{GameHelper.Get102Str((decimal)leftCash)}").FlushVars();
            // comBox.text_more.text = GameHelper.Get101Str((decimal)leftCash);
            comBox.pb_num.max = vo.item_need;
            comBox.pb_num.TweenValue(vo.item_need - leftCash, 0.1f);
            comBox.pb_num.GetChild("title").text =
                $"{GameHelper.Get102Str((decimal)(vo.item_need - leftCash))}/{GameHelper.Get102Str((decimal)comBox.pb_num.max)}";

            ui.btn_out.SetClick(() =>
            {
                uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData);
            });
        }

        public void SetCash(string str102 = null)
        {
            if (str102 == null)
                str102 = GameHelper.Get102() == -1
                    ? GameHelper.GetCommonModel().InitialNum.ToString("N")
                    : GameHelper.Get102().ToString("N");


            ui.com_top.text_num.text = "$" + str102;
        }

        #region 生命周期

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

        protected override void OnClose()
        {
            GameHelper.showGameUI = true;

            SdkManager.Instance.ShowH5View(false);
           // WebThroughUtil.WebThroughDisable(H5WebThroughType.OnlineH5, ui.btn_icon);
            StopFly();
            countDownKit?.OnDestroy();
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);
            CommonHelper.FadeOut(ui);
        }
        public Camera orthoCamera;


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

        protected override void OnOpenBefore(object args)
        {
            if (Screen.safeArea.y != 0)
            {
                ui.TopBox.height += Screen.safeArea.y;
                // ui.TopBox.y += Screen.safeArea.y;    
            }

            SdkManager.Instance.ShowH5View(true);
            makeupTaskData_saveing = SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1];
            InitData();
            InitView();
        }

        protected override void OnOpen(object args)
        {
            openTime = GameHelper.GetNowTime();
            CommonHelper.FadeIn(ui);
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            HallManager.Instance.AddChangeGiftSwitch(InitView);
            GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, OnRefreshMakeupData);
            GameDispatcher.Instance.AddListener(GameMsg.resetH5progress, ResetTime);

        }

        protected override void RemoveListener()
        {
            HallManager.Instance.RemoveChangeGiftSwitch(InitView);
            GameDispatcher.Instance.RemoveListener(GameMsg.RefreshMakeupData, OnRefreshMakeupData);
            GameDispatcher.Instance.RemoveListener(GameMsg.resetH5progress, ResetTime);

        }

        #endregion

        void ResetTime(object a = null)
        {
            iconTime = 0;
            SetMakeup();
        }

        #region 飞行美元

        private void CheckShowFly()
        {
            var nowTime = GameHelper.GetNowTime();
            var leftTime = (int)(PreferencesMgr.Instance.AdCashFlyShowTime - nowTime);

            ui.com_fly.visible = false;

            if (!_flySwitch) return;

            // ui.com_fly.visible = leftTime <= 0;
            if (leftTime > 0)
            {
                SdkManager.Instance.ShowFlyBtn(false);
                isFlyShow = false;

                StopFlyCountdown();
                StartFlyCountdown(leftTime);
            }
            else
            {
                if (!isFlyShow) SdkManager.Instance.ShowFlyBtn(true);
                isFlyShow = true;

                StartFly();
                StopFlyCountdown();
            }
        }

        private void StartFly()
        {
            StopFly();
            SetFlyPoints();

            var bubbleGo = ui.com_fly.displayObject.gameObject;
            bubbleMoveTween = bubbleGo.transform
                .DOLocalPath(movePointList.ToArray(), 20)
                .SetEase(Ease.Linear)
                .OnComplete(StartFly)
                .SetAutoKill(true)
                .OnUpdate(() =>
                {
                   // WebThroughUtil.WebThroughCreate(H5WebThroughType.Fly, ui.com_fly);
                });
        }

        private void SetFlyPoints()
        {
            movePointList.Clear();

            var w = ui.fly_area.width;
            var h = ui.fly_area.height - 173;
            var startPos = ui.fly_area.position;
            w -= ui.com_fly.width;

            var pos1 = new Vector3(startPos.x + w - CommonHelper.RandomRange(30, 100), startPos.y);
            ui.com_fly.position = pos1;
            movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos1));

            var pos2 = new Vector3(startPos.x, startPos.y + CommonHelper.RandomRange((int)(h / 4f), (int)(h / 2 - h / 8)));
            movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos2));

            var pos3 = new Vector3(startPos.x + w, startPos.y + h / 2 + CommonHelper.RandomRange((int)(h / 8), (int)(h / 4)));
            movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos3));

            var pos4 = new Vector3(startPos.x + CommonHelper.RandomRange(0, 20),
                startPos.y + h + CommonHelper.RandomRange(-20, 20));
            movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos4));
        }

        private void StopFly()
        {
            bubbleMoveTween?.Kill();
        }

        private void StartFlyCountdown(int leftTime)
        {
            countDownKit = new CountDownKit();
            countDownKit.SetTime(leftTime)
                .SetCountDownType(CountDownType.Second)
                .SetCompletedEvent(CheckShowFly);

            countDownKit.Start();
        }

        private void StopFlyCountdown()
        {
            countDownKit?.Stop();
            countDownKit = null;
        }

        private void CheckShowFlyVideo(int times)
        {
            var configTimes = ConfigSystem.GetConfig<CommonModel>().flytimes;

            Debug.Log($"CheckShowFlyVideo times=== {times} configTimes=== {configTimes}");
            if (times != 0 && configTimes != 0 && times % configTimes == 0)
            {
                PlayerPrefs.SetInt($"ShowFlyVideo", 0);
                GameHelper.AddInterAdNumber();
            }
        }

        private long _lastClickFlyCash;
        private void OnClickFlyCash()
        {
            // var nowTime = GameHelper.GetNowTime();
            // if (_lastClickFlyCash == nowTime)
            // {
            //     return;
            // }
            // _lastClickFlyCash = nowTime;
            //
            // var times = PlayerPrefs.GetInt($"ShowFlyVideo", 0);
            // int localTimes = times + 1;
            //
            // PlayerPrefs.SetInt($"ShowFlyVideo", localTimes);
            // CheckShowFlyVideo(localTimes);

            PreferencesMgr.Instance.AdCashFlyShowTime =
                GameHelper.GetNowTime() + ConfigSystem.GetConfig<CommonModel>().flyCD;
            var rewardData = new RewardData();

          //  WebThroughUtil.WebThroughClick(H5WebThroughType.Fly, ui.com_fly);

            var singleValue =
                (decimal)Math.Round(
                    Random.Range(ConfigSystem.GetConfig<CommonModel>().flyReward[0],
                        ConfigSystem.GetConfig<CommonModel>().flyReward[1]), 2);
            decimal rewardValue;


            if (flyClickCount >= flyNeedClickCount)
            {
                flyClickCount = 0;
                rewardValue = singleValue;
                GameHelper.ShowVideoAd("reward_fly", isCompleted =>
                {
                    if (isCompleted)
                    {
                        GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
                        GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
                    }
                });
            }
            else
            {
                rewardValue = singleValue;
            }

            var rewardSingleData = new RewardSingleData(102, rewardValue, RewardOrigin.H5Fly101)
            {
                startPosition = GameHelper.GetUICenterPosition(ui.com_fly),
                endPosition = GameHelper.GetUICenterPosition(ui.com_top.icon_101)
            };

            rewardData.AddReward(rewardSingleData);
            rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;
            rewardData.AddCompleted(isSuccess =>
            {
                if (isSuccess) flyClickCount++;

                SetMakeup();
            });
            GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
            GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData);
            CheckShowFly();
        }

        #endregion

        public void ClickBtn(string name)
        {
            // // Debug.Log("[UNITY] Click btn: " + name);
            // FGUIHelper.PlayClickSound();
            if (name == "flyBtn")
            {
                OnClickFlyCash();
                NetworkKit.BuriedPoint(BuriedPointEvent.Hall_behavior, BuriedPointEvent.collect_fly_number, 1);
                //NetworkKit.BuriedPoint(BuriedPointEvent.Hall_behavior,BuriedPointEvent.collect_fly_people,1);
            }
            else if (name == "rewardBtn")
            {
                OnClickIcon();

            }
        }
    }
}