using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MyQQ
{
    /// <summary>
    /// (ChatForm)聊天窗体中的相关功能
    /// </summary>
    public partial class ChatForm : Form
    {
        int x = 0;
        int y = 0;
        int i = 0;

        public int friendId;

        //未读消息的Id号
        string messageIdsString = "";

        //读取的相应的消息
        string message = "";

        //读取的好友的昵称
        string nickName = "";

        //读取自己的昵称
        string nickName1 = "";

        DataBase mydatabase = new DataBase();

        public ChatForm()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult result1 = MessageBox.Show("是否真的要关闭MyQQ聊天窗体？", "关闭提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

            if (result1 == DialogResult.OK)
            {
                this.Close();
            }
        }

        //更改皮肤的代码
        public void ShowSkin()
        {
            int i = 0;
            string sql = string.Format("select skinId from Users where Id={0}", UserHelper.Loginld);
            try
            {
                SqlDataReader dataReader = mydatabase.GetDataReader(sql);
                if (dataReader.Read())
                {
                    i = Convert.ToInt32(dataReader["skinId"]);
                }
                dataReader.Close();

                if (i == 1)
                {
                    this.skinEngine.SkinFile = "Wave.ssk";
                }
                else if (i == 2)
                {
                    this.skinEngine.SkinFile = "WaveColor1.ssk";
                }
                else if (i == 3)
                {
                    this.skinEngine.SkinFile = "WaveColor1.ssk";
                }
                else if (i == 4)
                {
                    this.skinEngine.SkinFile = "SportsBlack.ssk";
                }
                else if (i == 5)
                {
                    this.skinEngine.SkinFile = "SportsBlue.ssk";
                }
                else if (i == 6)
                {
                    this.skinEngine.SkinFile = "SportsCyan.ssk";
                }
                else if (i == 7)
                {
                    this.skinEngine.SkinFile = "SportsGreen.ssk";
                }
                else
                {
                    this.skinEngine.SkinFile = "MP10.ssk";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
        private void ChatForm_Load(object sender, EventArgs e)
        {
            ShowSkin();

            try
            {
                string sql2 = string.Format("select U.Id,NickName,FaceId,Friendbeizhu,UserState from Users as U inner join Friends as F on U.Id=F.FriendId where F.FriendId={0} and F.HostId={1}", friendId,Convert.ToInt32(UserHelper.Loginld));

                SqlDataReader dataReader1 = mydatabase.GetDataReader(sql2);
                {
                    if (dataReader1.Read())
                    {
                        int faceId = 0;

                        int id = Convert.ToInt32(dataReader1["Id"]);

                        if (dataReader1["Friendbeizhu"] is DBNull)
                        {
                            nickName = dataReader1["NickName"].ToString();
                        }
                        else 
                        {
                            nickName = dataReader1["Friendbeizhu"].ToString();
                        }
                        if (dataReader1["FaceId"] is DBNull)
                        {
                            faceId = 0;
                        }
                        else
                        {
                            faceId = (int)dataReader1["FaceId"];
                        }

                        if (Convert.ToInt32(dataReader1["UserState"]) == 1)
                        {
                            picFriendFace.Image = ilFriendFace.Images[faceId];
                        }
                        else 
                        {
                            picFriendFace.Image = ilFriendFace.Images[73];
                        }
                        lblFriendName.Text = string.Format("{0}({1})", nickName, id);
                        this.Text = string.Format("与{0}聊天中", nickName);
                    }

                    dataReader1.Close();
                }               

                string sql3 = string.Format("select Id,Message,MessageTime from Messages where FromUserId ={0} and ToUserId ={1} and MessageTypeId =1 and MessageState =0", friendId, UserHelper.Loginld);

                SqlDataReader dataReader2 = mydatabase.GetDataReader(sql3);

                if (dataReader2.HasRows)
                {
                    while (dataReader2.Read())
                    {
                        messageIdsString += Convert.ToString(dataReader2["Id"]) + "_";

                        //读取未读的消息
                        message = Convert.ToString(dataReader2["Message"]);

                        //显示未读的消息
                        lblMessages.Text += string.Format("{0} {1}\n{2}\n", nickName, Convert.ToString(dataReader2["MessageTime"]), message);
                    }

                    dataReader2.Close();
                }

                if (messageIdsString.Length > 0)
                {
                  messageIdsString.Remove(messageIdsString.Length - 1);
                }

                string[] messageIds = messageIdsString.Split('_');

                //更新聊天消息的状态的SQL语句
                string sql4 = "update Messages set MessageState =1 where Id =";

                //执行更新的最终的SQL语句
                string updateSql;


                foreach (string id in messageIds)
                {
                    if (id != "")
                    {
                        //补充完整的SQL语句
                        updateSql = sql4 + id;

                        int result = mydatabase.ExecuteSQL(sql4);
                    }
                }
                string sql7 = string.Format("select NickName from Users where Id ={0}", UserHelper.Loginld);
               
                SqlDataReader datareader = mydatabase.GetDataReader(sql7);
                if (datareader.Read())
                {
                    nickName1 = (string)datareader["NickName"];
                }
                datareader.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
                  }

        //当单击“发送”按钮时，将编辑的信息先插入聊天信息表中，然后再显示在聊天面板中
        private void btnToFriend_Click(object sender, EventArgs e)
        {
            if (txtToFriend.Text.Trim() == "")
            {
                MessageBox.Show("发送信息不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                try
                {
                    string sql5 = string.Format("insert into Messages (FromUserId,ToUserId,Message,MessageTypeId,MessageState,MessageStation) values ({0},{1},'{2}',{3},{4},0)", UserHelper.Loginld, friendId, Convert.ToString(txtToFriend.Text.Trim()), 1, 0);

                    SqlCommand command2 = new SqlCommand(sql5);

                    mydatabase.ExecuteSQL(sql5);
                    string sql6 = string.Format("select MessageTime from Messages where Message ='{0}'", txtToFriend.Text.Trim());
                    string messageTime = mydatabase.GetScalar(sql6).ToString();
                    lblMessages.Text += string.Format("{0} {1}\n{2}\n", nickName1, messageTime, txtToFriend.Text.Trim());
                    pnlFromFriend.AutoScrollPosition = new Point(pnlFromFriend.AutoScrollPosition.X, lblMessages.Height);
                }
                catch
                {
                    string message = string.Format("由于系统问题，你不能发送英文\n状态下的单引号！！");
                    MessageBox.Show(message,"提示");
                }
                finally
                {
                    txtToFriend.Text = "";
                    txtToFriend.Focus();
                }
            }
        }

        //按Enter键发送信息
        private void tismEnter_Click(object sender, EventArgs e)
        {
            this.AcceptButton = btnToFriend;

            tsmiSned.Visible = true;

            tismEnter.Visible = false;
        }

        //按发送键发送信息
        private void tsmiSned_Click(object sender, EventArgs e)
        {
            this.AcceptButton = null;

            tsmiSned.Visible = false;

            tismEnter.Visible = true;
        }

        //设置字体
        private void tsmiFont_Click(object sender, EventArgs e)
        {
            fontDialog.ShowDialog();
            txtToFriend.Font = fontDialog.Font;
            lblMessages.Font = fontDialog.Font;
        }

        //设置字体颜色
        private void tsmiFontColor_Click(object sender, EventArgs e)
        {
            colorDialog.ShowDialog();
            txtToFriend.ForeColor = colorDialog.Color;
            lblMessages.ForeColor = colorDialog.Color;
        }

        //读取好友信息
        private void trMessage_Tick(object sender, EventArgs e)
        {
            string sql3 = string.Format("select Id,Message,MessageTime from Messages where FromUserId ={0} and ToUserId ={1} and MessageTypeId =1 and MessageState =0", friendId, UserHelper.Loginld);

            SqlDataReader dataReader2 = mydatabase.GetDataReader(sql3);

            if (dataReader2.HasRows)
            {
                while (dataReader2.Read())
                {
                    //记录未读消息的Id
                    messageIdsString += Convert.ToString(dataReader2["Id"]) + "_";

                    //读取未读的消息
                    message = Convert.ToString(dataReader2["Message"]);

                    //显示未读的消息
                    lblMessages.Text += string.Format("{0} {1}\n{2}\n", nickName, Convert.ToString(dataReader2["MessageTime"]), message);
                }

                dataReader2.Close();
            }

           
            if (messageIdsString.Length > 0)
            {
                messageIdsString.Remove(messageIdsString.Length - 1);
            }
            //分割出每个未读消息的Id，并将其赋给一个数组
            string[] messageIds = messageIdsString.Split('_');

            //更新聊天消息的状态的SQL语句
            string sql4 = "update Messages set MessageState =1 where Id =";

            //执行更新的最终的SQL语句
            string updateSql;

            foreach (string id in messageIds)
            {
                if (id != "")
                {
                    updateSql = sql4 + id;

                    int result = mydatabase.ExecuteSQL(updateSql);
                }
            }
            string sql2 = string.Format("select U.Id,NickName,FaceId,Friendbeizhu,UserState from Users as U inner join Friends as F on U.Id=F.FriendId where F.FriendId={0} and F.HostId={1}", friendId, Convert.ToInt32(UserHelper.Loginld));

            SqlDataReader dataReader1 = mydatabase.GetDataReader(sql2);

            if (dataReader1.HasRows)
            {
                if (dataReader1.Read())
                {
                    int faceId = 0;

                    int id = Convert.ToInt32(dataReader1["Id"]);
                    if (dataReader1["Friendbeizhu"] is DBNull)
                    {
                        nickName = dataReader1["NickName"].ToString();
                    }
                    else
                    {
                        nickName = dataReader1["Friendbeizhu"].ToString();
                    }
                    if (dataReader1["FaceId"] is DBNull)
                    {
                        faceId = 0;
                    }
                    else
                    {
                        faceId = (int)dataReader1["FaceId"];
                    }
                    if (Convert.ToInt32(dataReader1["UserState"]) == 1)
                    {
                        picFriendFace.Image = ilFriendFace.Images[faceId];
                    }
                    else
                    {
                        picFriendFace.Image = ilFriendFace.Images[73];
                    }

                    lblFriendName.Text = string.Format("{0}({1})", nickName, id);
                    this.Text = string.Format("与{0}聊天中", nickName);
                }

                dataReader1.Close();
            }
        }

        //察看聊天记录的返回键事件
        private void tsmiReturn_Click(object sender, EventArgs e)
        {
            pnlMessag3.Visible = false;

            tsmiReturn.Visible = false;

            pnlFromFriend.Visible = true;

            lblMessage.Text = "";

            tsmiMesssage.Visible = true;
        }

        //查看聊天记录的处理事件
        private void tsmiMesssage_Click(object sender, EventArgs e)
        {
            tsmiMesssage.Visible = false;

            pnlMessag3.Visible = true;

            tsmiReturn.Visible = true;

            pnlFromFriend.Visible = false;

            string sql3 = string.Format("select [Message],MessageTime,FromUserId from Messages  where (ToUserId={0} and MessageTypeId =1 and MessageState =1  and MessageStation=0 and FromUserId={1}) or (ToUserId={2} and MessageTypeId =1 and MessageState =1 and MessageStation=0 and FromUserId={3})", friendId, UserHelper.Loginld, UserHelper.Loginld,friendId);

            SqlDataReader dataReader2 = mydatabase.GetDataReader(sql3);

            if (dataReader2.HasRows)
            {
                while (dataReader2.Read())
                {
                    message = Convert.ToString(dataReader2["Message"]);

                    if (Convert.ToInt32(dataReader2["FromUserId"]) == friendId)
                    {
                        lblMessage.Text += string.Format("{0} {1}\n{2}\n", nickName, Convert.ToString(dataReader2["MessageTime"]), message);
                    }
                    else 
                    {
                        lblMessage.Text += string.Format("{0} {1}\n{2}\n", nickName1, Convert.ToString(dataReader2["MessageTime"]), message);
                    }
                   
                }

                dataReader2.Close();
            }

        }

        /// <summary>
        /// 抖动窗体事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void msDoudong_Click(object sender, EventArgs e)
        {
            int state = 0;
            string sql1 = string.Format("select UserState from Users where Id={0} ",friendId);

            SqlDataReader datare = mydatabase.GetDataReader(sql1);
            if (datare.Read()) 
            {
                state = Convert.ToInt32(datare["UserState"]);
            }
            datare.Close();

            if (state != 1)
            {
                string message = string.Format("你的好友不在线或隐身，你暂时不能\n发送窗口抖动！！！");

                MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else 
            {
                trdoudong1.Enabled = true;

                trdoudong2.Enabled = true;

                string sql = string.Format("insert into Messages (FromUserId,ToUserId,MessageTypeId,MessageState,MessageX,MessageY) values ({0},{1},{2},{3},{4},{5})", UserHelper.Loginld, friendId, 3, 0, 80, 38);

                int reslut = mydatabase.ExecuteSQL(sql);
            }
           
        }

        private void trdoudong1_Tick(object sender, EventArgs e)
        {
            i++;

            //当计时控件计时到2400毫秒时，停止所有抖动时间控件
            if (i>=24) 
            {
                //停止计时控件
                trdoudong1.Enabled=false;

                //停止自己抖动窗体地事件
                trdoudong2.Enabled=false;


                //停止朋友抖动窗体的事件
                trdoudong4.Enabled = false;

                i = 0;
            }
        }

       /// <summary>
       ///抖动自己的窗体事件控件
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void trdoudong2_Tick(object sender, EventArgs e)
        {
            if (this.Location.X == 90 && this.Location.Y == 50)
            {
                this.Location = new Point(80,38);
            }
            else 
            {
                this.Location = new Point(90, 50);
            }
        }
        /// <summary>
        /// 查询朋友是否发送抖动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trdoudong3_Tick(object sender, EventArgs e)
        {
            string sql = string.Format("select MessageX,MessageY from Messages where FromUserId={0} and ToUserId={1} and MessageTypeId=3 and MessageState=0", friendId, Convert.ToInt32(UserHelper.Loginld));

            SqlDataReader datareader = mydatabase.GetDataReader(sql);
            while (datareader.Read())
            {
                if (!(datareader["MessageX"] is DBNull) && !(datareader["MessageY"] is DBNull))
                {
                    trdoudong1.Enabled = true;
                    trdoudong4.Enabled = true;
                }
                x = Convert.ToInt32(datareader["MessageX"]);
                y = Convert.ToInt32(datareader["MessageY"]);

            }

            datareader.Close();

            string sql1 = string.Format("update Messages set MessageState=1 where FromUserId={0} and ToUserId={1} and MessageTypeId=3", friendId, Convert.ToInt32(UserHelper.Loginld));

            int resulte = mydatabase.ExecuteSQL(sql1);
        }

        /// <summary>
        /// 朋友发送的窗体抖动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trdoudong4_Tick(object sender, EventArgs e)
        {
            //当窗体时最小化时变成最大化
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }

            //定义窗体抖动的坐标
            if (this.Location.X == 90 && this.Location.Y == 50)
            {
                this.Location = new Point(x, y);
            }
            else
            {
                this.Location = new Point(90, 50);
            }
        }
    }
}