using ESBasic;
using OMCS;
using OMCS.Contracts;
using OMCS.Passive;
using OMCS.Passive.Audio;
using OMCS.Passive.MultiChat;
using OVCS.ClientWpf.Tools;
using OVCS.Core;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace OVCS.ClientWpf
{
    /// <summary>
    /// 多人视频语音聊天、电子白板、共享远程桌面控件容器。
    /// </summary>
    public partial class MultiVideoChatContainer : System.Windows.Controls.UserControl
    { 
        private IMultimediaManager multimediaManager;//OMCS 多媒体管理器
        private IChatGroup chatGroup;// 视频聊天组
        #region 共享桌面的其他人Id
        public string ShareDeskId
        {
            get { return groupExtension?.DesktopSharedUserID; }
        }
        #endregion        
        private bool isMyselfVideo = true;// 是否开启摄像头     
        private bool isMyselfMic = false;// 是否开启麦克风
        private bool isMyselfSpeak = true;//是否开启扬声器
        private bool isMyselfDesktop = false;//是否开启共享桌面
        private bool isWhiteBoard = false;  //是否开启电子白板（主持人）
        public VideoPanel myselfPanel = new VideoPanel();//当前登录的账号的视频小窗口视图
        public VideoHidePanel myselfHidePanel = new VideoHidePanel();//当前登录的账号的视频小窗口视图
        private string loginId;//当前登录者Id
        private string groupId;//当前房间号
        private bool isWhiteBoardWatching = false;//当前是否正在观看白板
        private bool isDeskTopWatching = false;//当前是否正在观看远程桌面
        private GroupExtension groupExtension;
        private int videoShowCount = 0;//视频正常显示并且连接成功的用户数量
        private bool isVideoShowBeyond = false; //是否超过限定的视频个数
        public MultiVideoChatContainer()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 关闭窗口时触发
        /// </summary>
        public void Close()
        {
            if (this.multimediaManager != null)
            {
                this.multimediaManager.ChatGroupEntrance.Exit(ChatType.Video, this.chatGroup.GroupID);
            }
            if (videoRecorder != null && videoRecorder.IsRecording)
            {
                videoRecorder.StopRecord();
            }
            this.multimediaManager.Dispose(); 
        }
        public void Initialize(IMultimediaManager _multimediaManager,string chatGroupID , GroupExtension _groupExtension)
        {
            this.cameraViewbox.videoPanelSizeChange += CameraViewbox_videoPanelSizeChange;
            this.groupId = chatGroupID;
            this.groupExtension = _groupExtension;
            this.multimediaManager = _multimediaManager;
            this.loginId = this.multimediaManager.CurrentUserID; 
            this.skinLabel_userID.Content = this.groupExtension.ModeratorID;
            this.myselfId.Text = _multimediaManager.CurrentUserID.ToString();

            this.multimediaManager.SpeakerVoiceNotified += new CbGeneric<List<UserDecibel>> (MultimediaManager_SpeakerVoiceNotified);


            //渲染当前登录（自己）的视频窗口   
            
            IChatUnit myChatUnit = this.multimediaManager.ChatGroupEntrance.CreateChatUnit(this.loginId);
            this.myselfPanel.Initialize(myChatUnit, true);
            this.myselfHidePanel.Initialize(true, myChatUnit,true);
            this.cameraViewbox.FlowLayoutPanel.Children.Insert(0, this.myselfPanel);
            
            this.myselfPanel.ChangeState += Panel_ChangeState;
            this.myselfPanel.CameraStateChange += Panel_CameraStateChange;
            this.myselfPanel.VideoByCount += Panel_VideoByCount;
            this.myselfPanel.VideoConnect += Panel_VideoConnect;
            VideoAllPanel videoAllMyselfPanel;
            videoAllMyselfPanel.videoPanel = this.myselfPanel;
            videoAllMyselfPanel.videoHidePanel = this.myselfHidePanel;
            myChatUnit.Tag = videoAllMyselfPanel;
            this.myselfPanel.ShowMicState(this.loginId, this.loginId == this.groupExtension.ModeratorID);

            //加入视频聊天组
            this.chatGroup = this.multimediaManager.ChatGroupEntrance.Join(ChatType.Video, chatGroupID);
            this.chatGroup.MyChatUnit = myChatUnit;
            this.chatGroup.SomeoneJoin += new CbGeneric<IChatUnit>(chatGroup_SomeoneJoin);
            this.chatGroup.SomeoneExit += new CbGeneric<string>(chatGroup_SomeoneExit);
            this.TotalNumChange(this.chatGroup.GetOtherMembers().Count + 1);
            //渲染连接其他人的摄像头麦克风
            foreach (IChatUnit unit in this.chatGroup.GetOtherMembers())
            {
                VideoPanel panel = new VideoPanel();
                panel.Initialize(unit, false);
                VideoHidePanel videoHidePanel = new VideoHidePanel();
                videoHidePanel.Initialize(true, unit,false);
                VideoAllPanel videoAllPanel;
                videoAllPanel.videoPanel = panel;
                videoAllPanel.videoHidePanel = videoHidePanel;
                if(this.cameraViewbox.FlowLayoutPanel.Children.Count >= 9)
                {
                    this.flowLayoutPanel2.Children.Insert(0, videoHidePanel);
                }
                else
                {
                    this.cameraViewbox.FlowLayoutPanel.Children.Insert(this.videoShowCount, panel);
                }
                
                panel.ChangeState += Panel_ChangeState;
                panel.CameraStateChange += Panel_CameraStateChange;
                panel.VideoByCount += Panel_VideoByCount;
                panel.VideoConnect += Panel_VideoConnect;
                unit.Tag = videoAllPanel;
                
            }
            
            #region 判断主持人是否为当前登录的账号 并默认打开摄像头麦克风设备
            //主持人默认打开摄像头和麦克风
            if (this.groupExtension.ModeratorID != null)
            {
                if (this.groupExtension.ModeratorID == this.multimediaManager.CurrentUserID)
                {
                    this.skinCheckBox_whilebord.Visibility = Visibility.Visible;
                    this.multimediaManager.OutputAudio = true;
                    this.isMyselfVideo = true;
                    this.isMyselfMic = true;
                    this.skinCheckBox_camera.Source = ResourceManager.Singleton.CameraOpenImage;
                    this.skinCheckBox_mic.Source = ResourceManager.Singleton.MicOpenImage;
                    this.skinCheckBox_mic.ToolTip = "麦克风：开";
                    ((VideoAllPanel)this.chatGroup.GetMember(this.loginId).Tag).videoPanel.pictureBox_Mic.Source = ResourceManager.Singleton.MicEnableImage;
                }
                else
                {
                    ((VideoAllPanel)this.chatGroup.GetMember(this.loginId).Tag).videoPanel.pictureBox_Mic.Source = ResourceManager.Singleton.MicDisableImage;
                }
                if (this.chatGroup.GetMember(this.groupExtension.ModeratorID) == null)
                { 
                    return;
                }
            }

            #endregion

            // 判断是否当前会议时内是否有用户开启远程桌面，若有则连接该用户的远程桌面。
            if (_groupExtension.DesktopSharedUserID != null)
            {
                this.OpenRemotingDesktop(groupExtension.DesktopSharedUserID);
                this.deskTopFullScreen.Visibility = Visibility.Visible;
                this.deskTopFullScreen.ToolTip = string.Format("打开{0}的共享桌面", this.groupExtension.DesktopSharedUserID);
                this.Panel_ChangeState(this.groupExtension.DesktopSharedUserID, "开启远程桌面");
            }
            // 判断是否当前会议时内主持人是否开启电子白板，若有则连接到电子白板。
            if (_groupExtension.IsModeratorWhiteBoardNow)
            {
                this.OpenRemotingWhiteBoard(this.groupId);
            }
            if (this.myselfPanel.DynamicCameraConnector.Connected)
            {
                this.topNav.IsHitTestVisible = true;
            }
            this.VideoSizeChange(new System.Windows.Size(this.cameraViewbox.FlowLayoutPanel.Width, this.cameraViewbox.FlowLayoutPanel.Height));
            this.VideoNumBeyond();
            if (this.isVideoShowBeyond)
            {
                this.cameraViewbox.FlowLayoutPanel.Children.Remove(this.myselfPanel);
                this.flowLayoutPanel2.Children.Insert(0, this.myselfHidePanel);
                this.myselfHidePanel.cameraVisibilityChange(true);
            }
        }

        private void Panel_VideoConnect(IChatUnit chatUnit)
        {
            if (!chatUnit.DynamicCameraConnector.OwnerOutput)
            {
                this.cameraViewbox.FlowLayoutPanel.Children.Remove(((VideoAllPanel)chatUnit.Tag).videoPanel);
                this.flowLayoutPanel2.Children.Insert(0, ((VideoAllPanel)chatUnit.Tag).videoHidePanel);
                this.myselfHidePanel.cameraVisibilityChange(false);
                this.VideoSizeChange(new System.Windows.Size(this.cameraViewbox.FlowLayoutPanel.Width, this.cameraViewbox.FlowLayoutPanel.Height));
            }
        }

        // 窗口尺寸修改时触发
        private void CameraViewbox_videoPanelSizeChange(System.Windows.Size size)
        {
            this.VideoSizeChange(size);
        }

        //计算会议中开启视频的人数
        private void Panel_VideoByCount(int count,IChatUnit chatUnit)
        {
            if(count<0 && this.videoShowCount == 0)
            {
                return;
            }
            
            this.videoShowCount += count;
        }

        //计算视频控件的宽高
        private void VideoSizeChange(System.Windows.Size size)
        {
            if (this.cameraViewbox.FlowLayoutPanel.Children.Count > 4)
            {
                foreach (VideoPanel panel in this.cameraViewbox.FlowLayoutPanel.Children)
                {
                    //2,0,2,2
                    panel.Height = (size.Height - 6) / 3;
                    panel.Width = (size.Width - 12) / 3;
                }
            }
            else if (this.cameraViewbox.FlowLayoutPanel.Children.Count <= 4 && this.cameraViewbox.FlowLayoutPanel.Children.Count > 1)
            {
                foreach (VideoPanel panel in this.cameraViewbox.FlowLayoutPanel.Children)
                {
                    panel.Height = (size.Height - 4) / 2;
                    panel.Width = (size.Width - 8) / 2;
                }
            }
            else if (this.cameraViewbox.FlowLayoutPanel.Children.Count == 1)
            {
                foreach (VideoPanel panel in this.cameraViewbox.FlowLayoutPanel.Children)
                {
                    panel.Height = size.Height - 2;
                    panel.Width = size.Width - 4;
                }
            }
        }

        /// <summary>
        /// 视频显示人数是否超过9个
        /// </summary>
        private void VideoNumBeyond()
        {
            this.isVideoShowBeyond = this.cameraViewbox.FlowLayoutPanel.Children.Count > 9 ? true : false;
        }

        private void TotalNumChange(int num)
        {
            this.skinLabel_totalNum.Content = num.ToString();
        }

        /// <summary>
        /// 获取当前所有说话者声音的分贝值 200ms触发一次
        /// </summary>
        /// <param name="decibels">用户分贝列表</param>
        private void MultimediaManager_SpeakerVoiceNotified(List<UserDecibel> decibels)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<List<UserDecibel>>(MultimediaManager_SpeakerVoiceNotified), decibels);
            }
            else
            {
                ((VideoAllPanel)this.chatGroup.GetMember(this.loginId).Tag).videoPanel.SpeakerDecibelChange(null);
                ((VideoAllPanel)this.chatGroup.GetMember(this.loginId).Tag).videoHidePanel.SpeakerDecibelDownChange(null);
                foreach (IChatUnit unit in this.chatGroup.GetOtherMembers())
                {
                    if (unit.Tag != null)
                    {
                        ((VideoAllPanel)unit.Tag).videoPanel.SpeakerDecibelChange(null);
                        ((VideoAllPanel)unit.Tag).videoHidePanel.SpeakerDecibelDownChange(null);
                    }
                }
                foreach (UserDecibel userdecibel in decibels)
                {
                    if(this.chatGroup.GetMember(userdecibel.UserID) != null)
                    {
                        VideoPanel panel = ((VideoAllPanel)this.chatGroup.GetMember(userdecibel.UserID).Tag).videoPanel;
                        VideoHidePanel panelhide = ((VideoAllPanel)this.chatGroup.GetMember(userdecibel.UserID).Tag).videoHidePanel;
                        panel.SpeakerDecibelChange(userdecibel);
                        panelhide.SpeakerDecibelDownChange(userdecibel);
                    }
                }
            }
        }

        /// <summary>
        /// 用户摄像头状态改变时触发
        /// </summary>
        /// <param name="isOpenCamera">是否显示</param>
        /// <param name="unit">用户</param>
        private void Panel_CameraStateChange(bool isOpenCamera, IChatUnit unit)
        {
            if (unit.MemberID == this.loginId)
            {
                return;
            }
            this.VideoNumBeyond();//9个以上
            if (this.isVideoShowBeyond)
            {
                ((VideoAllPanel)unit.Tag).videoHidePanel.cameraVisibilityChange(isOpenCamera);
                return;
            }
            if (isOpenCamera)
            {   
                this.flowLayoutPanel2.Children.Remove(((VideoAllPanel)unit.Tag).videoHidePanel);
                this.cameraViewbox.FlowLayoutPanel.Children.Insert(this.videoShowCount, ((VideoAllPanel)unit.Tag).videoPanel);
            }
            else
            {
                this.cameraViewbox.FlowLayoutPanel.Children.Remove(((VideoAllPanel)unit.Tag).videoPanel);
                ((VideoAllPanel)unit.Tag).videoPanel.cameraPanel1.ClearImage();
                this.flowLayoutPanel2.Children.Insert(0, ((VideoAllPanel)unit.Tag).videoHidePanel);
                ((VideoAllPanel)unit.Tag).videoHidePanel.cameraVisibilityChange(false);
            }
            this.VideoSizeChange(new System.Windows.Size(this.cameraViewbox.FlowLayoutPanel.Width, this.cameraViewbox.FlowLayoutPanel.Height));
        }
        
        /// <summary>
        /// 用户状态改变时
        /// </summary>
        /// <param name="ownerID">账号</param>
        /// <param name="stateInformation">状态信息</param>
        private void Panel_ChangeState(string ownerID, string stateInformation)
        {
            this.userDeviceState.Text = ownerID + stateInformation;
        }

        #region 视频聊天会议组

        //某人退出chatGroup视频会议
        void chatGroup_SomeoneExit(string memberID)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<string>(this.chatGroup_SomeoneExit), memberID);
            }
            else
            {
                VideoPanel target = null;
                VideoHidePanel targethide = null;
                foreach (VideoPanel panel in this.cameraViewbox.FlowLayoutPanel.Children)
                {
                    if (panel.MemberID == memberID)
                    {
                        target = panel;
                        break;
                    }
                }
                if (target == null)
                {
                    foreach (VideoHidePanel panel in this.flowLayoutPanel2.Children)
                    {
                        if (panel.MemberID == memberID)
                        {
                            targethide = panel;
                            break;
                        }
                    }
                }
                if (target == null && targethide == null)
                {
                    return;
                }
                this.TotalNumChange(this.chatGroup.GetOtherMembers().Count + 1);
                if ( memberID == this.groupExtension.DesktopSharedUserID)
                {
                    string id = this.chatGroup.GetMember(this.groupExtension.ModeratorID) == null ? this.groupExtension.ModeratorID : this.loginId;
                    this.CloseRemotingDesktop();
                }
                if(memberID == this.groupExtension.ModeratorID && this.groupExtension.IsModeratorWhiteBoardNow)
                {
                    this.CloseRemotingWhiteBoard();
                }
                if (target!=null)
                {
                    target.DynamicCameraConnector.Disconnect();
                }

                if (target == null)
                {
                    this.flowLayoutPanel2.Children.Remove(targethide);
                }
                else if (targethide == null)
                {
                    this.cameraViewbox.FlowLayoutPanel.Children.Remove(target);
                }
                this.VideoSizeChange(new System.Windows.Size(this.cameraViewbox.FlowLayoutPanel.Width, this.cameraViewbox.FlowLayoutPanel.Height));
                this.VideoNumBeyond();
            }
        }
        //某人加入chatGroup视频会议
        void chatGroup_SomeoneJoin(IChatUnit unit)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<IChatUnit>(this.chatGroup_SomeoneJoin), unit);
            }
            else
            {
                VideoPanel panel = new VideoPanel();
                panel.Initialize(unit, false);
                VideoHidePanel videoHidePanel = new VideoHidePanel();
                videoHidePanel.Initialize(false, unit,false);
                VideoAllPanel videoAllPanel;
                videoAllPanel.videoPanel = panel;
                videoAllPanel.videoHidePanel = videoHidePanel;
                if (panel.CameraConnectResult != ConnectResult.Succeed)
                {
                    this.flowLayoutPanel2.Children.Insert(0, videoHidePanel);
                    videoHidePanel.cameraVisibilityChange(false);
                }
                else
                {
                    
                    if (this.isVideoShowBeyond)
                    {
                        this.flowLayoutPanel2.Children.Insert(0, videoHidePanel);
                        videoHidePanel.cameraVisibilityChange(true);
                    }
                    else
                    {
                        this.cameraViewbox.FlowLayoutPanel.Children.Insert(this.videoShowCount, panel);
                    }
                }
                this.TotalNumChange(this.chatGroup.GetOtherMembers().Count + 1);
                panel.ChangeState += Panel_ChangeState;
                panel.CameraStateChange += Panel_CameraStateChange;
                panel.VideoByCount += Panel_VideoByCount;
                panel.VideoConnect += Panel_VideoConnect;
                unit.Tag = videoAllPanel;
                this.VideoNumBeyond();
                this.VideoSizeChange(new System.Windows.Size(this.cameraViewbox.FlowLayoutPanel.Width, this.cameraViewbox.FlowLayoutPanel.Height));
            }
        }
        #endregion

        #region 设备开关
        //点击选择是否开启摄像头
        private void skinCheckBox_camera_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.isMyselfVideo = !this.isMyselfVideo;
            System.Windows.Controls.Image imageVideo = sender as System.Windows.Controls.Image;
            imageVideo.Source = this.isMyselfVideo ? ResourceManager.Singleton.CameraOpenImage : ResourceManager.Singleton.CameraCloseImage;
            imageVideo.ToolTip = this.isMyselfVideo ? "摄像头：开" : "摄像头：关";
            VideoPanel myPanel = ((VideoAllPanel)this.chatGroup.GetMember(this.loginId).Tag).videoPanel;
            VideoHidePanel myHidePanel = ((VideoAllPanel)this.chatGroup.GetMember(this.loginId).Tag).videoHidePanel;
            this.VideoNumBeyond();
            if (this.isVideoShowBeyond)
            {
                myHidePanel.cameraVisibilityChange(this.isMyselfVideo);
            }
            else
            {
                if (!isMyselfVideo)
                {
                    this.cameraViewbox.FlowLayoutPanel.Children.Remove(myPanel);
                    myPanel.cameraPanel1.ClearImage();
                    this.flowLayoutPanel2.Children.Insert(0, myHidePanel);
                    myHidePanel.cameraVisibilityChange(false);
                }
                else
                {
                    this.flowLayoutPanel2.Children.Remove(myHidePanel);
                    this.cameraViewbox.FlowLayoutPanel.Children.Insert(this.videoShowCount, myPanel);
                }
            }
            
            if (IsInitialized)
            {
                this.multimediaManager.OutputVideo = this.isMyselfVideo;
                this.VideoSizeChange(new System.Windows.Size(this.cameraViewbox.FlowLayoutPanel.Width, this.cameraViewbox.FlowLayoutPanel.Height));
            }
        }

        //点击选择是否开启麦克风
        private void skinCheckBox_mic_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.isMyselfMic = !this.isMyselfMic;
            System.Windows.Controls.Image imageMic = sender as System.Windows.Controls.Image;
            imageMic.Source = this.isMyselfMic ? ResourceManager.Singleton.MicOpenImage : ResourceManager.Singleton.MicCloseImage;
            imageMic.ToolTip = this.isMyselfMic ? "麦克风 ：开" : "麦克风：关";
            if (IsInitialized)
            {
                this.myselfPanel.ShowMicState(this.loginId, this.isMyselfMic);
                this.multimediaManager.OutputAudio = this.isMyselfMic;
            }
        }
        //点击选择是否静音
        private void skinCheckBox_speaker_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.isMyselfSpeak = !this.isMyselfSpeak;
            System.Windows.Controls.Image imageSpeak = sender as System.Windows.Controls.Image;
            imageSpeak.Source = this.isMyselfSpeak ? ResourceManager.Singleton.SpeakerOpenImage : ResourceManager.Singleton.SpeakerCloseImage;
            imageSpeak.ToolTip = this.isMyselfSpeak ? "扬声器：开" : "扬声器：关";
            if (IsInitialized)
            {
                this.multimediaManager.Mute = !this.isMyselfSpeak;
            }
        }

        //点击选择是否共享远程桌面
        private void skinCheckBox_desk_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.isMyselfDesktop = !this.isMyselfDesktop;
            System.Windows.Controls.Image imageDesktop = sender as System.Windows.Controls.Image;
            
            if (this.isMyselfDesktop)
            {
                if (this.groupExtension.DesktopSharedUserID != null)
                {
                    System.Windows.Forms.MessageBox.Show(string.Format("{0}正在共享桌面", this.groupExtension.DesktopSharedUserID), "ERROR");
                    this.isMyselfDesktop = !this.isMyselfDesktop;
                    return;
                };
                this.deskTop_myself.Visibility = Visibility.Visible;
                this.groupExtension.DesktopSharedUserID = this.loginId;
                this.multimediaManager.SendCustomizedMessage(App.ServerID, InformationTypes.BroadcastShareDesk, BitConverter.GetBytes(this.isMyselfDesktop), this.groupId);
            }
            else
            {
                if (this.isDeskTopWatching)
                {
                    this.VideoBtn.Background = new BrushConverter().ConvertFrom("#87CEFA") as System.Windows.Media.Brush;
                    this.cameraViewbox.Visibility = Visibility.Visible;
                    this.isDeskTopWatching = false;
                }
                this.multimediaManager.SendCustomizedMessage(App.ServerID, InformationTypes.BroadcastShareDesk, BitConverter.GetBytes(this.isMyselfDesktop), this.groupId);
                this.groupExtension.DesktopSharedUserID = null;
                this.deskTop_myself.Visibility = Visibility.Collapsed;
                if (bigDeskTopWindow != null )
                {
                    bigDeskTopWindow.Close();
                    bigDeskTopWindow = null;
                }
            }
            imageDesktop.Source = this.isMyselfDesktop ? ResourceManager.Singleton.DesktopOpenImage : ResourceManager.Singleton.DesktopCloseImage;
            imageDesktop.ToolTip = this.isMyselfDesktop ? "远程桌面共享：开" : "远程桌面共享：关";
        }

        /// <summary>
        /// 是否开启电子白板，主持人才有权限
        /// </summary>
        private void skinCheckBox_whilebord_MouseDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Controls.Image imageWhiteBoard = sender as System.Windows.Controls.Image;
            this.isWhiteBoard = !this.isWhiteBoard;
            imageWhiteBoard.Source = this.isWhiteBoard ? ResourceManager.Singleton.WhiteBoardOpenImage : ResourceManager.Singleton.WhiteBoardCloseImage;
            imageWhiteBoard.ToolTip = this.isWhiteBoard ? "电子白板（主持人才有权限）：开":"电子白板（主持人才有权限）：关";
            if (this.isWhiteBoard)
            {
                this.whiteBoardConnect(this.groupId);
                this.groupExtension.IsModeratorWhiteBoardNow = true;
                this.whiteBoardBtn.Visibility = Visibility.Visible;
                this.multimediaManager.SendCustomizedMessage(App.ServerID, InformationTypes.BroadcastWhiteBoard, BitConverter.GetBytes(this.isWhiteBoard), this.groupId);
            }
            else
            {
                this.whiteBoardBtn.Visibility = Visibility.Collapsed;
                this.whiteBoardConnecter.Disconnect();
                if (this.isWhiteBoardWatching)
                {
                    this.whiteBoardBtn.Background = new BrushConverter().ConvertFrom("#D5D5D5") as System.Windows.Media.Brush;
                    this.whiteBoardConnecter.Visibility = Visibility.Hidden;
                    this.VideoBtn.Background = new BrushConverter().ConvertFrom("#87CEFA") as System.Windows.Media.Brush;
                    this.cameraViewbox.Visibility = Visibility.Visible;
                    this.isWhiteBoardWatching = false;
                }
                this.multimediaManager.SendCustomizedMessage(App.ServerID, InformationTypes.BroadcastWhiteBoard, BitConverter.GetBytes(this.isWhiteBoard), this.groupId);
                this.groupExtension.IsModeratorWhiteBoardNow = false;
            }
        }
        #endregion

        #region 远程桌面连接器
        //远程桌面连接器
        BigDeskTopWindow bigDeskTopWindow;
        public void desktopConnect(string desktopId)
        {
            bigDeskTopWindow = new BigDeskTopWindow(desktopId, this);
            bigDeskTopWindow.Show();
            this.DeskTopBtnHitTestVisibleChange(false);
        }
        public void DeskTopBtnHitTestVisibleChange(bool isHitTestVisible)
        {
            this.deskTopFullScreen.IsHitTestVisible = isHitTestVisible;
        }
        #endregion

        #region 电子白板连接器
        public void whiteBoardConnect(string whiteBoardId)
        {
            this.whiteBoardConnecter.ConnectEnded += new CbGeneric<string, ConnectResult>(WhiteBoardConnecter_ConnectEnded);
            this.whiteBoardConnecter.Disconnected += new CbGeneric<string, ConnectorDisconnectedType>(WhiteBoardConnecter_Disconnected);
            if (!this.whiteBoardConnecter.Connected)
            {
                this.whiteBoardConnecter.BeginConnect(whiteBoardId);
            }
        }

        #region 电子白板连接结果、电子白板断开连接
        private void WhiteBoardConnecter_Disconnected(string boardId, ConnectorDisconnectedType type)
        {
            
        }

        private void WhiteBoardConnecter_ConnectEnded(string boardId, ConnectResult res)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<string, ConnectResult>(this.WhiteBoardConnecter_ConnectEnded), boardId, res);
            }
            else
            {
                if (res != ConnectResult.Succeed)
                {
                    System.Windows.MessageBox.Show("电子白板连接失败！" + res.ToString());
                }
            }
        }
        #endregion
        #endregion

        #region 弹出远程桌面
        private void deskTopFullScreen_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (this.groupExtension.DesktopSharedUserID != null || this.isMyselfDesktop)
            {
                this.desktopConnect(this.groupExtension.DesktopSharedUserID);
            }  
        }
        #endregion

        #region 录制功能 2022-12-07
        private VideoRecorder videoRecorder = new VideoRecorder();
        /// <summary>
        /// 点击开始录制或结束录制
        /// </summary>
        private void skinCheckBox_record_MouseDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Controls.Image image = (System.Windows.Controls.Image)sender;
            videoRecorder.Initialize(this.multimediaManager);
            if (!videoRecorder.IsRecording)
            {
                videoRecorder.RecordTimeChanged += new CbGeneric<TimeSpan>(RecordingVideo_RecordTimeChange);
                this.record_time.Visibility = Visibility.Visible;
                videoRecorder.RecordInit();
                image.Source = ResourceManager.Singleton.RecordStopImage;
                image.ToolTip = "结束录制";
                this.DeskTopBtnHitTestVisibleChange(false);
            }
            else
            {
                videoRecorder.RecordInit();
                image.Source = ResourceManager.Singleton.RecordStartImage;
                image.ToolTip = "录制视频";
                this.DeskTopBtnHitTestVisibleChange(true);
                this.record_time.Content = "00:00:00";
                this.record_time.Visibility = Visibility.Collapsed;
                System.Windows.Forms.MessageBox.Show("录制完成！");
            }
        }

        private void RecordingVideo_RecordTimeChange(TimeSpan timeSpan)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<TimeSpan>(this.RecordingVideo_RecordTimeChange), timeSpan);
            }
            else
            {
                this.record_time.Content = videoRecorder.RecordTime(timeSpan);
            }
        }

        #endregion

        #region 远程桌面和白板
        
        /// <summary>
        /// 收到其他人开启共享远程桌面 渲染 
        /// </summary>
        /// <param name="broadcasterID">当前共享桌面的用户Id</param>
        public void OpenRemotingDesktop(string broadcasterID)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<string>(this.OpenRemotingDesktop), broadcasterID);
            }
            else
            {
                this.desktopConnect(broadcasterID);
                this.deskTopFullScreen.Visibility = Visibility.Visible;
                this.groupExtension.DesktopSharedUserID = broadcasterID;
                this.deskTopFullScreen.ToolTip = string.Format("打开{0}的共享桌面", this.groupExtension.DesktopSharedUserID);
                this.Panel_ChangeState(broadcasterID, "开启远程桌面");
            }
        }

        /// <summary>
        /// 收到其他人关闭共享远程桌面 渲染 
        /// </summary>
        public void CloseRemotingDesktop()
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric(this.CloseRemotingDesktop));
            }
            else
            {
                if (this.isDeskTopWatching)
                {
                    this.VideoBtn.Background = new BrushConverter().ConvertFrom("#87CEFA") as System.Windows.Media.Brush;
                    this.cameraViewbox.Visibility = Visibility.Visible;
                    this.isDeskTopWatching = false;
                }
                this.deskTopFullScreen.Visibility = Visibility.Hidden;
                this.deskTopFullScreen.ToolTip = "";
                IChatUnit deskUnit = this.chatGroup.GetMember(this.groupExtension.ModeratorID) ?? this.chatGroup.GetMember(this.loginId);
                VideoPanel deskPanel = ((VideoAllPanel)deskUnit.Tag).videoPanel;
                this.Panel_ChangeState(this.groupExtension.DesktopSharedUserID, "关闭远程桌面");
                this.groupExtension.DesktopSharedUserID = null;
                if (bigDeskTopWindow != null)
                {
                    bigDeskTopWindow.Close();
                    bigDeskTopWindow= null;
                }
            }
        }

        /// <summary>
        /// 收到主持人开启电子白板 渲染
        /// </summary>
        /// <param name="whiteBoardID">电子白板id</param>
        public void OpenRemotingWhiteBoard(string whiteBoardID)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<string>(this.OpenRemotingWhiteBoard), whiteBoardID);
            }
            else
            {
                this.whiteBoardConnect(whiteBoardID);
                this.whiteBoardBtn.Visibility = Visibility.Visible;
                this.groupExtension.IsModeratorWhiteBoardNow = true;
                this.Panel_ChangeState(this.groupExtension.ModeratorID, "开启电子白板");
            }
        }

        /// <summary>
        /// 收到主持人关闭电子白板 渲染
        /// </summary>
        public void CloseRemotingWhiteBoard()
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric(this.CloseRemotingWhiteBoard));
            }
            else
            {
                //当打开电子白板时，关闭电子白板，并显示视频
                if(this.isWhiteBoardWatching)
                {
                    this.whiteBoardBtn.Background = new BrushConverter().ConvertFrom("#D5D5D5") as System.Windows.Media.Brush;
                    this.whiteBoardConnecter.Visibility = Visibility.Hidden;
                    this.VideoBtn.Background = new BrushConverter().ConvertFrom("#87CEFA") as System.Windows.Media.Brush;
                    this.cameraViewbox.Visibility = Visibility.Visible; 
                    this.isWhiteBoardWatching=false;
                }
                this.whiteBoardBtn.Visibility = Visibility.Collapsed;
                IChatUnit deskUnit = this.chatGroup.GetMember(this.groupExtension.ModeratorID) ?? this.chatGroup.GetMember(this.loginId);
                VideoPanel deskPanel = ((VideoAllPanel)deskUnit.Tag).videoPanel;
                this.Panel_ChangeState(this.groupExtension.ModeratorID, "关闭电子白板");
                this.whiteBoardConnecter.Disconnect();
                this.groupExtension.IsModeratorWhiteBoardNow = false;
            }
        }

        /// <summary>
        /// 正在共享桌面的用户退出群时 断开远程桌面
        /// </summary>
        /// <param name="isDesktop">是否开启远程</param>
        public void ClearDesktopAndWhiteBoard(bool isDesktop)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<bool>(this.ClearDesktopAndWhiteBoard), isDesktop);
            }
            else
            {
                if (bigDeskTopWindow != null && isDesktop)
                {
                    bigDeskTopWindow.Close();
                    bigDeskTopWindow = null;
                }
            }
        }
        #endregion
        
        /// <summary>
        /// 切换到显示视频（默认）
        /// </summary>
        private void VideoBtn_Click(object sender, MouseButtonEventArgs e)
        {
            Border border = sender as Border;
            border.Background = new BrushConverter().ConvertFrom("#87CEFA") as System.Windows.Media.Brush;
            this.whiteBoardBtn.Background = new BrushConverter().ConvertFrom("#D5D5D5") as System.Windows.Media.Brush;
            this.whiteBoardConnecter.Visibility = Visibility.Hidden;
            this.cameraViewbox.Visibility = Visibility.Visible;
            this.cameraViewbox.InvalidateVisual();
        }

        /// <summary>
        /// 切换到电子白板（主持人开启白板时有效）
        /// </summary>
        private void whiteBoardBtn_Click(object sender, MouseButtonEventArgs e)
        {
            Border border = sender as Border;
            border.Background = new BrushConverter().ConvertFrom("#87CEFA") as System.Windows.Media.Brush;
            this.VideoBtn.Background = new BrushConverter().ConvertFrom("#D5D5D5") as System.Windows.Media.Brush;
            this.cameraViewbox.Visibility = Visibility.Hidden;
            this.whiteBoardConnecter.Visibility = Visibility.Visible;
            this.whiteBoardConnecter.InvalidateVisual();
            this.isDeskTopWatching = false;
            this.isWhiteBoardWatching = true;
        }

        #region CameraIndexChange

        internal void CameraIndexChange(string destID)
        {
            UiSafeInvoker.ActionOnUI(() =>
            {
                if (destID == myselfPanel.ChatUnit.MemberID)
                {
                    myselfPanel.CameraIndexChange();
                    return;
                }
                List<IChatUnit> chatUnits = this.chatGroup.GetOtherMembers();
                if (chatUnits != null)
                {
                    IChatUnit chatUnit = chatUnits.Find(x => x.MemberID == destID);
                    if (chatUnit != null && chatUnit.Tag != null)
                    {
                        VideoAllPanel tag = (VideoAllPanel)chatUnit.Tag;
                        tag.videoPanel?.CameraIndexChange();
                    }
                }
            });
        }

        #endregion 
    }

    public interface IMemberNameGetter
    {
        string GetMemberName(string memberID);
    }

    public class DefaultMemberNameGetter : IMemberNameGetter
    {
        public string GetMemberName(string memberID)
        {
            return memberID;
        }
    }

    public struct VideoAllPanel
    {
        public VideoPanel videoPanel;
        public VideoHidePanel videoHidePanel;
    }

}
