using System;
using System.IO;
using FairyGUI;
using FGUI.LG_Common;
using FGUI.LG_live;
using Newtonsoft.Json;
using SGModule.Common.Extensions;
using SGModule.NetKit;
using UnityEngine;
using UnityEngine.Video;
using Object = UnityEngine.Object;

namespace RedHotRoast
{
    public class LiveDetailUI : BaseUI
    {
        private LiveDetailUICtrl ctrl;
        private LiveDetailModel model;
        private com_liveDetail ui;
        private VideoPlayer video;

        public LiveDetailUI(LiveDetailUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.LiveDetailUI;
            this.ctrl = ctrl;
        }

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

        //初始化页面逻辑
        private void Updata()
        {
            if (GameHelper.GetNowTime() < livedata_.LiveADTime)
            {
                Debug.Log("??????????????????");
                (ui.btn_watchad as btn_claim_4).state.selectedIndex = 1;
                (ui.btn_watchad as btn_claim_4).text_time.text = CommonHelper.TimeFormat(
                    (int)livedata_.LiveADTime - Convert.ToInt32(GameHelper.GetNowTime()),
                    CountDownType.Hour);
            }
            else
            {
                (ui.btn_watchad as btn_claim_4).state.selectedIndex = 0;
                if (LiveConfig.AD == livedata_.AD_num + 1)
                    ui.btn_watchad.title = "+" + (100 - livedata_.progress) + "%";
                else
                    ui.btn_watchad.title = "+" + livedata_.Singleprogress + "%";
            }
        }

        private void InitView()
        {
            Updata();

            var btn_down_coin = ui.btn_download_coin;
            if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As<int>()))
            {
                ui.btn_download.have_vip.selectedIndex = 1;
                ui.is_vip.selectedIndex = 1;
            }
            else
            {
                ui.is_vip.selectedIndex = 0;
                btn_down_coin.down_load.selectedIndex = 1;
            }

            if (livedata_.progress < 100)
            {
                ui.state.selectedIndex = 0;
                if (LiveConfig.AD == 0)
                {
                    ui.can_speed.selectedIndex = 1;
                }
                if (LiveConfig.SubscribeUnlock == 1)
                {
                    ui.SubscribeUnlock.selectedIndex = 1;
                    if (GameHelper.GetVipLevel() > 0)
                    {
                        ui.btn_pay.visible = false;
                        ui.btn_watchad.visible = false;
                    }
                } else
                {
                    ui.SubscribeUnlock.selectedIndex = 0;
                }
            }
            else
            {
                ui.state.selectedIndex = 1;
                ui.SubscribeUnlock.selectedIndex = 0;
                if (video != null) video.Play();
            }

            ui.img_mask.fillAmount = (float)(100 - livedata_.progress) / 100;
            ui.progress_live.value = (float)livedata_.progress;

            //ui.btn_pay.title = LiveConfig.GoldCoins.ToString();
            Debug.Log(LiveConfig.GoldCoins);
            var need_gold = (int)MathF.Ceiling((100f - livedata_.progress) * LiveConfig.GoldCoins / 100);
            ui.btn_pay.title = need_gold.ToString();

            if (LiveConfig.AD == livedata_.AD_num + 1)
                ui.btn_watchad.title = "+" + (100 - livedata_.progress) + "%";
            else
                ui.btn_watchad.title = "+" + livedata_.Singleprogress + "%";


