#if UMR
#endif

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

namespace Rokid.MRC
{
    public class UIConnectPanel : UIPanelBase
    {
        private Transform rootPanel;

        private Text txtTitle;
        private Text txtDeviceNameLabel;
        private Text txtDeviceName;
        private Text txtIPLabel;
        private Text txtIP;
        private Text txtStatusLabel;
        private Text txtStatusDisconnect;
        private Transform rootStatusConnect;
        private Text txtStatusConnect;
        private Text txtButtonDisconnect;

        private Text txtDesc;

        private Button btnNetwork;
        private Text txtButtonNetwork;
        private Image imgWifi;
        private Text txtWifiName;
        private Text txtWifiLabel;

        //播放
        private VideoPlayer videoPlayer;
        private Image imgPlay;
        private Button btnPlayBg;

        public override void OnInit()
        {
            base.OnInit();

            rootPanel = transform.Find("Root");

            //标题
            txtTitle = transform.Find("Root/TxtTittle").gameObject.GetComponent<Text>();

            //设备名称
            txtDeviceNameLabel = transform.Find("Root/InfoView/DeviceInfo/TxtNameLabel").GetComponent<Text>();
            txtDeviceName = transform.Find("Root/InfoView/DeviceInfo/TxtNameLabel/TxtName").GetComponent<Text>();

            //IP
            txtIPLabel = transform.Find("Root/InfoView/IPInfo/TxtIPLabel").GetComponent<Text>();
            txtIP = transform.Find("Root/InfoView/IPInfo/TxtIPLabel/TxtIP").GetComponent<Text>();

            //设备状态
            txtStatusLabel = transform.Find("Root/InfoView/SatusInfo/TxtStatusLabel").GetComponent<Text>();
            txtStatusDisconnect = transform.Find("Root/InfoView/SatusInfo/TxtDisconnect").GetComponent<Text>();
            rootStatusConnect = transform.Find("Root/InfoView/SatusInfo/Connected");
            txtStatusConnect = rootStatusConnect.Find("TxtStatus").GetComponent<Text>();
            txtButtonDisconnect = rootStatusConnect.Find("BtnStatus/Text").GetComponent<Text>();
            Button btnDisconnect = rootStatusConnect.Find("BtnStatus").GetComponent<Button>();
            btnDisconnect.onClick.AddListener(() =>
            {
            //断开按钮
            PlayerManager.Instance.CloseAllClient();
            });
            btnDisconnect.gameObject.SetActive(false);
            txtDesc = transform.Find("Root/InfoView/TxtDesc").GetComponent<Text>();

            //打开
            Button btnOpen = transform.Find("BtnOpen").GetComponent<Button>();
            btnOpen.onClick.AddListener(() =>
            {
                rootPanel.gameObject.SetActive(!rootPanel.gameObject.activeInHierarchy);
                if(rootPanel.gameObject.activeInHierarchy)
                {
                    OnRefreshPanel(null);
                }
            });

            //设置网络
            btnNetwork = transform.Find("Root/InfoView/NetworkView/BtnNetwork").GetComponent<Button>();
            btnNetwork.onClick.AddListener(() =>
            {
                SDKManager.Instance.OpenWifiSetting();
            });
            Button btnWifi = transform.Find("Root/InfoView/NetworkView").GetComponent<Button>();
            btnWifi.onClick.AddListener(() =>
            {
                //刷新Wifi
                RefreshWifiStatus();
            });
            txtButtonNetwork = btnNetwork.transform.Find("Text").GetComponent<Text>();
            imgWifi = transform.Find("Root/InfoView/NetworkView/ImgWifi").GetComponent<Image>();
            txtWifiName = transform.Find("Root/InfoView/NetworkView/TxtWifiName").GetComponent<Text>();
            txtWifiLabel = transform.Find("Root/InfoView/NetworkView/TxtWifiLabel").GetComponent<Text>();

            //播放
            Transform displayView = transform.Find("Root/DisplayView");
            videoPlayer = displayView.GetComponent<VideoPlayer>();
            videoPlayer.loopPointReached += (source) =>
            {
                //视频播放结束
                imgPlay.gameObject.SetActive(true);
            };
            btnPlayBg = displayView.Find("BtnPlayBg").GetComponent<Button>();
            btnPlayBg.onClick.AddListener(() =>
            {
                if(videoPlayer.isPlaying)
                {
                    videoPlayer.Pause();
                    imgPlay.gameObject.SetActive(true);
                }
                else if(videoPlayer.isPaused)
                {
                    videoPlayer.Play();
                    imgPlay.gameObject.SetActive(false);
                }
            });
            imgPlay = displayView.Find("BtnPlayBg/ImgPlay").GetComponent<Image>();
            imgPlay.gameObject.SetActive(!videoPlayer.playOnAwake);

            //语言表
            txtTitle.text = LocalizationMgr.Instance.GetTextByKey("PanelTitle");
            txtDeviceNameLabel.text = LocalizationMgr.Instance.GetTextByKey("DeviceNameLabel");
            txtIPLabel.text = LocalizationMgr.Instance.GetTextByKey("IpLabel");
            txtStatusLabel.text = LocalizationMgr.Instance.GetTextByKey("StatusLabel");
            txtStatusDisconnect.text = LocalizationMgr.Instance.GetTextByKey("Disconnected");
            txtStatusConnect.text = LocalizationMgr.Instance.GetTextByKey("Connected");
            txtButtonDisconnect.text = LocalizationMgr.Instance.GetTextByKey("BtnDisconnect");
            txtDesc.text = LocalizationMgr.Instance.GetTextByKey("Description");
            txtButtonNetwork.text = LocalizationMgr.Instance.GetTextByKey("ButtonNetwork");

            txtWifiLabel.text = LocalizationMgr.Instance.GetTextByKey("WifiLabel");

            //注册网络事件
            MessageCenter.AddMsgListener(EventDefine.ServerConnectionEvent, HandleServerEvent);
            MessageCenter.AddMsgListener(GlobalDefine.RefreshConnectPanel, OnRefreshPanel);

            InitAnchorPanel();
        }

