using CPF;
using CPF.Controls;
using CPF.Drawing;
using CPF.Input;
using ESBasic;
using OMCS.Contracts;
using OMCS.Cpf;
using OMCS.Passive;
using OMCS.Passive.Audio;
using OMCS.Passive.MultiChat;
using OVCS.ClientLinux.Tools;
using OVCS.LinuxCore;
using System;
using System.Collections.Generic;

namespace OVCS.ClientLinux
{
    [CPF.Design.DesignerLoadStyle("res://OVCS.ClientLinux/Resource/Stylesheet1.css")]//用于设计的时候加载样式

    //聊天面板控件
    public class MultiVideoChatContainer : Control
    {
        protected override void InitializeComponent()
        {
            MarginTop = 0;
            MarginBottom = 0;
            MarginRight = 0;
            MarginLeft = 0;
            Size = SizeField.Fill;
            Children.Add(new Grid
            {
                Size = SizeField.Fill,
                RowDefinitions =
                {
                    new RowDefinition
                    {
                        Height = GridLength.Auto,
                    },
                    new RowDefinition
                    {
                        Height = GridLength.Star,
                    },
                    new RowDefinition
                    {
                        Height = GridLength.Auto,
                    },
                    new RowDefinition
                    {
                        Height = GridLength.Auto,
                    }
                },
                Children =
                {
                    new Grid
                    {
                        MarginTop = 0,
                        MarginLeft= 0,
                        MarginRight= 0,
                        Name="topNav",
                        Background=CPF.Drawing.Color.DeepSkyBlue,
                        PresenterFor=this,
                        Height = 56,
                        ColumnDefinitions =
                        {
                            new ColumnDefinition
                            {
                                Width= GridLength.Auto,
                            },
                            new ColumnDefinition
                            {
                                Width= GridLength.Auto,
                            },
                            new ColumnDefinition
                            {
                                Width= GridLength.Star,
                            },
                            new ColumnDefinition
                            {
                                Width= GridLength.Auto,
                            },
                        },
                        Children =
                        {
                            new Grid
                            {
                                RowDefinitions =
                                {
                                    new RowDefinition
                                    {
                                        Height= GridLength.Star,
                                    },
                                    new RowDefinition
                                    {
                                        Height= GridLength.Star,
                                    }
                                },
                                Children =
                                {
                                    new StackPanel()
                                    {
                                        MarginLeft = 10,
                                        MarginBottom = 3,
                                        Height = 28,
                                        Orientation = Orientation.Horizontal,
                                        Children =
                                        {
                                            new Label()
                                            {
                                                Size = SizeField.Fill,
                                                MarginTop = 0,
                                                MarginLeft= 0,
                                                Text = "主持人：",
                                                FontSize = 15,
                                                Foreground = CPF.Drawing.Color.White
                                            },
                                            new Label()
                                            {
                                                Size = SizeField.Fill,
                                                MarginTop = 0,
                                                MarginLeft= 0,
                                                Name="skinLabel_userID",
                                                PresenterFor = this,
                                                Text = "aa01",
                                                FontSize = 15,
                                                Foreground = CPF.Drawing.Color.White
                                            }
                                        },
                                        Attacheds =
                                        {
                                            {
                                                Grid.RowIndex,
                                                0
                                            }
                                        }
                                    },
                                    new StackPanel()
                                    {
                                        Orientation = Orientation.Horizontal,
                                        MarginLeft = 10,
                                        MarginTop = 3,
                                        Children =
                                        {
                                            new Label()
                                            {
                                                MarginLeft= 0,
                                                Text = "人  数：",
                                                FontSize = 15,
                                                Foreground = CPF.Drawing.Color.White
                                            },
                                            new Label()
                                            {
                                                MarginLeft= 0,
                                                Name="skinLabel_totalNum",
                                                PresenterFor = this,
                                                Text = "1",
                                                FontSize = 15,
                                                Foreground = CPF.Drawing.Color.White
                                            }
                                        },
                                        Attacheds =
                                        {
                                            {
                                                Grid.RowIndex,
                                                1
                                            }
                                        }
                                    }
                                }
                            },
                            new StackPanel
                            {
                                Orientation = Orientation.Horizontal,
                                Children =
                                {
                                    new Picture()
                                    {
                                        ToolTip = "摄像头：开",
                                        MarginTop = 8,
                                        MarginLeft = 8,
                                        MarginBottom = 8,
                                        MarginRight = 8,
                                        Name = "skinCheckBox_camera",
                                        PresenterFor = this,
                                        Width = 35,
                                        Height = 35,
                                        Stretch = Stretch.Uniform,
                                        Source = CommonHelper.ResourcesCatalog + "CameraSelect.png",
                                        Commands =
                                        {
                                            {
                                                nameof(Button.MouseDown),
                                                (s, e) =>
                                                {
                                                    this.skinCheckBox_camera_MouseDown(s,(MouseEventArgs)e);
                                                }
                                            }
                                        }
                                     },
                                    new Picture()
                                    {
                                        ToolTip="扬声器：开",
                                        MarginTop = 8,
                                        MarginLeft = 8,
                                        MarginBottom = 8,
                                        MarginRight = 8,
                                        Width = 35,
                                        Height = 35,
                                        Name = "skinCheckBox_speaker",
                                        PresenterFor = this,
                                        Stretch = Stretch.UniformToFill,
                                        Source = CommonHelper.ResourcesCatalog + "SpeakerSelect.png",
                                        Commands =
                                         {
                                             {
                                                 nameof(Button.MouseDown),
                                                 (s, e) =>
                                                 {
                                                     this.skinCheckBox_speaker_MouseDown(s,(MouseEventArgs)e);
                                                 }
                                             }
                                         }
                                    },
                                    new Picture()
                                    {
                                        Width = 40,
                                        Height = 40,
                                        MarginTop = 8,
                                        MarginLeft = 8,
                                        MarginBottom = 8,
                                        MarginRight = 8,
                                        ToolTip="麦克风：关",
                                        Name="skinCheckBox_mic",
                                        PresenterFor = this,
                                        Stretch = Stretch.UniformToFill,
                                        Source = CommonHelper.ResourcesCatalog + "micNoSelect.png",
                                        Commands =
                                        {
                                            {
                                                nameof(Button.MouseDown),
                                                (s, e) =>
                                                {
                                                    this.skinCheckBox_mic_MouseDown(s,(MouseEventArgs)e);
                                                }
                                            }
                                        }
                                    },
                                    new Picture()
                                    {
                                        Width = 40,
                                        Height = 40,
                                        MarginTop = 8,
                                        MarginLeft = 8,
                                        MarginBottom = 8,
                                        MarginRight = 8,
                                        ToolTip="远程桌面共享：关",
                                        Name = "skinCheckBox_desk",
                                        PresenterFor = this,
                                        Stretch = Stretch.UniformToFill,
                                        Source = CommonHelper.ResourcesCatalog + "DesktopNoSelect.png",
                                        Commands =
                                        {
                                            {
                                                nameof(Button.MouseDown),
                                                (s,e) =>
                                                {
                                                    this.skinCheckBox_desk_MouseDown(s,(MouseEventArgs)e);
                                                }
                                            }
                                        }
                                    },
                                    new Picture()
                                    {
                                        ToolTip="电子白板（主持人才有权限）：关",
                                        Visibility = Visibility.Collapsed,
                                        Width = 40,
                                        Height = 40,
                                        MarginTop = 8,
                                        MarginLeft = 8,
                                        MarginBottom = 8,
                                        MarginRight = 8,
                                        Name="skinCheckBox_whilebord",
                                        PresenterFor = this,
                                        Source = CommonHelper.ResourcesCatalog + "WhiteBoardNoSelect.png",
                                        Stretch = Stretch.UniformToFill,
                                        Commands =
                                        {
                                            {
                                                nameof(Button.MouseDown),
                                                (s,e) =>
                                                {
                                                    this.skinCheckBox_whilebord_MouseDown(s,(MouseEventArgs)e);
                                                }
                                            }
                                        }
                                    },
                                    new TextBlock
                                    {
                                        Visibility = Visibility.Collapsed,
                                        Text="您正在共享桌面！",
                                        FontSize=15,
                                        Foreground="#FFFFFF",
                                        Name="deskTop_myself",
                                        PresenterFor = this,
                                    }
                                },
                                Attacheds =
                                {
                                    {
                                        Grid.ColumnIndex,
                                        1
                                    }
                                }
                            },
                            new Picture()
                            {
                                Visibility = Visibility.Hidden,
                                ToolTip="",
                                Height = 35,
                                Width = 35,
                                Name="deskTopFullScreen",
                                PresenterFor = this,
                                MarginRight = 5,
                                MarginBottom = 0,
                                Source = CommonHelper.ResourcesCatalog + "FullScreen.png",
                                Stretch = Stretch.UniformToFill,
                                Commands =
                                {
                                    {
                                        nameof(Button.MouseDown),
                                        (s,e) =>
                                        {
                                            this.deskTopFullScreen_MouseDown(s,(MouseEventArgs)e);
                                        }
                                    }
                                },
                                Attacheds =
                                {
                                    {
                                        Grid.ColumnIndex,
                                        2
                                    }
                                }
                            },
                            new StackPanel()
                            {
                                MarginRight = 0,
                                MarginBottom= 0,
                                Orientation = Orientation.Horizontal,
                                Children =
                                {
                                    new Border
                                    {
                                        Background= CPF.Drawing.Color.LightGray,
                                        Name="whiteBoardBtn",
                                        PresenterFor= this,
                                        Height = 30,
                                        Width = 60,
                                        BorderFill = Color.Transparent,
                                        Visibility = Visibility.Collapsed,
                                        MarginRight = 0,
                                        Child = new TextBlock
                                        {
                                            TextAlignment = TextAlignment.Center,
                                            VerticalAlignment= VerticalAlignment.Center,

                                            Text = "电子白板",
                                            MarginTop = 0,
                                            MarginBottom= 0,
                                        },
                                        Commands =
                                        {
                                            {
                                                nameof(Button.MouseDown),
                                                (s,e) =>
                                                {
                                                    this.whiteBoardBtn_Click(s,(MouseEventArgs)e);
                                                }
                                            }
                                        },
                                    },
                                    new Border
                                    {
                                        Background=CPF.Drawing.Color.LightSkyBlue,
                                        Name="VideoBtn",
                                        BorderFill = Color.Transparent,
                                        PresenterFor = this,
                                        Height = 30,
                                        Width = 60,
                                        MarginLeft= 1,
                                        Visibility = Visibility.Visible,
                                        MarginRight = 0,
                                        Child = new TextBlock
                                        {
                                            TextAlignment = TextAlignment.Center,
                                            Text = "视频",
                                            VerticalAlignment= VerticalAlignment.Center,

                                            MarginTop = 0,
                                            MarginBottom= 0,
                                        },
                                        Commands =
                                        {
                                            {
                                                nameof(Button.MouseDown),
                                                (s,e) =>
                                                {
                                                    this.VideoBtn_Click(s,(MouseEventArgs)e);
                                                }
                                            }
                                        }
                                    },
                                },
                                Attacheds =
                                {
                                    {
                                        Grid.ColumnIndex,
                                        3
                                    }
                                }
                            },
                        },
                        Attacheds =
                        {
                            {
                                Grid.RowIndex,
                                0
                            }
                        }
                    },
                    new Grid
                    {

                        MarginTop = 0,
                        MarginBottom = 0,
                        MarginLeft = 0,
                        MarginRight = 0,
                        Background = "#121212",
                        Name = "GridWhiteBoard",
                         PresenterFor = this,
                        Children =
                        {
                            new AutoScaleContainer
                            {
                                Size = SizeField.Fill,
                                Name = "cameraViewbox",
                                PresenterFor = this,
                                MarginTop = 0,
                                MarginLeft = 0,
                                MarginRight = 0,
                                MarginBottom = 0
                            },
                            //new WhiteBoardConnector
                            //{
                            //    Size = SizeField.Fill,
                            //    Background = CPF.Drawing.Color.White,
                            //    Visibility = Visibility.Hidden,
                            //    Name = "whiteBoardConnecter",
                            //    PresenterFor = this,
                            //}
                        },
                        Attacheds =
                        {
                            {
                                Grid.RowIndex,
                                1
                            }
                        }
                    },
                    new ScrollViewer
                    {
                        Height = 52,
                        Width = 888,
                        Background="#202020",
                        Name = "scroll_bottom",
                        PresenterFor = this,
                        HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,

                        Content = new WrapPanel()
                        {
                            Name = "flowLayoutPanel2",
                            PresenterFor = this,
                            MarginLeft = 0,
                            MarginRight = 0,
                        },
                        Attacheds =
                        {
                             {
                                 Grid.RowIndex,
                                 2
                             }
                         }
                    },
                    new Grid
                    {
                       MarginBottom= 0,
                       Background = CPF.Drawing.Color.DeepSkyBlue,
                       Width= "100%",
                       Height = 36,
                       Children =
                       {
                            new StackPanel
                            {
                                MarginLeft = 0,
                                Orientation = Orientation.Horizontal,
                                Children =
                                {
                                    new TextBlock
                                    {
                                        MarginLeft = 20,
                                        Text = "当前登录：",
                                        FontSize = 15,
                                        VerticalAlignment = VerticalAlignment.Center,
                                        Foreground = CPF.Drawing.Color.White,
                                    },
                                    new TextBlock
                                    {
                                        Name="myselfId",
                                        PresenterFor= this,
                                        MarginLeft = 20,
                                        Text = "aa01",
                                        FontSize = 15,
                                        VerticalAlignment = VerticalAlignment.Center,
                                        Foreground = CPF.Drawing.Color.White
                                    }
                                }
                            },
                            new TextBlock
                            {
                                MarginRight = 20,
                                Name = "userDeviceState",
                                PresenterFor = this,
                                Text = "",
                                FontSize = 15,
                                VerticalAlignment = VerticalAlignment.Center,
                                Foreground = CPF.Drawing.Color.White
                            }
                        },
                       Attacheds =
                       {
                            {
                                Grid.RowIndex,
                                3
                            }
                        }
                    }
                }
            }) ;
            if (!DesignMode)//设计模式下不执行，也可以用#if !DesignMode
            {
                SetComponent();
            }
        }
//#if !DesignMode //用户代码写到这里，设计器下不执行，防止设计器出错
        #region 带名称控件
        private Grid topNav;
        private Label skinLabel_userID;
        private Picture skinCheckBox_camera;
        private Picture skinCheckBox_speaker;
        private Picture skinCheckBox_mic;
        private Picture skinCheckBox_desk;
        private Picture skinCheckBox_whilebord;
        private Picture deskTopFullScreen;
        private Grid GridWhiteBoard;
        private WhiteBoardConnector whiteBoardConnecter = new WhiteBoardConnector
        {
            Size = SizeField.Fill,
            Background = CPF.Drawing.Color.White,
            Visibility = Visibility.Hidden,
        };
        private TextBlock myselfId;
        private ScrollViewer scroll_bottom;
        private TextBlock userDeviceState;
        private Border VideoBtn;
        private Border whiteBoardBtn;
        private AutoScaleContainer cameraViewbox;