            ui.btn_pay.SetClick(() =>
            {
                if (DataMgr.Coin.Value >= need_gold)
                {
                    DataMgr.Coin.Value -= need_gold;

                    livedata_.progress = 100;
                    DataMgr.LiveDataDic.Value[index] = livedata_;
                    Debug.Log($"[解锁成功 0]  LiveData总数为：  {DataMgr.LiveDataDic.Value.Count}");
                    DataMgr.LiveDataDic.Save();

                    GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                    GameDispatcher.Instance.Dispatch(GameMsg.Update101);
                    GameDispatcher.Instance.Dispatch(GameMsg.LiveChange, index);

                    // HandlePvPlay();
                    InitView();
                    GameHelper.ShowTips("unlock_success", true);
                }
                else
                {
                    GameHelper.ShowTips("no_enough_gold", true);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open);
                }
            });

            ui.btn_watchad.SetClick(() =>
            {
                if (livedata_.LiveADTime < GameHelper.GetNowTime())
                    GameHelper.ShowVideoAd("UnlockLive", isSuccess =>
                    {
                        if (isSuccess)
                        {
                            livedata_.AD_num++;
                            if (LiveConfig.AD == livedata_.AD_num)
                            {
                                livedata_.progress = 100;
                                GameHelper.ShowTips("unlock_success", true);
                            }
                            else
                            {
                                livedata_.progress += livedata_.Singleprogress;
                            }

                            DataMgr.LiveDataDic.Value[index] = livedata_;
                            Debug.Log($"[解锁成功 1]  LiveData总数为：  {DataMgr.LiveDataDic.Value.Count}");
                            DataMgr.LiveDataDic.Save();

                            livedata_.LiveADTime = GameHelper.GetNowTime() + LiveConfig.CD;
                            SaveData.SaveDataFunc();
                            // if (livedata_.progress == 100) HandlePvPlay();
                            InitView();
                            GameDispatcher.Instance.Dispatch(GameMsg.LiveChange, index);
                        }
                    });
            });

            ui.btn_vip_unlock.SetClick(() =>
            {
                if (GameHelper.GetVipLevel() > 0)
                {
                    livedata_.progress = 100;
                    DataMgr.LiveDataDic.Value[index] = livedata_;
                    Debug.Log($"[解锁成功 0]  LiveData总数为：  {DataMgr.LiveDataDic.Value.Count}");
                    DataMgr.LiveDataDic.Save();

                    GameDispatcher.Instance.Dispatch(GameMsg.LiveChange, index);
                    
                    HandlePvPlay();
                    InitView();
                    GameHelper.ShowTips("unlock_success", true);

                    string eventName = ADEventTrack.Property.vip_live_unclock_ + (index + 1);
                    TrackKit.SendEvent(ADEventTrack.VipLive, eventName);
                }
                else
                {
                    uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open,2);
                    TrackKit.SendEvent(ADEventTrack.VipLive, ADEventTrack.Property.vip_live_unclock);
                }
            });
        }

        #region 生命周期

        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.LiveDetailModel) as LiveDetailModel;
        }

        protected override void OnClose()
        {
            if (video != null) Object.Destroy(video.gameObject);
            HallManager.Instance.UpdateSecondEvent -= Updata;

            VideoPlayerHandover.Return();
            // var loader = ui.com_loader.GetChild("loader") as GLoader;
            // if (loader?.texture != null)
            // {
            //     loader.texture.Dispose();
            //     loader.texture = null;
            // }
            
        }

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

        private void HandlePvPlay()
        {
            Debug.Log("HandlePvPlay: " + index);
            var secondUIRoot = ui.displayObject.gameObject.transform;
            var loader = ui.com_loader.GetChild("loader") as GLoader;


            // 接管播放器
            VideoPlayerHandover.TakeOver(player, secondUIRoot, loader, () =>
            {
                // ui.img_cover.visible = false;
            });

            var localPath = Path.Combine(TextureHelper.getResPath(), "LiveVideos", LiveConfig.Name + ".mp4");
            if (!File.Exists(localPath))
            {
                ui.img_cover.visible = true;
                setCover();
            } else
            {
                ui.img_cover.visible = false;
            }
        }

        private int index;
        private VideoPlayer player;
        private LiveData livedata_;
        private Live LiveConfig;

        protected override void OnOpenBefore(object args)
        {
            var tuple = ((int index, VideoPlayer player))args;

            index = tuple.index;
            player = tuple.player;
            if (player != null)
                player.audioOutputMode = VideoAudioOutputMode.None;

            // 从配置表取配置（这里还是 List，如果有 Id 字段可改成字典）
            LiveConfig = ConfigSystem.GetConfig<Live>()[index];

            livedata_ = PreDownloadManager.GetLiveDataByIndex(LiveConfig, index);

            ui.btn_close.SetClick(() => { CtrlCloseUI(); });


            if (livedata_.progress >= 100)
                HandlePvPlay();
            else
            {
                setCover();
            }
            var btn_down_coin = ui.btn_download_coin;
            var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload;
            btn_down_coin.title = downloadCoinNum.ToString();
            HallManager.Instance.UpdateSecondEvent += Updata;

            btn_down_coin.SetClick(() =>
            {

                if (GameHelper.Get101() >= downloadCoinNum)
                {
                    DataMgr.Coin.Value -= downloadCoinNum;
                    GameDispatcher.Instance.Dispatch(GameMsg.Update101);
                    TextureHelper.SaveVideoToAlbum(LiveConfig.Name);
                }
                else
                {
                    GameHelper.ShowTips("no_enough_gold", true);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open);
                }
            });
            ui.btn_download.SetClick(() =>
            {
                if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As<int>()))
                    TextureHelper.SaveVideoToAlbum(LiveConfig.Name);
                else
                    GameHelper.ShowVideoAd("DownloadLive", isSuccess =>
                    {
                        if (isSuccess) TextureHelper.SaveVideoToAlbum(LiveConfig.Name);
                    });
            });
            InitView();
        }

        private void setCover()
        {
            var coverLoader = ui.img_cover.GetChild("loader") as GLoader;
            if (coverLoader?.texture != null)
            {
                coverLoader.texture.Dispose();
                coverLoader.texture = null;
            }
            LiveVideoManager.Instance.GetVideoCover(coverLoader, LiveConfig.Name + "_cover", (tex) =>
            {
                if (tex != null && coverLoader != null && !coverLoader.isDisposed)
                {
                    coverLoader.texture = new NTexture(tex)
                    {
                        destroyMethod = DestroyMethod.Destroy
                    };
                    coverLoader.visible = true;   
                }
                else
                {
                    Debug.LogError("封面获取失败");
                }
            });
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        private void vipLevelChange(object o)
        {
            InitView();
        }

        private void liveVideoLoaded(object o)
        {
            HandlePvPlay();
            // InitView();
        }

        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.BuyVip, vipLevelChange);//VIP订阅后更新头像的vip图标
            GameDispatcher.Instance.AddListener(GameMsg.liveVideoLoaded, liveVideoLoaded);
        }

        protected override void RemoveListener()
        {
            HallManager.Instance.UpdateSecondEvent -= Updata;
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, vipLevelChange);//VIP订阅后更新头像的vip图标
            GameDispatcher.Instance.RemoveListener(GameMsg.liveVideoLoaded, liveVideoLoaded);
        }

        #endregion
    }
}