        public override void OnOpen()
        {
            base.OnOpen();

            //刷新IP
            RefreshIP();

            //设备状态
            RefreshDeviceStatus();

            //Wifi
            RefreshWifiStatus();
        }

        public override void OnClose()
        {
            base.OnClose();

            //移除事件
            MessageCenter.RemoveMsgListener(EventDefine.ServerConnectionEvent, HandleServerEvent);
            MessageCenter.RemoveMsgListener(GlobalDefine.RefreshConnectPanel, OnRefreshPanel);
        }

        private void OnRefreshPanel(object val)
        {
            //刷新IP
            RefreshIP();
            //设备状态
            RefreshDeviceStatus();
            //Wifi
            RefreshWifiStatus();
        }

        private void HandleServerEvent(object val)
        {
            ConnectionEventMessage msg = (ConnectionEventMessage)val;

            if(msg.ConnectStatus == ConnectStatus.Success)
            {
                rootPanel.gameObject.SetActive(false);
            }
            else if(msg.ConnectStatus == ConnectStatus.GenericDisconnect)
            {
                //某个客户端断开
                rootPanel.gameObject.SetActive(true);
            }

            RefreshDeviceStatus();
        }

        private void RefreshIP()
        {
            //IP
            string ip = MRCUtility.GetWirelessIP(AddressType.IPv4);
            if(string.IsNullOrEmpty(ip))
            {
                ip = LocalizationMgr.Instance.GetTextByKey("IpDesc");
            }
            txtIP.text = ip;
        }

        //刷新设备状态
        private void RefreshDeviceStatus()
        {
            //设备名称
            txtDeviceName.text = SystemInfo.deviceName;

            PlayerData? playerData = PlayerManager.Instance.GetConnectedPlayerData();
            bool haveConnectedClient = playerData == null ? false : true;
            rootStatusConnect.gameObject.SetActive(haveConnectedClient);
            txtStatusDisconnect.gameObject.SetActive(!haveConnectedClient);
        }

        //刷新Wifi状态
        private void RefreshWifiStatus()
        {
            if(Application.internetReachability == NetworkReachability.NotReachable)
            {
                imgWifi.color = Color.gray;
                txtWifiName.color = Color.gray;
                txtWifiName.text = LocalizationMgr.Instance.GetTextByKey("NoWifi");
            }
            else
            {
                string wifiName = SDKManager.Instance.GetCurConnectedWifiName();
                if(string.IsNullOrEmpty(wifiName))
                {
                    imgWifi.color = Color.gray;
                    txtWifiName.color = Color.gray;
                    txtWifiName.text = LocalizationMgr.Instance.GetTextByKey("NoWifi");
                }
                else
                {
                    imgWifi.color = Color.white;
                    txtWifiName.color = Color.white;
                    txtWifiName.text = wifiName;
                }
            }
        }

        //锚点界面
        private Transform clientAnchor;
        private GameObject anchorViewPort;
        private Text txtAnchorDesc;
        private RectTransform anchorItemParent;
        private GameObject anchorItemPrefab;
        //锚点UI集合
        private List<GameObject> anchorItemList = new List<GameObject>();

        public void InitAnchorPanel()
        {
            InitAnchor();
            InitComposite();
        }

        private void InitAnchor()
        {
            clientAnchor = transform.Find("ClientAnchor");
            clientAnchor.gameObject.SetActive(MRCDriver.Instance.ShowAnchorUI);

            if(!MRCDriver.Instance.ShowAnchorUI)
            {
                return;
            }

            anchorViewPort = transform.Find("ClientAnchor/ScrollView/Viewport").gameObject;
            txtAnchorDesc = transform.Find("ClientAnchor/TxtDesc").GetComponent<Text>();

            anchorItemParent = transform.Find("ClientAnchor/ScrollView/Viewport/Content").GetComponent<RectTransform>();

            anchorItemPrefab = transform.Find("ClientAnchor/ScrollView/Viewport/Content/Anchor").gameObject;
            anchorItemPrefab.SetActive(false);

            //注册网络事件
            MessageCenter.AddMsgListener(EventDefine.ServerConnectionEvent, UpdateAnchorPanel);
            MessageCenter.AddMsgListener(GlobalDefine.ClientAnchorInstantiate, UpdateAnchorPanel);

            UpdateAnchorItem();
        }


