using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IMLibrary.Controls;
using P;
using Ourmsg.Enum;

namespace OurMsg
{
    public partial class FormSetRoom : Form
    {
        #region 构造函数
        public FormSetRoom()
        {
            InitializeComponent();
            ListView1.MouseMove += ListView1_MouseMove ;
            ListView1.ColumnWidthChanging += (s, e) =>
            { 
                e.NewWidth = ListView1.Columns[e.ColumnIndex].Width;
                e.Cancel = true; 
            };
            ListView1.SelectedIndexChanged += ListView1_SelectedIndexChanged;
            ListView1.Click += ListView1_Click ;

            tsButDelUser.Click += tsButDel_Click;
            tsButSetManager.Click += tsButSetManager_Click;
            tsButDelManager.Click += tsButDelManager_Click;
            tsButEditCard.Click += tsButEditCard_Click ;

            textBoxCard.KeyDown += new KeyEventHandler(textBoxCard_KeyDown);
            
            butInvAddRoomUser.Click += (s, e) => showFormInviteFriends();

            linkLabelSave.Click += new System.EventHandler(linkLabelSave_Click);

            setControls(false);
        }

        void linkLabelSave_Click(object sender, EventArgs e)
        {
            if (textBoxRoomName.Text.Trim() == string.Empty)
            {
                Global.ShowMessage("群名不能为空！");
                textBoxRoomName.Focus();
            }
            if (getRoombaseInfoString() == oldRoombaseInfoString)
            {
                Console.WriteLine("群数据未变化，不会提交服务器。");
                return;
            }
            RoomBaseInfo rbinfo = new RoomBaseInfo();
            rbinfo.RoomID = RoomID;
            if (radioAddCondition1.Checked)
                rbinfo.AddCondition = (byte)Ourmsg.Enum.AddCondition.AllowAll;
            else if (radioAddCondition2.Checked)
                rbinfo.AddCondition = (byte)Ourmsg.Enum.AddCondition.NeedAuditing;
            else if (radioAddCondition3.Checked)
                rbinfo.AddCondition = (byte)Ourmsg.Enum.AddCondition.RefuseALL;
            rbinfo.RoomName = textBoxRoomName.Text.Trim();
            rbinfo.Notice = textBoxNotice.Text.Trim();
            rbinfo.Remark = textBoxRemark.Text.Trim();
            rbinfo.RemarkName = textBoxRemarkName.Text.Trim();
            OnCreateMsgAfter(Ourmsg.Enum.CommandType.SetRoomBaseInfo, rbinfo);
        }