        private Label skinLabel_totalNum;
        private WrapPanel flowLayoutPanel2;
        private TextBlock deskTop_myself;
        #endregion

         
        private IMultimediaManager multimediaManager;//OMCS 多媒体管理器
        private IChatGroup chatGroup;// 视频聊天组
        #region 共享桌面的其他人Id
        //private string shareDeskId; //正在共享桌面的其他人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 MainWindow mainWindow;//主窗体
        private int videoShowCount = 0;//视频正常显示并且连接成功的用户数量
        private bool isVideoShowBeyond = false; //是否超过限定的视频个数
        public void SetComponent()
        {
            topNav = this.FindPresenterByName<Grid>("topNav");
            skinLabel_userID = this.FindPresenterByName<Label>("skinLabel_userID");
            skinCheckBox_camera = this.FindPresenterByName<Picture>("skinCheckBox_camera");
            skinCheckBox_speaker = this.FindPresenterByName<Picture>("skinCheckBox_speaker");
            skinCheckBox_mic = this.FindPresenterByName<Picture>("skinCheckBox_mic");
            skinCheckBox_desk = this.FindPresenterByName<Picture>("skinCheckBox_desk");
            skinCheckBox_whilebord = this.FindPresenterByName<Picture>("skinCheckBox_whilebord");
            deskTopFullScreen = this.FindPresenterByName<Picture>("deskTopFullScreen");
            myselfId = this.FindPresenterByName<TextBlock>("myselfId");
            scroll_bottom = this.FindPresenterByName<ScrollViewer>("scroll_bottom");
            userDeviceState = this.FindPresenterByName<TextBlock>("userDeviceState");
            VideoBtn = this.FindPresenterByName<Border>("VideoBtn");
            whiteBoardBtn = this.FindPresenterByName<Border>("whiteBoardBtn");
            cameraViewbox = this.FindPresenterByName<AutoScaleContainer>("cameraViewbox");
            skinLabel_totalNum = this.FindPresenterByName<Label>("skinLabel_totalNum");
            flowLayoutPanel2 = this.FindPresenterByName<WrapPanel>("flowLayoutPanel2");
            deskTop_myself = this.FindPresenterByName<TextBlock>("deskTop_myself");
            GridWhiteBoard = this.FindPresenterByName<Grid>("GridWhiteBoard");
            GridWhiteBoard.Children.Add(whiteBoardConnecter);
            this.PropertyChanged += MultiVideoChatContainer_PropertyChanged;
        }