        private void UpdateAnchorPanel(object val)
        {
            if(val == null)
            {
                //生成Anchor事件
                UpdateAnchorItem();
                return;
            }

            ConnectionEventMessage msg = (ConnectionEventMessage)val;
            if(msg.ConnectStatus == ConnectStatus.Success || msg.ConnectStatus == ConnectStatus.GenericDisconnect)
            {
                UpdateAnchorItem();
            }
        }

        public void CheckAnchorList()
        {
            if(PlayerManager.Instance.HavePlayer())
            {
                anchorViewPort.SetActive(true);
                txtAnchorDesc.gameObject.SetActive(false);
            }
            else
            {
                anchorViewPort.SetActive(false);
                txtAnchorDesc.gameObject.SetActive(true);
            }
        }

        //显示每个客户端锚点UI
        public void UpdateAnchorItem()
        {
            CheckAnchorList();

            //删除所有UI的Item
            DeleteCachedItem();

            //生成新UI
            foreach(var player in PlayerManager.Instance.PlayerDataDic)
            {
                //Debug.Log($"Name : {player.Value.PlayerName} ClientID : {player.Value.ClientId}");
                if(player.Value.ClientId != 0)
                {
                    AddAnchorItem(player.Value);
                }
            }

            //重新刷新
            LayoutRebuilder.ForceRebuildLayoutImmediate(anchorItemParent);
        }

        public void AddAnchorItem(PlayerData playerData)
        {
            GameObject objItem = Instantiate(anchorItemPrefab, anchorItemParent);
            anchorItemList.Add(objItem);
            objItem.SetActive(true);

            Image bg = objItem.GetComponent<Image>();
            Text TxtName = objItem.transform.Find("TxtName").GetComponent<Text>();
            Toggle tog = objItem.transform.Find("Toggle").GetComponent<Toggle>();

            //背景颜色
            if(playerData.Anchor != null && playerData.Anchor.activeInHierarchy)
            {
                //有生成Anchor
                bg.color = playerData.IsVideoClient ? Color.cyan : Color.green;
                tog.isOn = true;
            }
            else
            {
                bg.color = playerData.IsVideoClient ? Color.cyan : Color.red;
                tog.isOn = false;
            }

            //添加开关，显示或隐藏Anchor
            tog.onValueChanged.AddListener((isOn) =>
            {
                ResourceManager.Instance.CreateClientAnchor(playerData);
                playerData.Anchor.SetActive(isOn);
                bg.color = playerData.IsVideoClient ? Color.cyan : (isOn ? Color.green : Color.red);
            });

            //客户端名称
            //TxtName.text = playerData.PlayerName;

            TxtName.text = playerData.PlayerName + " IP : " + playerData.ClientIP;

            //Button btnConnect = objItem.transform.Find("BtnConnect").GetComponent<Button>();
            //btnConnect.onClick.AddListener(() =>
            //{
            //});
        }

        public void DeleteCachedItem()
        {
            foreach(GameObject anchorItem in anchorItemList)
            {
                if(anchorItem != null)
                {
                    Destroy(anchorItem);
                }
            }

            anchorItemList.Clear();
        }

        //RT渲染画面显示
        private Transform compositeRoot;
        private RawImage imgCompositeCamColorRT;

        private void InitComposite()
        {
            imgCompositeCamColorRT = transform.Find("Composite/ImgColorRT").GetComponent<RawImage>();

            compositeRoot = transform.Find("Composite");
            compositeRoot.gameObject.SetActive(MRCDriver.Instance.ShowCompositeUI);
            imgCompositeCamColorRT.gameObject.SetActive(MRCDriver.Instance.ShowCompositeUI);

            if(MRCDriver.Instance.ShowCompositeUI)
            {
                MessageCenter.AddMsgListener(GlobalDefine.CameraParamFinished, SetRenderTextureImage);
            }
        }

        public void SetRenderTextureImage(object val)
        {
            RenderTexture renderRT = (RenderTexture)val;

            //设置显示纹理
            imgCompositeCamColorRT.texture = renderRT;

            //设置Image大小
            RectTransform colorRectTransform = imgCompositeCamColorRT.GetComponent<RectTransform>();
            //colorRectTransform.rect.Set(colorRectTransform.rect.x, colorRectTransform.rect.y, renderRT.width, renderRT.height);
            SetSize(colorRectTransform, new Vector2(renderRT.width, renderRT.height));
        }

        public void SetSize(RectTransform rectTrans, Vector2 newSize)
        {
            Vector2 oldSize = rectTrans.rect.size;
            Vector2 offset = newSize - oldSize;
            rectTrans.sizeDelta += offset;
        }

    }
}