using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using GoodLuck.Properties;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace GoodLuck
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            if (!Directory.Exists(Application.StartupPath + "\\Head"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\Head");
            }
            if (!Directory.Exists(Application.StartupPath + "\\Luck"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\Luck");
            }
        }
        private bool m_bLucking=false;
        private bool m_bStart = false;
        private Options m_options = null;
        private List<KeyValuePair<string, Image>> m_listUsers = new List<KeyValuePair<string, Image>>();

       /// <summary>
       /// MCI 多媒体数据接口初始化
       /// </summary>
        public static uint SND_ASYNC = 0x0001;  // play asynchronously 
        public static uint SND_FILENAME = 0x00020000; // name is file name
        [DllImport("winmm.dll")]
        public static extern uint mciSendString(string lpstrCommand, 
        string lpstrReturnString, uint uReturnLength, uint hWndCallback);


        /// <summary>
        /// 开始按钮，点击自动隐藏，开始播放抽奖音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonStart_Click(object sender, EventArgs e)
        {
            buttonStart.Visible = false;
            this.m_bStart = true;
            timerPicture.Enabled = true;
            m_bLucking = true;

            mci("bv.mp3");
        }

        private void mci(string e)
        {
            mciSendString(@"close temp_alias", null, 0, 0);
            mciSendString(@"open " + "\""+ e + "\"" + " alias temp_alias", null, 0, 0);
            mciSendString("play temp_alias  repeat", null, 0, 0);
        }

        /// <summary>
        /// 读取image文件夹文件
        /// </summary>
        private void DisplayPicture()
        {
            if (m_listUsers.Count == 0)
            {
                timerPicture.Enabled = false;
                //winner文件夹为空 提示所有人中奖 并播放音乐
                mci("allwin.mp3");
                MessageBox.Show("所有人都已经中奖");
            }
            else
            {
                Random random = new Random();//随机
                int a = random.Next(0, m_listUsers.Count);
                pictureBoxHead.Image = m_listUsers[a].Value;
                pictureBoxHead.Tag = m_listUsers[a].Key;
                pictureBoxHead.SizeMode = PictureBoxSizeMode.CenterImage;
            }
        }

        private List<KeyValuePair<string, Image>> LoadUsers()
        {
            List<KeyValuePair<string, Image>> lsUsers = new List<KeyValuePair<string, Image>>();
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Head\\");
            FileInfo[] fiHeads = di.GetFiles("*.jpg");
            foreach(FileInfo fi in fiHeads)
            {
                KeyValuePair<string, Image> kv = new KeyValuePair<string, Image>(fi.FullName,Image.FromFile(fi.FullName));
                lsUsers.Add(kv);
            }
            return lsUsers;
        }

        /// <summary>
        /// 窗体载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {

            if (File.Exists(Application.StartupPath + "\\bd.jpg"))
            {
                Image ig = Image.FromFile(Application.StartupPath + "\\bd.jpg", true);
                this.BackgroundImage = ig;
            }  

            int w = this.ClientRectangle.Width - buttonStart.Width;
            int h = this.ClientRectangle.Height - buttonStart.Height;
            buttonStart.Location = new Point(w / 2, h / 2);


            int w2 = this.ClientRectangle.Width - labelTitle.Width;
            int h2 = this.ClientRectangle.Height - labelTitle.Height;
            this.labelTitle.Location = new Point(w2 / 2, 30);
            this.labelTitle.ForeColor = Color.Red;
            this.labelTitle.BackColor = Color.Transparent;
            m_listUsers = LoadUsers();
            m_options = new Options(this);
            m_options.Show();
        }
        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PicTimer_Tick(object sender, EventArgs e)
        {
            DisplayPicture();
        }
        /// <summary>
        /// 定时器开关
        /// </summary>
        private void Judge()
        {
            if (m_bLucking == true)
            {
                timerPicture.Enabled = false;
                m_bLucking = false;
                //中奖后音乐
                mci("win.mp3");
                mciSendString(@"close temp_alias", null, 0, 0);
                mciSendString(@"open " + "win.mp3" + " alias temp_alias", null, 0, 0);
                mciSendString("play temp_alias", null, 0, 0);

                //中奖图片移动到winner文件夹
                if (m_listUsers.Count  == 0)
                {
                    mci("allwin.mp3");
                    MessageBox.Show(this,"所有人都已经中奖");
                }
                else
                {
                    string strOrgF = pictureBoxHead.Tag as string;
                    int nIx = strOrgF.LastIndexOf('\\');
                    if(nIx == -1)
                    {
                        MessageBox.Show("文件异常");
                        return;
                    }
                    string strName = strOrgF.Substring(nIx + 1);
                    string strLuckName = Application.StartupPath + "\\Luck\\" + this.labelTitle.Text + "_" + strName;

                    if (File.Exists(strLuckName))
                    {
                        new FileInfo(strLuckName).Delete();
                    }

                    try
                    {
                        File.Copy(strOrgF, strLuckName);
                    }
                    catch (Exception e)
                    {
                        //mci("allwin.mp3");
                        MessageBox.Show(e.Message);
                    }

                    List<KeyValuePair<string, Image>> newLsUsers = new List<KeyValuePair<string, Image>>();
                    foreach(KeyValuePair<string, Image> ls in m_listUsers)
                    {
                        if(ls.Key != strOrgF)
                        {
                            newLsUsers.Add(ls);
                        }
                    }
                    m_listUsers = newLsUsers;
                }

            }
            else
            {
                //回归背景音乐
                timerPicture.Enabled = true;
                m_bLucking = true;
                mci("bv.mp3");
            }

        }
        //胜利人员列表
        private void OpenOptions()
        {
            if(m_options.IsDisposed)
            {
                m_options = new Options(this);
                m_options.Show();
            }
            else
             m_options.Show();
        }
        //单击抽奖
       private void pictureBox1_Click(object sender, EventArgs e)
        {         
           Judge();
        }
      
        private void Form1_Click(object sender, EventArgs e)
        {         
         
            Judge();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Enter://回车抽奖
                case Keys.Space:
                    Judge();
                    return true;
                case Keys.A://A 调用胜利人员列表
                    OpenOptions();
                    break;
                case Keys.X:
                    this.Close();
                    break;
                case Keys.Q:
                    CreateImgByName();
                    break;
                case Keys.T://for test
                   // MessageBox.Show(GetFileCount(Application.StartupPath + "\\Head\\", "刘*").ToString());
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        public void UpdateTitle(string msg)
        {
           
            this.labelTitle.Text = msg;
        }

        public void ReloadUsers()
        {
            m_listUsers = LoadUsers();
        }

        private void pictureBoxHead_Click(object sender, EventArgs e)
        {
            if (!this.m_bStart)
                return;
            Judge();
        }

        private void Main_Click(object sender, EventArgs e)
        {
            if (!this.m_bStart)
                return;
            Judge();
        }

        private void Main_Resize(object sender, EventArgs e)
        {
            int w = this.ClientRectangle.Width - buttonStart.Width;
            int h = this.ClientRectangle.Height - buttonStart.Height;
            buttonStart.Location = new Point(w / 2, h / 2);


            int w2 = this.ClientRectangle.Width - labelTitle.Width;
            int h2 = this.ClientRectangle.Height - labelTitle.Height;
            this.labelTitle.Location = new Point(w2 / 2, 30);
        }
        

        //根据名字清单，生成名字图片
        private void CreateImgByName()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            dlg.InitialDirectory = Application.StartupPath;
            dlg.Title = "请选择名字清单";
            dlg.RestoreDirectory = true;
            dlg.Multiselect = false;

            if (dlg.ShowDialog() != DialogResult.OK)
                return;

            StreamReader myStream = new StreamReader(dlg.FileName);
            List<string> lsNames = new List<string>();
            string text;
            if (myStream != null)
            {
                do
                {
                    text = myStream.ReadLine();
                    if (text != null && !string.IsNullOrEmpty(text))
                    {
                        lsNames.Add(text);
                    }
                } while (text != null);
                myStream.Close();
            }

            foreach (string strName in lsNames)
            {
                try
                {
                    string strHeadName = Application.StartupPath + "\\Head\\" + strName + ".jpg";

                    if (File.Exists(strHeadName))
                        File.Delete(strHeadName);

                    Bitmap image = new Bitmap(400, 300);
                    Graphics g = Graphics.FromImage(image);
                    g.Clear(Color.White);

                    //Font(字体 大小 粗细
                    Font font = new System.Drawing.Font("宋体", 64, FontStyle.Bold);
                    //LinearGradientBrush的参数是画的图像,起始颜色,简便的终止颜色,粗细,true
                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Black, 0.0f, true);
                    if (strName.Length == 1)
                        g.DrawString(strName, font, brush, 156, 110);//文本 字体 颜色 起始位置x 起始位置y
                    else if (strName.Length == 2)
                        g.DrawString(strName, font, brush, 110, 110);//文本 字体 颜色 起始位置x 起始位置y
                    else if (strName.Length == 3)
                        g.DrawString(strName, font, brush, 60, 110);//文本 字体 颜色 起始位置x 起始位置y        
                    else if (strName.Length == 4)
                        g.DrawString(strName, font, brush, 26, 110);//文本 字体 颜色 起始位置x 起始位置y
                    else
                        g.DrawString(strName, font, brush, 0, 110);//文本 字体 颜色 起始位置x 起始位置y
                    image.Save(strHeadName, ImageFormat.Jpeg);
                    
                    g.Dispose();
                    
                    image.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }

            MessageBox.Show("生成任务完成");
        }

        private int GetFileCount(string strPath,string strP)
        {          
            string[] fiHeads = Directory.GetFiles(strPath, strP);
            return fiHeads == null ? 0 : fiHeads.Length;
        }
    }
}