        // 手动修改 尺寸
        public void MultiVideoChatContainer_PropertyChanged(object sender, CPFPropertyChangedEventArgs e)
        {
            MultiVideoChatContainer chatContainer = (MultiVideoChatContainer)sender;
            if (e.PropertyName.Contains("Size"))
            {
                if (chatContainer.ActualSize.Width > 0)
                {
                    this.scroll_bottom.Width = chatContainer.ActualSize.Width;
                }
            }
        }

        // 修改控件尺寸
        public void SetUserControl_SizeChanged()
        {
            this.cameraViewbox.UserControl_SizeChanged();
        }

        protected override void OnInitialized()
        {
            base.OnInitialized();
        }

        /// <summary>
        /// 关闭窗口时触发
        /// </summary>
        public void Close()
        {
            if (this.multimediaManager != null)
            {
                this.multimediaManager.ChatGroupEntrance.Exit(ChatType.Video, this.chatGroup.GroupID);
            }
            this.multimediaManager.Dispose(); 
        }
        //用户代码
        public void Initialize(IMultimediaManager _multimediaManager, string chatGroupID, GroupExtension _groupExtension,MainWindow main)
        {
            try
            {
                this.cameraViewbox.videoPanelSizeChange += CameraViewbox_videoPanelSizeChange;
                this.groupId = chatGroupID;
                this.groupExtension = _groupExtension;
                this.multimediaManager = _multimediaManager;
                this.mainWindow = main;
                this.loginId = this.multimediaManager.CurrentUserID; 
                this.skinLabel_userID.Text = this.groupExtension.ModeratorID;
                this.myselfId.Text = this.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.ShowMicState(this.loginId, this.loginId == this.groupExtension.ModeratorID);
                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);
                //渲染连接其他人的摄像头麦克风
                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;
                } 
                this.TotalNumChange(this.chatGroup.GetOtherMembers().Count + 1);
                #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 = "麦克风：开";
                    }
                    if (this.chatGroup.GetMember(this.groupExtension.ModeratorID) == null)
                    {
                        return;
                    }
                }
                #endregion


                // 判断是否当前会议时内是否有用户开启远程桌面，若有则连接该用户的远程桌面并显示。
                if (_groupExtension.DesktopSharedUserID != null)
                {
                    this.OpenRemotingDesktop(groupExtension.DesktopSharedUserID);
                }
                // 判断是否当前会议时内主持人是否开启电子白板，若有则连接到电子白板并显示。
                if (_groupExtension.IsModeratorWhiteBoardNow)
                {
                    this.OpenRemotingWhiteBoard(this.groupId);
                }
                if (this.myselfPanel.DynamicCameraConnector.Connected)
                {
                    this.topNav.IsHitTestVisible = true;
                }
                this.VideoSizeChange(new Size(this.cameraViewbox.FlowLayoutPanel.Width.Value,this.cameraViewbox.FlowLayoutPanel.Height.Value));
                this.VideoNumBeyond();
                if (this.isVideoShowBeyond)
                {
                    this.cameraViewbox.FlowLayoutPanel.Children.Remove(this.myselfPanel);
                    this.flowLayoutPanel2.Children.Insert(0, this.myselfHidePanel);
                    this.myselfHidePanel.cameraVisibilityChange(true);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message+" - " + ex.StackTrace);
            }
        }

        public 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 Size(this.cameraViewbox.FlowLayoutPanel.Width.Value, this.cameraViewbox.FlowLayoutPanel.Height.Value));
            }
        }

        // 窗口尺寸修改时触发
        public void CameraViewbox_videoPanelSizeChange(CPF.Drawing.Size size)
        {
            this.VideoSizeChange(size);
        }

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

        //计算视频控件的宽高
        public void VideoSizeChange(CPF.Drawing.Size size)
        {
            if (this.cameraViewbox.FlowLayoutPanel.Children.Count > 4)
            {
                foreach (VideoPanel panel in this.cameraViewbox.FlowLayoutPanel.Children)
                {
                    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>
        public void VideoNumBeyond()
        {
            this.isVideoShowBeyond = this.cameraViewbox.FlowLayoutPanel.Children.Count > 9 ? true : false;
        }

        //会议总人数
        public void TotalNumChange(int num)
        {
            this.skinLabel_totalNum.Text = num.ToString();
        }

        /// <summary>
        /// 获取当前所有说话者声音的分贝值 200ms触发一次
        /// </summary>
        /// <param name="decibels">用户分贝列表</param>
        public void MultimediaManager_SpeakerVoiceNotified(List<UserDecibel> decibels)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                ((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())
                {
                    ((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="panel">用户</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 Size(this.cameraViewbox.FlowLayoutPanel.Width.Value, this.cameraViewbox.FlowLayoutPanel.Height.Value));
        }

        /// <summary>
        /// 用户状态改变时
        /// </summary>
        /// <param name="ownerID">账号</param>
        /// <param name="stateInformation">状态信息</param>
        public void Panel_ChangeState(string ownerID, string stateInformation)
        {
            this.userDeviceState.Text = ownerID + stateInformation;
        }

        #region 视频聊天会议组
        //某人退出chatGroup视频会议
        public void chatGroup_SomeoneExit(string memberID)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {   
                VideoPanel target = null;
                VideoHidePanel targethide = null;
                foreach (VideoPanel panel in this.cameraViewbox.FlowLayoutPanel.Children)
                {
                    if (panel.MemberID == memberID)
                    {
                        target = panel;
                        break;
                    }
                }
                if (this.isVideoShowBeyond && 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 Size(this.cameraViewbox.FlowLayoutPanel.Width.Value, this.cameraViewbox.FlowLayoutPanel.Height.Value));
                this.VideoNumBeyond();
            });
        }
        //某人加入chatGroup视频会议
        public void chatGroup_SomeoneJoin(IChatUnit unit)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                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 Size(this.cameraViewbox.FlowLayoutPanel.Width.Value, this.cameraViewbox.FlowLayoutPanel.Height.Value));
            });
        }
        #endregion

        #region 设备开关
        //主持人开启/关闭白板
        public void skinCheckBox_whilebord_MouseDown(CpfObject s, MouseEventArgs e)
        {
            this.isWhiteBoard = !this.isWhiteBoard;
            skinCheckBox_whilebord.Source = this.isWhiteBoard ? ResourceManager.Singleton.WhiteBoardOpenImage : ResourceManager.Singleton.WhiteBoardCloseImage;
            skinCheckBox_whilebord.ToolTip = this.isWhiteBoard ? "电子白板（主持人才有权限）：开" : "电子白板（主持人才有权限）：关";
            if (this.isWhiteBoard)
            {
                this.whiteBoardConnect(this.groupId);
                this.groupExtension.IsModeratorWhiteBoardNow = true;
                this.whiteBoardBtn.Visibility = Visibility.Visible;
                this.multimediaManager.SendCustomizedMessage(null, InformationTypes.BroadcastWhiteBoard, System.BitConverter.GetBytes(this.isWhiteBoard), this.groupId);
            }
            else
            {
                this.whiteBoardBtn.Visibility = Visibility.Collapsed;
                this.whiteBoardConnecter.Disconnect();
                if (this.isWhiteBoardWatching)
                {
                    this.whiteBoardBtn.Background = "#D5D5D5";
                    this.whiteBoardConnecter.Visibility = Visibility.Hidden;
                    this.VideoBtn.Background = "#87CEFA";
                    this.cameraViewbox.Visibility = Visibility.Visible;
                    this.isWhiteBoardWatching = false;
                }
                this.multimediaManager.SendCustomizedMessage(null, InformationTypes.BroadcastWhiteBoard, System.BitConverter.GetBytes(this.isWhiteBoard), this.groupId);
                this.groupExtension.IsModeratorWhiteBoardNow = false;
            }
        }

        //开启/关闭远程桌面
        public void skinCheckBox_desk_MouseDown(CpfObject s, MouseEventArgs e)
        {
            this.isMyselfDesktop = !this.isMyselfDesktop;
           
            if (this.isMyselfDesktop)
            {
                if (this.groupExtension.DesktopSharedUserID != null)
                {
                    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(null, InformationTypes.BroadcastShareDesk, System.BitConverter.GetBytes(this.isMyselfDesktop), this.groupId);
            }
            else
            {
                if (this.isDeskTopWatching)
                {
                    this.VideoBtn.Background = "#87CEFA";
                    this.cameraViewbox.Visibility = Visibility.Visible;
                    this.isDeskTopWatching = false;
                }
                this.multimediaManager.SendCustomizedMessage(null, InformationTypes.BroadcastShareDesk, System.BitConverter.GetBytes(this.isMyselfDesktop), this.groupId);
                this.groupExtension.DesktopSharedUserID = null;

                this.deskTop_myself.Visibility = Visibility.Collapsed;
                if (bigDeskTopWindow != null)
                {
                    bigDeskTopWindow.Close();
                    bigDeskTopWindow = null;
                }
            }
            this.skinCheckBox_desk.Source = this.isMyselfDesktop ? ResourceManager.Singleton.DesktopOpenImage : ResourceManager.Singleton.DesktopCloseImage;
            this.skinCheckBox_desk.ToolTip = this.isMyselfDesktop ? "远程桌面共享：开" : "远程桌面共享：关";

        }

        //开启/关闭麦克风
        public void skinCheckBox_mic_MouseDown(CpfObject s, MouseEventArgs e)
        {
            this.isMyselfMic = !this.isMyselfMic;
            this.skinCheckBox_mic.Source = this.isMyselfMic ? ResourceManager.Singleton.MicOpenImage : ResourceManager.Singleton.MicCloseImage;
            this.skinCheckBox_mic.ToolTip = this.isMyselfMic ? "麦克风 ：开" : "麦克风：关";
            if (IsInitialized)
            {
                this.myselfPanel.ShowMicState(this.loginId, this.isMyselfMic);
                this.multimediaManager.OutputAudio = this.isMyselfMic;
            }
        }

        //开启/关闭扬声器
        public void skinCheckBox_speaker_MouseDown(CpfObject s, MouseEventArgs e)
        {
            this.isMyselfSpeak = !this.isMyselfSpeak;
            this.skinCheckBox_speaker.Source = this.isMyselfSpeak ? ResourceManager.Singleton.SpeakerOpenImage : ResourceManager.Singleton.SpeakerCloseImage;
            this.skinCheckBox_speaker.ToolTip = this.isMyselfSpeak ? "扬声器：开" : "扬声器：关";
            if (IsInitialized)
            {
                this.multimediaManager.Mute = !this.isMyselfSpeak;
            }
        }

        //开启/关闭摄像头
        private void skinCheckBox_camera_MouseDown(CpfObject s, MouseEventArgs e)
        {
            this.isMyselfVideo = !this.isMyselfVideo;
            this.skinCheckBox_camera.Source = this.isMyselfVideo ? ResourceManager.Singleton.CameraOpenImage : ResourceManager.Singleton.CameraCloseImage;
            this.skinCheckBox_camera.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 Size(this.cameraViewbox.FlowLayoutPanel.Width.Value, this.cameraViewbox.FlowLayoutPanel.Height.Value));
            }
        }
        #endregion
        #region 远程桌面连接器
        //远程桌面连接器
        BigDesktop bigDeskTopWindow;
        public void desktopConnect(string desktopId)
        {
#if !DesignMode
            bigDeskTopWindow = new BigDesktop(desktopId, this);
#endif
            bigDeskTopWindow.Show();
            this.DeskTopBtnHitTestVisibleChange(false);
        }
        public void DeskTopBtnHitTestVisibleChange(bool isHitTestVisible)
        {
            this.deskTopFullScreen.IsHitTestVisible = isHitTestVisible;
        }
        #endregion
        #region 手动打开远程桌面
        public void deskTopFullScreen_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.groupExtension.DesktopSharedUserID != null || this.isMyselfDesktop)
            {
                this.desktopConnect(this.groupExtension.DesktopSharedUserID);
            }
        }
        #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.ParentWindow = mainWindow;
                this.whiteBoardConnecter.BeginConnect(whiteBoardId);
            }
        }
        #endregion
        #region 电子白板连接结果、电子白板断开连接
        public void WhiteBoardConnecter_Disconnected(string boardId, ConnectorDisconnectedType type)
        {

        }

        public void WhiteBoardConnecter_ConnectEnded(string boardId, ConnectResult res)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                if (res != ConnectResult.Succeed)
                {
                    MessageBox.Show("电子白板连接失败！" + res.ToString());
                }
            });
        }
        #endregion 
        #region 远程桌面和白板 
        /// <summary>
        /// 收到其他人开启共享远程桌面 渲染 
        /// </summary>
        /// <param name="broadcasterID">当前共享桌面的用户Id</param>
        public void OpenRemotingDesktop(string broadcasterID)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                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()
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                if (this.isDeskTopWatching)
                {
                    this.VideoBtn.Background = "#87CEFA";
                    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 (this.bigDeskTopWindow != null)
                {
                    this.bigDeskTopWindow.Close();
                    bigDeskTopWindow = null;
                }
            });
        }

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

        /// <summary>
        /// 收到主持人关闭电子白板 渲染
        /// </summary>
        public void CloseRemotingWhiteBoard()
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                //当打开电子白板时，关闭电子白板，并显示视频
                if (this.isWhiteBoardWatching)
                {
                    this.whiteBoardBtn.Background = "#D5D5D5";
                    this.whiteBoardConnecter.Visibility = Visibility.Hidden;
                    this.VideoBtn.Background = "#87CEFA";
                    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)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                if (bigDeskTopWindow != null && isDesktop)
                {
                    bigDeskTopWindow.Close();
                    bigDeskTopWindow = null;
                }
            });
        }
        #endregion

        /// <summary>
        /// 切换到显示视频（默认）
        /// </summary>
        public void VideoBtn_Click(object sender, MouseEventArgs e)
        {
            Border border = sender as Border;
            border.Background = "#87CEFA";
            this.whiteBoardBtn.Background = "#D5D5D5";
            this.whiteBoardConnecter.Visibility = Visibility.Hidden;
            this.cameraViewbox.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 切换到电子白板（主持人开启白板时有效）
        /// </summary>
        public void whiteBoardBtn_Click(object sender, MouseEventArgs e)
        {
            Border border = sender as Border;
            border.Background = "#87CEFA";
            this.VideoBtn.Background = "#D5D5D5";
            this.cameraViewbox.Visibility = Visibility.Hidden;
            this.whiteBoardConnecter.Visibility = Visibility.Visible;
            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;
        } 
    }
}