        void textBoxCard_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == System.Windows.Forms.Keys.Enter)
            {
                textBoxCardVisible();
            }
        }

        void ListView1_Click(object sender, EventArgs e)
        {
            textBoxCardVisible();
        }

        void textBoxCardVisible()
        {
            if (textBoxCard.Visible)
                if (textBoxCard.Text.Trim() != textBoxCard.OldValue)
                {
                    RoomUser ru = new RoomUser();
                    ru.UserID = textBoxCard.UserID;
                    ru.UserCard = textBoxCard.Text.Trim();
                    OnCreateMsgAfter(Ourmsg.Enum.CommandType.SetRoomUserCard, ru);
                }
            textBoxCard.Visible = false; 
        }


        void tsButEditCard_Click(object sender, EventArgs e)
        {
            if (SelectItem != null)
            {
                if (textBoxCard.Visible && Convert.ToUInt32(SelectItem.Tag)==textBoxCard.UserID)
                    return;
                textBoxCard.Width = SelectItem.SubItems[2].Bounds.Width;
                textBoxCard.Height = SelectItem.Bounds.Height;
                textBoxCard.Top = ListView1.Top + SelectItem.Bounds.Y - 2;
                textBoxCard.Left = ListView1.Left + SelectItem.SubItems[2].Bounds.X;
                textBoxCard.OldValue = SelectItem.SubItems[2].Text;
                textBoxCard.Text = SelectItem.SubItems[2].Text;
                textBoxCard.UserID = Convert.ToUInt32(SelectItem.Tag);
                textBoxCard.Visible = true;
                textBoxCard.Focus();

            }
            else
                textBoxCard.Visible = false;
        }
        #endregion
         
        #region 事件
        /// <summary>
        /// 发送事件代理
        /// </summary>
        /// <param name="Msg">要发送的消息</param>
        public delegate void EventHandler(object sender, object  Msg);
        /// <summary>
        /// 创建消息事件
        /// </summary>
        public event EventHandler CreateMsgAfter;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void OnCreateMsgAfter(Ourmsg.Enum. CommandType cmd,object msg)
        {
            cmdType = cmd;
            if (CreateMsgAfter != null)
                CreateMsgAfter(this, msg);
        }
        #endregion

        #region 字段
        /// <summary>
        /// 自己是否群管理员
        /// </summary>
        bool SelfIsManager = false;
        /// <summary>
        /// 自己是否群主
        /// </summary>
        bool SelfIsCreater = false;

        /// <summary>
        /// 当前群帐号
        /// </summary>
        UInt32 RoomID = 0;

        /// <summary>
        /// 邀请用户加群窗口
        /// </summary>
        FormInviteFriends formInviteFriends;

        ListViewItem SelectItem = null;
        /// <summary>
        /// 事件操作类型
        /// </summary>
        public Ourmsg.Enum. CommandType cmdType
        {
            private set;
            get;
        }
        /// <summary>
        /// 群基本信息原值
        /// </summary>
        string oldRoombaseInfoString;
        #endregion

        #region 编辑、保存
        private void linkLabelEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            oldRoombaseInfoString = getRoombaseInfoString();
            setControls(true);
        }

        /// <summary>
        /// 获得当前的群基本信息字符串
        /// </summary>
        /// <returns></returns>
        private string getRoombaseInfoString()
        {
            string s="";
            s += textBoxRoomName.Text.Trim();
            s += textBoxRemarkName.Text.Trim();
            s += textBoxNotice.Text.Trim();
            s += textBoxRemark.Text.Trim();
            if (radioAddCondition1.Checked)
                s += "1";
            else if (radioAddCondition2.Checked)
                s += "2";
            else if (radioAddCondition3.Checked)
                s += "3";
            return s;
        }

        private void linkLabelSave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            setControls(false);
        }
        #endregion

        #region 设置控件样式
        private void setControls(bool edit)
        {
            linkLabelSave.Visible = edit;
            linkLabelEdit.Visible = !edit;
            textBoxRoomName.ReadOnly = !edit; textBoxRoomName.BackColor = Color.White;
            textBoxNotice.ReadOnly = !edit;
            textBoxRemark.ReadOnly = !edit;
            textBoxRemarkName.ReadOnly = !edit;

            radioAddCondition1.Enabled = edit;
            radioAddCondition2.Enabled = edit;
            radioAddCondition3.Enabled = edit;

            textBoxRoomName.Focus();
        }
        #endregion

        #region 窗口加载事件
        private void FormSetRoom_Load(object sender, EventArgs e)
        {
            ToolStrip1.FormBackColor = ListView1.BackColor;

        }
        #endregion

        #region 设置群
        /// <summary>
        /// 设置群
        /// </summary>
        /// <param name="room"></param>
        public void SetRoomData(ExRoom room)
        {
            RoomID = room.BaseInfo.RoomID;

            SetRoomBaseInfo(room.BaseInfo);

            var selfUser = Global.GetRoomUser(RoomID, Global.MsgClient.MyAuth.UserID );
            if (selfUser != null && selfUser.Admin )
            {
                SelfIsManager = true;
                linkLabelEdit.Visible = true;
                butInvAddRoomUser.Visible = true;
            }
            else
            {
                linkLabelEdit.Visible = false;
                butInvAddRoomUser.Visible = false;
            }

            if (selfUser.UserID == room.BaseInfo.CreateUserID)
                SelfIsCreater = true;

            this.textBoxRoomID.Text = RoomID.ToString();
            this.textBoxRoomName.Text = room.BaseInfo.RoomName;
            this.textBoxNotice.Text = room.BaseInfo.Notice;
            this.textBoxRemark.Text = room.BaseInfo.Remark;
            this.textBoxCreateUserID.Text = room.BaseInfo.CreateUserID.ToString();
            this.textBoxRemarkName.Text = room.BaseInfo.RemarkName;
            this.radioAddCondition1.Checked = true;

            if (room.BaseInfo.AddCondition == (byte)Ourmsg.Enum.AddCondition.NeedAuditing)
                this.radioAddCondition2.Checked = true;
            else if (room.BaseInfo.AddCondition == (byte)Ourmsg.Enum.AddCondition.RefuseALL)
                this.radioAddCondition3.Checked = true;

            foreach (var user in room.Users)
            {
                if (imageList1.Images[user.HeadID.ToString()] == null)
                    imageList1.Images.Add(user.HeadID.ToString(), Global.GetHeadImage(user.HeadID, ImageSize.P20X20));

                string name = user.UserName;
                if (name == null || name == string.Empty)
                    name = user.UserID.ToString();

                ListViewItem item = new ListViewItem(name);
                item.ImageKey = user.HeadID.ToString();
                item.Tag = user.UserID;
                ListViewItem.ListViewSubItem admin = new ListViewItem.ListViewSubItem();
                if (user.UserID == room.BaseInfo.CreateUserID)
                    admin.Text = "群主";//"管理员";// 
                else if (user.Admin)
                    admin.Text = "管理员";

                item.SubItems.Add(admin);
                ListViewItem.ListViewSubItem UserCard = new ListViewItem.ListViewSubItem();
                UserCard.Text = user.UserCard;
                item.SubItems.Add(UserCard);
                ListViewItem.ListViewSubItem UserLevel = new ListViewItem.ListViewSubItem();
                UserLevel.Text = user.UserLevel.ToString();
                item.SubItems.Add(UserLevel);
                ListViewItem.ListViewSubItem LastTalkDate = new ListViewItem.ListViewSubItem();
                LastTalkDate.Text = user.LastTalkDate;
                item.SubItems.Add(LastTalkDate);
                this.ListView1.Items.Add(item);
                if (user.UserID == room.BaseInfo.CreateUserID)
                {
                    ListViewSubEx sub = new ListViewSubEx();
                    sub.ShowImage(this.ListView1, item.Index, 1, imageList1, 0); 
                }
                else if (user.Admin)
                {
                    ListViewSubEx sub = new ListViewSubEx();
                    sub.ShowImage(this.ListView1, item.Index, 1, imageList1, 0); 
                }
            }

            setLabUsersCount();
            setLabManagersCount();
        }
        #endregion

        #region ListView 事件

        void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ListView1.SelectedItems.Count > 0)
                ListView1.SelectedItems[0].Focused = false;
        }

        private void ListView1_MouseMove(object sender, MouseEventArgs e)
        {
            SelectItem = ListView1.GetItemAt(e.X, e.Y) as ListViewItem;
            if (SelectItem == null)
            {
                panelLine.Visible = false;
                ToolStrip1.Visible = false;
                return;
            }
             
            if (SelfIsManager)//如果是管理员
            {
                tsButEditCard.Visible = true;

                if (Global.MsgClient.MyAuth.UserID  == GetSelectedItemUserID())//如果是自己或群主
                {
                    tsButSetManager.Visible = false;
                    tsButDelManager.Visible = false;
                    tsButDelUser.Visible = false;
                }
                else
                {
                    RoomUser user = Global.GetRoomUser(RoomID, GetSelectedItemUserID());
                    if (user == null) return;
                    if (Global.IsRoomCreater(RoomID, Global.MsgClient.MyAuth.UserID))
                    {
                        if (user.Admin)
                        {
                            tsButSetManager.Visible = false;
                            tsButDelManager.Visible = true;
                        }
                        else
                        {
                            tsButDelManager.Visible = false;
                            tsButSetManager.Visible = true;
                        }
                    }
                    tsButDelUser.Visible = true;
                }

                ToolStrip1.Visible = true;
                ToolStrip1.Left = ListView1.Left + SelectItem.Bounds.Width;
                ToolStrip1.Top = ListView1.Top + SelectItem.Position.Y;
            }
            else
                ToolStrip1.Visible = false;
             
            panelLine.Visible = true;
            panelLine.Left = ListView1.Left;
            panelLine.Width = SelectItem.Bounds.Width;
            panelLine.Top = ListView1.Top + SelectItem.Position.Y + SelectItem.Bounds.Height;
        }
        #endregion
         
        #region 删除用户按键事件
        void tsButDel_Click(object sender, EventArgs e)
        {
            if (SelectItem!=null )
            {
                if (IsCreate())//如果是群主,不能进行设置
                {
                    Global.ShowMessage("不能对群主进行操作！"); 
                    return;
                }

                RoomUser u = Global.GetRoomUser(RoomID, GetSelectedItemUserID());
                if (Global.ShowYNCMessage("确定要删除用户  " + u.UserName + "(" + u.UserID + ")  吗？" ) == System.Windows.Forms.DialogResult.Yes)
                {
                    RoomUser  ru = new  RoomUser();
                    ru.UserID = u.UserID;
                    OnCreateMsgAfter(Ourmsg.Enum.CommandType.DelRoomUser,ru);//触发删除用户事件
                }
            }
        }
        #endregion

        #region 设置管理员
        void tsButSetManager_Click(object sender, EventArgs e)
        {
            if (SelectItem != null)
            {
                if (IsCreate())//如果是群主,不能进行设置
                {
                    Global.ShowMessage("不能对群主进行操作！"); 
                    return;
                }

                RoomUser u = Global.GetRoomUser(RoomID, GetSelectedItemUserID());
                if (Global.ShowYNCMessage("确定要将用户  " + u.UserName + "(" + u.UserID + ")  设置为管理员吗？") == System.Windows.Forms.DialogResult.Yes)
                { 
                    RoomUser  ru = new  RoomUser();
                    ru.UserID = u.UserID;
                    ru.Admin = true;
                    OnCreateMsgAfter(Ourmsg.Enum.CommandType.SetRoomManger,ru);//触发设置管理
                }
            }
        }

        void tsButDelManager_Click(object sender, EventArgs e)
        {
            if (SelectItem != null)
            {
                if (IsCreate())//如果是群主,不能进行设置
                {
                    Global.ShowMessage("不能对群主进行操作！");
                    return;
                }

                RoomUser u = Global.GetRoomUser(RoomID, GetSelectedItemUserID());
                if (Global.ShowYNCMessage("确定要将管理员  " + u.UserName + "(" + u.UserID + ")  设置为普通成员吗？") == System.Windows.Forms.DialogResult.Yes)
                {
                    RoomUser ru = new RoomUser();
                    ru.UserID = u.UserID;
                    ru.Admin = false;
                    OnCreateMsgAfter(Ourmsg.Enum.CommandType.SetRoomManger,ru);//触发设置管理
                }
            }
        }
        #endregion

        #region 获取鼠标选中用户
        /// <summary>
        /// 获取鼠标选中用户是否群主
        /// </summary>
        /// <returns></returns>
        private bool IsCreate()
        {
            var user = Global.GetRoomUser(RoomID, GetSelectedItemUserID());
            if (user == null)
                return false;
            ExRoom room = Global.GetRoom(RoomID);
            if (room == null) 
                return false;
            if (user.UserID == room.BaseInfo.CreateUserID)
                return true;
            return false;
        }

        /// <summary>
        /// 获得选中的用户帐号
        /// </summary>
        /// <returns></returns>
        private UInt32 GetSelectedItemUserID()
        {
            if (SelectItem != null)
            {
                return Convert.ToUInt32(SelectItem.Tag);
            }
            else
                return 0;
        }
      
        /// <summary>
        /// 判断选中用户是否群管理员
        /// </summary>
        /// <returns></returns>
        private bool IsAdmin()
        {
            var roomUser = Global.GetRoomUser(RoomID , GetSelectedItemUserID());
            if (roomUser == null)
                return false;

            return roomUser.Admin;
        }
        #endregion

        #region 显示邀请用户加入群窗体
        private void showFormInviteFriends()
        {
            if (formInviteFriends == null || formInviteFriends.IsDisposed)
            {
                formInviteFriends = new FormInviteFriends();
                foreach (ListViewItem item in ListView1.Items)
                    formInviteFriends.AddRoomExsitUser(Convert.ToUInt32(item.Tag));
                formInviteFriends.FormClosing += (s, e) =>
                    {
                        var invitedUser = formInviteFriends.GetInvitedUsersID();
                        if (invitedUser != null && invitedUser.Length > 0)
                            Global.MsgClient.InviteAddRoom(RoomID, invitedUser);
                    };
            }
            formInviteFriends.Show();
            formInviteFriends.Activate();
        }
        #endregion

        #region 设置群用户管理员
        /// <summary>
        /// 设置群用户管理员
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="isManager"></param>
        public void SetRoomManager(UInt32 userID,bool isManager)
        {
            foreach(ListViewItem item in ListView1.Items)
                if (Convert.ToUInt32(item.Tag) == userID)
                {
                    if (isManager)
                    {
                        ListViewSubEx sub = new ListViewSubEx();
                        sub.ShowImage(this.ListView1, item.Index, 1, imageList1, 0);
                        item.SubItems[1].Text = "管理员"; 
                    }
                    else
                    {
                        ListViewSubEx sub = new ListViewSubEx();
                        sub.ShowImage(this.ListView1, item.Index, 1, imageList1,-1);
                        item.SubItems[1].Text = ""; 
                    }
                    setLabManagersCount();//设置显示管理员数
                    return;
                }
        }
        #endregion

        #region 设置群用户名片
        /// <summary>
        /// 设置群用户名片
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="userCard"></param>
        public void SetRoomUserCard(UInt32 userID, string userCard)
        {
            foreach (ListViewItem item in ListView1.Items)
                if (Convert.ToUInt32(item.Tag) == userID)
                {
                    if (userCard == null) userCard = "";
                    item.SubItems[2].Text = userCard;
                    return;
                }
        }
        #endregion

        #region 设置群基本信息
        /// <summary>
        /// 设置群基本信息
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="userCard"></param>
        public void SetRoomBaseInfo(RoomBaseInfo roomBaseInfo)
        {
            this.Text = string.Format("{0}({1})群信息",roomBaseInfo.RoomName ,RoomID);
           // Global.ShowMessage("群信息已更新！");
        }
        #endregion

        #region 删除群用户
        /// <summary>
        /// 删除群用户
        /// </summary>
        /// <param name="userID"></param>
        public void DelRoomUser(UInt32 userID )
        { 
            foreach (ListViewItem item in ListView1.Items)
                if (Convert.ToUInt32(item.Tag) == userID)
                {
                    ListView1.Items.Remove(item);
                    setLabUsersCount();
                    return;
                }
        }
        #endregion

        #region 设置显示成员数
        /// <summary>
        /// 设置显示成员数
        /// </summary>
        void setLabUsersCount()
        {
            labUsersCount.Text = string.Format("{0}/500 人",ListView1.Items.Count);
        }
        #endregion

        #region 设置显示管理员数
        /// <summary>
        /// 设置显示管理员数
        /// </summary>
        void setLabManagersCount()
        {
            int count = 0;
            foreach (ListViewItem item in ListView1.Items)
            {
                var u = Global.GetRoomUser(RoomID, Convert.ToUInt32(item.Tag));
                if (u != null && u.Admin)
                    count++;
            }
            labManagersCount.Text = string.Format("{0}/15 人", count);
        }
        #endregion

    }
}
