using BLL;
using DAL;
using Helper;
using Model;
using Sunny.UI;
using SunnyMusic.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Update;

namespace SunnyMusic
{
    public enum PlayMode { 顺序播放 = 0, 随机播放 = 1, 列表循环 = 2, 单曲循环 = 3 }
    public partial class FrmMain : UIForm
    {
        public FrmMiniPlayer MiniPlayer { get; set; }
        /// <summary>
        /// 主窗体构造
        /// </summary>
        public FrmMain(Music s = null)
        {
            InitializeComponent();
            MiniPlayer = new FrmMiniPlayer();
            MiniPlayer.MyParent = this;
            MusicHelper.MainForm = this;
            GetAssembly();
            player.URL = "";
            if (s != null)
                CurrentMusic = s;
        }
        #region 属性与字段集
        /// <summary>
        /// 播放模式
        /// </summary>
        public PlayMode Mode
        {
            get { return (PlayMode)Settings.Default.播放模式; }
            set { Settings.Default.播放模式 = (int)value; }
        }
        /// <summary>
        /// 搜索结果
        /// </summary>
        public List<Music> Result { get; set; }
        /// <summary>
        /// 获取或设置当前正在播放的歌曲
        /// </summary>
        public Music CurrentMusic
        {
            get { return this.Tag as Music; }
            set
            {
                this.Tag = value;
                Music s = value;
                if (s.ToString().Contains("遗憾迟香"))
                { throw new Exception("有内鬼,终止交易!"); }
                if (player.URL != s.Url)
                {
                    player.URL = s.Url;
                }
                Thread p = new Thread(PlayMusic);
                p.IsBackground = true;
                p.Start(s);
                lblInfo.Text = s.ToString();
                lblAlbum.Text = string.Format("{0}\n{1}\n{2}", s.Name, s.Artist, s.Album);
                MiniPlayer.lblInfo.Text = string.Format("{0}\n{1}", s.Name, s.Artist);
                Image pic = CurrentMusic.Love ? Properties.Resources.love : Properties.Resources.unlove;
                btnLove.BackgroundImage = pic;
                MiniPlayer.btnLove.BackgroundImage = pic;
                if (!playList.Items.Contains(s))
                { playList.Items.Add(s); }
            }
        }
        private void PlayMusic(object o)
        {
            try
            {
                Music s = o as Music;
                IsBusy = true;
                if (!HttpHelper.CheckUri(s.Url))
                {
                    MusicHelper h = new MusicHelper(s);
                    h.GetData();
                    s = h.MusicModel;
                }
                Thread t = new Thread(LoadPic);
                t.IsBackground = true;
                t.Start(s);
                player.URL = s.Url;
                LoadLrc(s.GetLrc());
                IsBusy = false;
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }

        }
        private void LoadPic(object o)
        {
            picMusic.Image = Properties.Resources.load;
            picAlbum.Image = Properties.Resources.load;
            MiniPlayer.picSong.Image = Properties.Resources.load;
            Music s = o as Music;
            Image pic = ImageHelper.GetImage(s.PicUrl);
            if (pic == null)
            { pic = Properties.Resources.logo; }
            picMusic.BackgroundImage = pic;
            picAlbum.BackgroundImage = pic;
            MiniPlayer.picSong.BackgroundImage = pic;
            MiniPlayer.picSong.Image = null;
            picAlbum.Image = null;
            picMusic.Image = null;
            //ChangeIcon(pic);
            //this.Invoke(new MyDel2(ChangeIcon), pic);
            GC.Collect();
        }
        /// <summary>
        /// 修改图标(不可用)
        /// </summary>
        /// <param name="pic"></param>
        //private void ChangeIcon(Image pic)
        //{
        //    this.Icon = ImageHelper.ImageToIcon(ImageHelper.ResizeImage(pic, new Size(32, 32)));
        //}
        //delegate void MyDel2(Image pic);

        /// <summary>
        /// 获取或设置当前歌词
        /// </summary>
        public Lyric CurrentLrc { get; set; }
        public int Index
        {
            get
            {
                for (int i = 0; i < playList.Items.Count; i++)
                {
                    if (playList.Items[i].Equals(CurrentMusic))
                    { return i; }
                }
                return 0;
            }
        }
        /// <summary>
        /// 搜索页码
        /// </summary>
        public int pn { get; set; }
        /// <summary>
        /// 播放进度
        /// </summary>
        public double Duration
        {
            get
            {
                return player.Ctlcontrols.currentPosition;
            }
            set
            {
                player.Ctlcontrols.currentPosition = value;
            }
        }
        /// <summary>
        /// 是否正在播放
        /// </summary>
        private bool Playing
        {
            get
            {
                bool flag = player.playState == WMPLib.WMPPlayState.wmppsPlaying;
                if (flag)
                {
                    btnPause.Image = Resources.pause;
                    MiniPlayer.btnPause.BackgroundImage = Resources.暂停;
                }
                else
                {
                    btnPause.Image = Resources.play;
                    MiniPlayer.btnPause.BackgroundImage = Resources.播放;
                }
                return flag;
            }
            set
            {
                tmrPlayer.Enabled = value;
                tmrLrc.Enabled = value;
            }
        }
        /// <summary>
        /// 显示或隐藏加载图标
        /// </summary>
        public bool IsBusy
        {
            set
            {
                picLoading.Visible = value;
                if (value)
                {
                    this.Cursor = Cursors.AppStarting;
                    tabControl.Cursor = Cursors.AppStarting;
                    dgvMusic.Cursor = Cursors.AppStarting;
                    foreach (TabPage item in tabControl.TabPages)
                    {
                        item.Cursor = Cursors.AppStarting;
                    }
                }
                else
                {
                    this.Cursor = Cursors.Default;
                    tabControl.Cursor = Cursors.Default;
                    dgvMusic.Cursor = Cursors.Default;
                    foreach (TabPage item in tabControl.TabPages)
                    {
                        item.Cursor = Cursors.Default;
                    }
                }
            }
        }
        #endregion
        #region 程序初始化与结束代码
        private void FrmMain_Load(object sender, EventArgs e)
        {
            SetDesign();
            LoadSettings();
            if (Settings.Default.问候语)
            { Welcome(); }
            if (Settings.Default.检查更新)
            { Update(); }
            LoadSources();
            LoadPlayList();
        }
        /// <summary>
        /// 问候语
        /// </summary>
        public void Welcome()
        {
            notify.ShowBalloonTip(10000, Settings.Default.title, Settings.Default.text, ToolTipIcon.Info);
        }

        public bool Update()
        {
            FrmUpdate.UpdateUrl = "http://" + MusicHelper.Ip + "/update.aspx";
            FrmUpdate f = new FrmUpdate(Program.Info);
            return f.ShowDialog() == DialogResult.Yes;
        }
        /// <summary>
        /// 加载音乐源
        /// </summary>
        public void LoadSources()
        {
            cboSource.Items.Clear();
            foreach (MusicSource item in DAL.Info.Sources)
            {
                if (item.Enabled)
                {
                    if (MusicHelper.Online)
                    {
                        if (item.SuppwotWeb)
                            cboSource.Items.Add(item);
                    }
                    else
                    {
                        if (item.SupportLocal)
                            cboSource.Items.Add(item);
                    }
                }
            }
            if (cboSource.Items.Count > 0)
            { cboSource.SelectedIndex = 0; }
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall)
            {
                goto end;
            }
            if (Settings.Default.退出显示提示)
            {
                FrmClose f = new FrmClose();
                f.Style = this.Style;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    if (f.rdo最小化托盘.Checked)
                    {
                        e.Cancel = true;
                        this.Hide();
                        Settings.Default.退出显示提示 = !f.chk不再提示.Checked;
                        chk退出时显示提示.Checked = !f.chk不再提示.Checked;
                        chk退出到托盘.Checked = f.rdo最小化托盘.Checked;
                        Settings.Default.退出到托盘 = f.rdo最小化托盘.Checked;
                        return;
                    }
                    else
                    {
                        Settings.Default.退出显示提示 = !f.chk不再提示.Checked;
                        chk退出时显示提示.Checked = !f.chk不再提示.Checked;
                        chk退出到托盘.Checked = f.rdo最小化托盘.Checked;
                        Settings.Default.退出到托盘 = f.rdo最小化托盘.Checked;
                        goto end;
                    }
                }
                else
                {
                    e.Cancel = true;
                    return;
                }
            }
            else
            {
                if (Settings.Default.退出到托盘)
                {
                    e.Cancel = true;
                    this.Hide();
                    return;
                }
            }
        end: SaveSettings();
            SavePlayList();
        }
        public void LoadPlayList()
        {
            List<Music> list = new List<Music>();
            try
            {
                playList.Items.Clear();
                list = Music.JsonToList(File.ReadAllText(Application.StartupPath + "\\playlist.json"));
                foreach (var item in list)
                {
                    playList.Items.Add(item);
                }
            }
            catch (Exception)
            { }
            try
            {
                lstLove.Items.Clear();
                list = Music.JsonToList(File.ReadAllText(Application.StartupPath + "\\love.json"));
                foreach (var item in list)
                {
                    lstLove.Items.Add(item);
                }
            }
            catch (Exception)
            { }
        }
        public void SavePlayList()
        {
            List<Music> list = new List<Music>();
            foreach (Music item in playList.Items)
            {
                list.Add(item);
            }
            File.Delete(Application.StartupPath + "\\playlist.json");
            File.WriteAllText(Application.StartupPath + "\\playlist.json",Music.ListToJson(list));
            list.Clear();
            foreach (Music item in lstLove.Items)
            {
                list.Add(item);
            }
            File.Delete(Application.StartupPath + "\\love.json");
            File.WriteAllText(Application.StartupPath + "\\love.json", Music.ListToJson(list));
        }
        public void LoadSettings()
        {
            MusicHelper.Path = Settings.Default.下载路径 == "\\" ? Application.StartupPath : Settings.Default.下载路径;
            txtPath.Text = Settings.Default.下载路径;
            chk问候语.Checked = Settings.Default.问候语;
            chk检查更新.Checked = Settings.Default.检查更新;
            txtIp.Text = Settings.Default.服务器地址;
            this.Opacity = Settings.Default.不透明度;
            chk边听边存.Checked = Settings.Default.边听边存;
            chk下载歌词.Checked = Settings.Default.下载歌词;
            chk下载封面.Checked = Settings.Default.下载封面;
            chk在线解析.Checked = Settings.Default.在线解析;
            txtSimilar.Text = Settings.Default.重新查找精确度.ToString();
            txtTimeout.Text = Settings.Default.超时时间.ToString();
            HttpHelper.TimeOut = Settings.Default.超时时间;
            txtNum.Text = Settings.Default.每页显示数量.ToString();
            player.settings.volume = Settings.Default.音量;
            trcVol.Value = Settings.Default.音量;
            trc不透明度.Value = (int)(this.Opacity * 100);
            this.Style = Settings.Default.主题;
            cbo主题.SelectedItem = Settings.Default.主题;
            HttpHelper.UseProxy = Settings.Default.使用代理;
            chkhttp代理.Checked = Settings.Default.使用代理;
            HttpHelper.Proxy = Settings.Default.http代理;
            txtProxy.Text = Settings.Default.http代理;
            txtFormat.Text = Settings.Default.文件命名格式;
            this.TopMost = Settings.Default.总在最前;
            chk总在最前.Checked = Settings.Default.总在最前;
            chk退出到托盘.Checked = Settings.Default.退出到托盘;
            chk退出时显示提示.Checked = Settings.Default.退出显示提示;
            chk迷你播放器.Checked = Settings.Default.迷你播放器;
            MiniPlayer.Visible = Settings.Default.迷你播放器;
        }
        public void SaveSettings()
        {
            Settings.Default.问候语 = chk问候语.Checked;
            Settings.Default.检查更新 = chk检查更新.Checked;
            Settings.Default.边听边存 = chk边听边存.Checked;
            Settings.Default.下载歌词 = chk下载歌词.Checked;
            Settings.Default.下载封面 = chk下载封面.Checked;
            Settings.Default.不透明度 = this.Opacity;
            Settings.Default.服务器地址 = txtIp.Text;
            Settings.Default.在线解析 = chk在线解析.Checked;
            Settings.Default.重新查找精确度 = Convert.ToDouble(txtSimilar.Text);
            Settings.Default.超时时间 = int.Parse(txtTimeout.Text);
            HttpHelper.TimeOut = int.Parse(txtTimeout.Text);
            Settings.Default.每页显示数量 = Convert.ToInt32(txtNum.Text);
            Settings.Default.总在最前 = this.TopMost;
            Settings.Default.主题 = this.Style;
            Settings.Default.使用代理 = HttpHelper.UseProxy;
            Settings.Default.http代理 = HttpHelper.Proxy;
            Settings.Default.文件命名格式 = txtFormat.Text;
            Settings.Default.退出到托盘 = chk退出到托盘.Checked;
            Settings.Default.退出显示提示 = chk退出时显示提示.Checked;
            Settings.Default.下载路径 = txtPath.Text;
            Settings.Default.迷你播放器 = MiniPlayer.Visible;
            Settings.Default.Save();
        }
        /// <summary>
        /// 获取关于信息
        /// </summary>
        public void GetAssembly()
        {
            this.labelProductName.Text = Program.AssemblyProduct;
            this.labelVersion.Text = String.Format("版本 {0}", Program.AssemblyVersion);
            this.labelCopyright.Text = Program.AssemblyCopyright;
            this.labelCompanyName.Text = Program.AssemblyCompany;
            this.textBoxDescription.Text = Program.AssemblyDescription;
        }
        #endregion
        #region 音乐加载

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtWord.Text) || txtWord.Text == empty)
            {
                UIMessageTip.ShowError("请输入关键字");
                return;
            }
            if (!bgwSearch.IsBusy)
            {
                //初始化页码
                pn = 1;
                //开始执行搜索线程
                SearchArgs ars = new SearchArgs(txtWord.Text.Trim(), pn, true);
                MusicSource source = (MusicSource)cboSource.SelectedItem;
                ars.Source = source.Value;
                bgwSearch.RunWorkerAsync(ars);
            }
            else
            {
                UIMessageTip.ShowError("当前有任务正在进行中");
            }
        }
        private void bgwSearch_DoWork(object sender, DoWorkEventArgs e)
        {
            IsBusy = true;
            try
            {
                SearchArgs ars = e.Argument as SearchArgs;
                if (ars.Cls)
                { Result = MusicHelper.Search(ars); }
                else { Result.AddRange(MusicHelper.Search(ars)); }
            }
            catch (Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
            }
            finally { IsBusy = false; }
        }
        private void bgwSearch_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                dgvMusic.AutoGenerateColumns = false;
                dgvMusic.DataSource = Music.ModelToTable(Result);
                this.ShowSuccessTip(string.Format("搜索完毕,共有{0}首歌", dgvMusic.RowCount));
            }
            catch (Exception)
            { }
        }
        delegate void MyDel(Music m);
        private void PlayVideo(Music m)
        {
            FrmVideo f = new FrmVideo(m.Url);
            f.Text = m.ToString();
            f.Icon = this.Icon;
            f.Show();
        }
        private void bgwPlay_DoWork(object sender, DoWorkEventArgs e)
        {
            IsBusy = true;
            try
            {
                Music s = LoadMusic(e.Argument);
                //播放歌曲
                if (s.IsVideo())
                {
                    this.Invoke(new MyDel(PlayVideo), s);
                }
                else { CurrentMusic = s; }
                if (chk边听边存.Checked)
                {
                    Download(s);
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message, 2000);
            }
            finally { IsBusy = false; }
        }
        private void bgwDown_DoWork(object sender, DoWorkEventArgs e)
        {
            IsBusy = true;
            try
            {
                Music s = LoadMusic(e.Argument);
                Download(s);
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message, 2000);
            }
            finally { IsBusy = false; }
        }
        private Music LoadMusic(object o)
        {
            Music s = new Music();
            if (o is Music)
            {
                s = o as Music;
            }
            if (o is ListBoxEx)
            {
                ListBoxEx lst = (ListBoxEx)o;
                s = lst.SelectedItem as Music;
            }
            if (o is UIDataGridView)
            {
                UIDataGridView dgv = (UIDataGridView)o;
                s = Music.FromDataGridView(dgv.SelectedRows[0]);
            }
            if (s == null)
            {
                throw new NullReferenceException("您未选中任何歌曲");
            }
            this.ShowInfoTip("正在获取音乐地址");
            //如果歌曲未被加载则加载歌曲
            if (s.PicId == "local")
            { s.Source = "Local"; }
            if (s.Artist == "遗憾迟香")
            { throw new Exception("有内鬼,终止交易!"); }
            MusicHelper h = new MusicHelper(s);
            if (!h.GetData())
            {
                //歌曲仍未加载成功,自动搜索其它音乐平台
                this.ShowInfoTip("未能解析出地址,自动搜索其它音乐平台");
                h.MusicModel = MusicHelper.ReSearch(s, 0.75);
            }
            return h.MusicModel;
        }
        private void Download(Music s)
        {
            this.ShowInfoTip("已开始后台下载");
            string path = Application.StartupPath;
            MusicHelper h = new MusicHelper(s);
            h.DownLoadAsync(path, notify);
        }
        private void bgwRefresh_DoWork(object sender, DoWorkEventArgs e)
        {
            IsBusy = true;
            try
            {
                CurrentMusic = LoadMusic(CurrentMusic);
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }
            finally { IsBusy = false; }
        }
        #endregion
        #region 窗体设计
        /// <summary>
        /// 加载窗体设计
        /// </summary>
        public void SetDesign()
        {
            //tabControl.SelectedIndex = 2;
            this.Style = UIStyle.Green;
            txtWord.Text = empty;
            Image pic = (Image)Properties.Resources.ResourceManager.GetObject(Mode.ToString(), null);
            btnPlayMode.BackgroundImage = pic;
            MiniPlayer.btnPlayMode.BackgroundImage = pic;
            txtWord.ForeColor = Color.FromArgb(173, 178, 181);
            notify.Icon = this.Icon;
            //TopControl(btnImportList, btnImportLove, btnExportList, btnExportLove, btnDeleteList, btnDeleteLove, btnClearList, btnClearLove);
            foreach (UIStyle item in Enum.GetValues(typeof(UIStyle)))
            {
                cbo主题.Items.Add(item);
            }
            cbo主题.SelectedIndex = 0;
        }
        private void TopControl(params Control[] ctrls)
        {
            foreach (var item in ctrls)
            {
                item.BringToFront();
            }
        }
        private void FrmMain_MouseDown(object sender, MouseEventArgs e)
        {
            Win32Helper.MoveWindow(this);
            //MyParent.Location = this.Location;
        }
        #endregion
        #region 播放器相关
        /// <summary>
        /// 加载歌词
        /// </summary>
        /// <param name="lrc">歌词对象</param>
        public void LoadLrc(Lyric lrc)
        {
            lrcView.Items.Clear();
            MiniPlayer.lrcView.Items.Clear();
            if (lrc == null)
            { return; }
            CurrentLrc = lrc;
            //清除显示歌词的listBox
            if (lrc == null)
            {
                lrcView.Tag = null;
                MiniPlayer.lrcView.Tag = null;
                return;
            }
            foreach (LrcWord i in lrc.Words)
            {//循环遍历添加歌词文本
                //if(i.Word!="")
                lrcView.Items.Add(i);
                MiniPlayer.lrcView.Items.Add(i);
            }
        }
        private void player_MediaChange(object sender, AxWMPLib._WMPOCXEvents_MediaChangeEvent e)
        {
            try
            {

                trcDur.Value = 0;
                trcDur.Maximum = (int)Math.Ceiling(player.currentMedia.duration);
                trcDur.Value = (int)Math.Floor(Duration);
                btnPause.Image = Resources.pause;
                lblDur.Text = string.Format("{0}/{1}", player.Ctlcontrols.currentPositionString, player.currentMedia.durationString);
                Playing = Playing;
                //player.settings.rate = numRate.Value;
            }
            catch (Exception)
            { }
        }
        private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            player_MediaChange(null, null);
        }
        public void btnPause_Click(object sender, EventArgs e)
        {
            if (CurrentMusic == null)
            { return; }
            try
            {
                if (Playing)
                {
                    player.Ctlcontrols.pause();
                }
                else
                {
                    player.Ctlcontrols.play();
                }
            }
            catch { }
        }
        private void tmrPlayer_Tick(object sender, EventArgs e)
        {
            try
            {
                Playing = Playing;
                trcDur.Value = (int)Math.Floor(Duration); //(int)Math.Floor(t);
                lblDur.Text = string.Format("{0}/{1}", player.Ctlcontrols.currentPositionString, player.currentMedia.durationString);
                if (Duration >= 1 && Duration + 1 > player.currentMedia.duration)
                {
                    if (playList.Items.Count == 0) { return; }
                    switch (Mode)
                    {
                        case PlayMode.顺序播放:
                            CurrentMusic = (Music)playList.Items[Index + 1];
                            break;
                        case PlayMode.随机播放:
                            Random rd = new Random();
                            CurrentMusic = (Music)playList.Items[rd.Next(0, playList.Items.Count)];
                            break;
                        case PlayMode.列表循环:
                            if (Index == playList.Items.Count - 1)
                            { CurrentMusic = (Music)playList.Items[0]; }
                            else { CurrentMusic = (Music)playList.Items[Index + 1]; }
                            break;
                        case PlayMode.单曲循环:
                            Duration = 0;
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception)
            { }
        }
        public void trcDur_MouseUp(object sender, MouseEventArgs e)
        {
            player.Ctlcontrols.currentPosition = trcDur.Value;
        }
        private void trcVol_ValueChanged(object sender, EventArgs e)
        {
            player.settings.volume = trcVol.Value;
            Settings.Default.音量 = trcVol.Value;
        }
        private void tmrLrc_Tick(object sender, EventArgs e)
        {
            try
            {
                //获取音乐进度
                double t = player.Ctlcontrols.currentPosition;
                //当歌词不为空的时候滚动
                if (CurrentLrc != null)
                {//
                    Lyric l = CurrentLrc;
                    //计算超前时间
                    double offset = t + l.Offset + numOffset.Value;
                    for (int i = 0; i < l.Words.Count; i++)
                    {//循环遍历歌词文本
                        if (l.Words[i].Time >= offset)
                        {//如果那句歌词时间大于等于进度则显示
                            lrcView.SelectedIndex = i - 1;
                            MiniPlayer.lrcView.SelectedIndex = i - 1;
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            { }
        }
        public void lrcView_ItemClick(object sender, EventArgs e)
        {
            Playing = false;
            lock (lrcView)
            {
                LrcWord l = lrcView.SelectedItem as LrcWord;
                if (l != null)
                {
                    Duration = l.Time;
                }
            }
            if (Playing)
            { Playing = true; }
        }
        #endregion
        #region 杂项菜单事件
        private void 筛选FToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string name = (sender as ToolStripMenuItem).Tag.ToString();
            Music s = Music.FromDataGridView(dgvMusic.CurrentRow);
            string cdn = name;
            switch (name)
            {
                case "Name":
                    cdn = string.Format("Name like '%{0}%'", s.Name);
                    break;
                case "Artist":
                    cdn = string.Format("Artist like '%{0}%'", s.Artist);
                    break;
                case "Album":
                    cdn = string.Format("Album like '%{0}%'", s.Album);
                    break;
                default:
                    cdn = "1=1";
                    break;
            }
            DataTable dt = Music.ModelToTable(Result);
            DataView dv = dt.DefaultView;
            dv.RowFilter = cdn;
            dgvMusic.DataSource = dv.ToTable();
        }

        private void trcDur_ValueChanged(object sender, EventArgs e)
        {
            MiniPlayer.trcDur.Maximum = trcDur.Maximum;
            MiniPlayer.trcDur.Value = trcDur.Value;
        }

        private void chk迷你播放器_ValueChanged(object sender, bool value)
        {
            MiniPlayer.Visible = chk迷你播放器.Checked;
        }

        private void btn管理播放列表_Click(object sender, EventArgs e)
        {
            SavePlayList();
            Process.Start("notepad",Application.StartupPath + "\\"+(sender as Control).Tag+".json");
            this.ShowInfoDialog("推荐使用notepad++\n点击\"确定\"按钮以更新列表", UIStyle.Blue);
            LoadPlayList();
        }

        private void numRate_ValueChanged(object sender, double value)
        {
            player.settings.rate = numRate.Value;
            LoadLrc(CurrentLrc.Speed(player.settings.rate));
            player_MediaChange(null, null);
        }

        public void menuPlayMode_Opening(object sender, CancelEventArgs e)
        {
            if (menuPlayMode.Items.Count == 0)
            {
                menuPlayMode.Items.Add(顺序播放ToolStripMenuItem);
                menuPlayMode.Items.Add(随机播放ToolStripMenuItem);
                menuPlayMode.Items.Add(列表循环ToolStripMenuItem);
                menuPlayMode.Items.Add(单曲循环ToolStripMenuItem);
            }
        }

        private void menuPlay_Opening(object sender, CancelEventArgs e)
        {
            if (播放模式ToolStripMenuItem.DropDownItems.Count == 0)
            {
                播放模式ToolStripMenuItem.DropDownItems.Add(顺序播放ToolStripMenuItem);
                播放模式ToolStripMenuItem.DropDownItems.Add(随机播放ToolStripMenuItem);
                播放模式ToolStripMenuItem.DropDownItems.Add(列表循环ToolStripMenuItem);
                播放模式ToolStripMenuItem.DropDownItems.Add(单曲循环ToolStripMenuItem);
            }
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!Update())
            { this.ShowSuccessTip("已是最新版本,无需更新"); }
        }
        private void btnKgHelperOpen_Click(object sender, EventArgs e)
        {
            if (openTxt.ShowDialog() == DialogResult.OK)
            {
                txtKgHelperPath.Text = openTxt.FileName;
            }
        }
        private void btnKgHelperLaunch_Click(object sender, EventArgs e)
        {
            Process.Start("KgHelper.exe", string.Format("\"{0}\"", txtKgHelperPath.Text));
        }
        private void btnSelectFolder_Click(object sender, EventArgs e)
        {
            if (folder.ShowDialog() == DialogResult.OK)
            {
                txtPath.Text = folder.SelectedPath;
                SaveSettings();
            }
        }
        private void btnExplorer_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", string.Format("\"{0}\"", MusicHelper.Path));
        }
        private void btnTestServer_Click(object sender, EventArgs e)
        {
            if (HttpHelper.CheckUri(string.Format("http://{0}/search.aspx", txtIp.Text)))
            { this.ShowSuccessTip("成功"); }
            else { this.ShowErrorTip("失败"); }
        }
        private void 加载更多ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (!bgwSearch.IsBusy)
            {
                //初始化页码
                pn++;
                //开始执行搜索线程
                SearchArgs ars = new SearchArgs(txtWord.Text.Trim(), pn, false);
                MusicSource source = (MusicSource)cboSource.SelectedItem;
                ars.Source = source.Value;
                bgwSearch.RunWorkerAsync(ars);
            }
            else
            {
                UIMessageTip.ShowError("当前有任务正在进行中");
            }
        }
        private void 显示隐藏主界面ToolStripMenuItem_Click(object sender, MouseEventArgs e)
        {

        }
        private void notify_MouseClick_1(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visible)
                { this.Hide(); }
                else { this.Show(); }
            }
        }
        private void 添加到播放列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Music s = Music.FromDataGridView(dgvMusic.CurrentRow);
            playList.Items.Add(s);
        }
        private void 收藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Music s = Music.FromDataGridView(dgvMusic.CurrentRow);
            s.Love = true;
            lstLove.Items.Add(s);
        }
        private void 批量操作ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Result.Clear();
            foreach (DataGridViewRow row in dgvMusic.Rows)
            {
                Result.Add(Music.FromDataGridView(row));
            }
            FrmMultiple f = new FrmMultiple(Result);
            f.MainForm = this;
            f.Style = this.Style;
            f.Show();
        }
        private void btnExportList_Click(object sender, EventArgs e)
        {
            if (folder.ShowDialog() == DialogResult.OK)
            {//3list4love
                List<Music> list = new List<Music>();
                switch (tabControl.SelectedIndex)
                {
                    case 3:
                        foreach (Music item in playList.Items)
                        {
                            list.Add(item);
                        }

                        break;
                    case 4:
                        foreach (Music item in lstLove.Items)
                        {
                            list.Add(item);
                        }
                        break;
                    default:
                        break;
                }
                Music.SaveList(folder.SelectedPath, list);
            }
        }
        private void btnDeleteLove_Click(object sender, EventArgs e)
        {
            lstLove.Items.Remove(lstLove.SelectedItem);
        }
        private void btnDeleteList_Click(object sender, EventArgs e)
        {
            lstLove.Items.Remove(playList.SelectedItem);
        }
        private void btnClearList_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog("提示", "确认清空播放列表?"))
            { playList.Items.Clear(); }
        }
        private void btnClearLove_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog("提示", "确认清空我的收藏?"))
            { lstLove.Items.Clear(); }
        }
        private string empty = "请输入关键字,歌单解析请输入@+歌单id";
        private void txtWord_Enter(object sender, EventArgs e)
        {
            this.AcceptButton = btnSearch;
            if (txtWord.Text == empty)
            {
                txtWord.Text = "";
                txtWord.ForeColor = Color.FromArgb(48, 48, 48);
            }
        }
        private void txtWord_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtWord.Text))
            {
                txtWord.Text = empty;
                txtWord.ForeColor = Color.FromArgb(173, 178, 181);
            }
        }
        private void txtProxy_TextChanged(object sender, EventArgs e)
        {
            HttpHelper.Proxy = txtProxy.Text;
        }
        private void chkTop_ValueChanged(object sender, bool value)
        {
            this.TopMost = chk总在最前.Checked;
        }
        private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (bgwDown.IsBusy)
            {
                UIMessageTip.ShowError("当前有任务正在进行中");
                return;
            }
            bgwDown.RunWorkerAsync(dgvMusic);
        }
        private void chkControl_ValueChanged(object sender, bool value)
        {
            if (chkControl.Checked)
            { Win32Helper.AllocConsole(); }
            else { Win32Helper.FreeConsole(); }
        }
        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openMusic.ShowDialog() == DialogResult.OK)
            {
                CurrentMusic = Music.FromFile(openMusic.FileName);
            }
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveMusic.ShowDialog() == DialogResult.OK)
            {
                CurrentMusic.SaveFile(saveMusic.FileName);
            }
        }
        private void btnImportList_Click(object sender, EventArgs e)
        {
            if (folder.ShowDialog() == DialogResult.OK)
            {//3list4love
                List<Music> list = Music.LoadList(folder.SelectedPath);
                foreach (var item in list)
                {
                    switch (tabControl.SelectedIndex)
                    {
                        case 3:
                            playList.Items.Add(item);
                            break;
                        case 4:
                            lstLove.Items.Add(item);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        private void btnGC_Click(object sender, EventArgs e)
        {
            GC.Collect();
        }
        private void trcOpacity_ValueChanged(object sender, EventArgs e)
        {
            if (trc不透明度.Value > 0)
                this.Opacity = (double)trc不透明度.Value / 100;
        }
        private void btnPlayMode_MouseUp(object sender, MouseEventArgs e)
        {
            menuPlayMode_Opening(null, null);
            menuPlayMode.Show(btnPlayMode, e.Location);
        }
        private void 播放模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Mode = (PlayMode)Convert.ToInt32((sender as ToolStripDropDownItem).Tag);
            Image pic = (Image)Properties.Resources.ResourceManager.GetObject(Mode.ToString(), null);
            btnPlayMode.BackgroundImage = pic;
            MiniPlayer.btnPlayMode.BackgroundImage = pic;
        }
        private void 搜索曲名SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvMusic.CurrentRow == null)
            {
                UIMessageTip.ShowError("您未选择任何歌曲");
                return;
            }
            Music s = Music.FromDataGridView(dgvMusic.CurrentRow);
            txtWord.Text = s.Name;
            if (!bgwSearch.IsBusy)
            {
                pn = 1;
                SearchArgs ars = new SearchArgs(s.Name, pn, true);
                MusicSource source = (MusicSource)cboSource.SelectedItem;
                ars.Source = source.Value;
                bgwSearch.RunWorkerAsync(ars);
            }
            else { UIMessageTip.ShowError("当前有任务正在进行中"); }
        }
        public void btnPre_Click(object sender, EventArgs e)
        {
            if (playList.Items.Count == 0) { return; }
            if (Index != 0)
                CurrentMusic = (Music)playList.Items[Index - 1];
            else CurrentMusic = (Music)playList.Items[playList.Items.Count - 1];
        }
        public void btnNext_Click(object sender, EventArgs e)
        {
            if (playList.Items.Count == 0) { return; }
            if (Mode == PlayMode.随机播放)
            {
                Random rd = new Random();
                CurrentMusic = (Music)playList.Items[rd.Next(0, playList.Items.Count)];
                return;
            }
            if (Index != playList.Items.Count - 1)
                CurrentMusic = (Music)playList.Items[Index + 1];
            else CurrentMusic = (Music)playList.Items[0];
        }
        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        public void 显示隐藏主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible)
            { this.Hide(); }
            else
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }
        }
        private void btnLrcEditor_Click(object sender, EventArgs e)
        {
            FrmLrcEditor f = new FrmLrcEditor();
            f.Show();
        }
        private void 编辑歌词toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentLrc != null)
            {
                player.Ctlcontrols.pause();
                FrmLrcEditor f = new FrmLrcEditor(CurrentMusic);
                f.MyParent = this;
                f.Show();
            }
        }
        private void dgvMusic_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (bgwPlay.IsBusy)
            {
                UIMessageTip.ShowError("当前有任务正在进行中");
                return;
            }
            bgwPlay.RunWorkerAsync(sender);
        }
        private void dgvMusic_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgvMusic.Rows[e.RowIndex].Selected == false)
                    {
                        dgvMusic.ClearSelection();
                        dgvMusic.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgvMusic.SelectedRows.Count == 1)
                    {
                        dgvMusic.CurrentCell = dgvMusic.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    menuMusic.Show(MousePosition.X, MousePosition.Y);
                }
                return;
                (sender as DataGridView).CurrentRow.Selected = false;
                (sender as DataGridView).Rows[e.RowIndex].Selected = true;
                //menuMusic.Show(this,e.Location);
            }
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }
        private void playList_ItemDoubleClick(object sender, EventArgs e)
        {
            Music s = (sender as ListBoxEx).SelectedItem as Music;
            if (s != null)
                CurrentMusic = s;
        }
        public void btnLove_Click(object sender, EventArgs e)
        {
            if (CurrentMusic == null)
            { return; }
            CurrentMusic.Love = !CurrentMusic.Love;
            if (CurrentMusic.Love)
            {
                if (!lstLove.Items.Contains(CurrentMusic))
                    lstLove.Items.Add(CurrentMusic);
            }
            else { lstLove.Items.Remove(CurrentMusic); }
            Image pic = CurrentMusic.Love ? Properties.Resources.love : Properties.Resources.unlove;
            btnLove.BackgroundImage = pic;
            MiniPlayer.btnLove.BackgroundImage = pic;
        }
        private void lstMusic_ItemDoubleClick(object sender, EventArgs e)
        {
            if (bgwPlay.IsBusy)
            {
                UIMessageTip.ShowError("当前有任务正在进行中");
                return;
            }
            bgwPlay.RunWorkerAsync(sender);
        }
        private void picMusic_Click(object sender, EventArgs e)
        {
            tabControl.SelectedIndex = 2;
        }
        private void txtWord_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyCode)
                {
                    case Keys.Down:
                        cboSource.SelectedIndex++;
                        break;
                    case Keys.Up:
                        cboSource.SelectedIndex--;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            { }
        }
        private void cboTheme_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Style = (UIStyle)cbo主题.SelectedItem;
        }
        private void picAlbum_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (openPic.ShowDialog() == DialogResult.OK)
                {
                    string path = openPic.FileName;
                    CurrentMusic.PicUrl = path;
                    CurrentMusic = CurrentMusic;
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                if (picAlbum.BackgroundImage == null)
                { return; }
                if (savePic.ShowDialog() == DialogResult.OK)
                {
                    picAlbum.BackgroundImage.Save(savePic.FileName, ImageFormat.Jpeg);
                }
            }
            else { Welcome(); }
        }
        private void btnPlayMenu_MouseUp(object sender, MouseEventArgs e)
        {
            menuPlay.Show(btnPlayMenu, e.Location);
        }
        public void 刷新toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!bgwRefresh.IsBusy)
            { bgwRefresh.RunWorkerAsync(); }
        }
        private void 复制歌曲地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Clipboard.SetText(CurrentMusic.Url);
                this.ShowSuccessTip(string.Format("已复制到前切板\n{0}", CurrentMusic.Url));
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }
        }
        private void 加载更多ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!bgwSearch.IsBusy)
            {
                pn++;
                bgwSearch.RunWorkerAsync(new SearchArgs(txtWord.Text.Trim(), pn, false));
            }
            else { UIMessageTip.ShowError("当前有任务正在进行中"); }
        }
        private void 搜索艺术家ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvMusic.CurrentRow == null)
            {
                UIMessageTip.ShowError("您未选择任何歌曲");
                return;
            }
            Music s = Music.FromDataGridView(dgvMusic.CurrentRow);
            txtWord.Text = s.Artist;
            if (!bgwSearch.IsBusy)
            {
                pn = 1;
                SearchArgs ars = new SearchArgs(s.Artist, pn, true);
                MusicSource source = (MusicSource)cboSource.SelectedItem;
                ars.Source = source.Value;
                bgwSearch.RunWorkerAsync(ars);
            }
            else { UIMessageTip.ShowError("当前有任务正在进行中"); }
        }
        private void 导入歌词toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openLrc.ShowDialog() == DialogResult.OK)
            {
                CurrentMusic.Lrc = Lyric.FromFile(openLrc.FileName, Encoding.Default).Export;
                CurrentMusic = CurrentMusic;
            }
        }
        private void 保存歌词ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveLrc.ShowDialog() == DialogResult.OK && CurrentLrc != null)
            {
                switch (saveLrc.FilterIndex)
                {
                    case 1:
                        CurrentLrc.Save(saveLrc.FileName, Encoding.Default);
                        break;
                    case 2:
                        CurrentLrc.SaveText(saveLrc.FileName, Encoding.Default);
                        break;
                    default:
                        break;
                }
            }
        }
        private void btnSearchCollection(object sender, EventArgs e)
        {
            PictureBox b = sender as PictureBox;
            if (!bgwSearch.IsBusy)
            {
                //开始执行搜索线程
                bgwSearch.RunWorkerAsync(new SearchArgs("@" + b.Tag.ToString(), pn, true, "Netease"));
                tabControl.SelectedIndex = 0;
            }
            else
            {
                UIMessageTip.ShowError("当前有任务正在进行中");
            }
        }
        #endregion


        #region 未完成的窗体设计代码
        private void FrmMain_BackColorChanged(object sender, EventArgs e)
        {
            this.TransparencyKey = this.BackColor;
        }

        private void FrmMain_LocationChanged(object sender, EventArgs e)
        {
            //MyParent.Location = this.Location;
        }

        private void ChangeBackColor(Color clr, params Control[] ctrls)
        {
            foreach (Control item in ctrls)
            {
                item.BackColor = clr;
                UIPanel pan = item as UIPanel;
                if (pan != null)
                    pan.FillColor = item.BackColor;
            }
        }
        private void FrmMain_Activated(object sender, EventArgs e)
        {

        }

        private void FrmMain_VisibleChanged(object sender, EventArgs e)
        {
            //MyParent.Visible = this.Visible;
            if (!this.Visible)
            { notify.ShowBalloonTip(3000, "提示", "软件已收起", ToolTipIcon.Info); }
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveSettings();
            //MyParent.Close();
        }

        private void FrmMain_BackColorChanged_1(object sender, EventArgs e)
        {
            return;
            this.TransparencyKey = this.BackColor;
            this.foreColor = this.BackColor;
            // ChangeBackColor(this.BackColor,txtFormat,txtIp,txtKgHelperPath,txtNum,txtPath,txtProxy,txtSimilar,txtWord,cboSource,lstGedan,lstLove,dgvMusic,numOffset,playList,lrcView,cboTheme,txtTimeout);
            dgvMusic.StripeEvenColor = this.BackColor;
            dgvMusic.StripeOddColor = this.BackColor;
            dgvMusic.BackgroundColor = this.BackColor;
            //tabControl.TabBackColor = this.BackColor;
            //tabControl.TabSelectedColor = this.BackColor;
            //panel1.BackColor = Color.FromArgb(30,Color.White);
            //uiPanel1.BackColor = Color.FromArgb(30, Color.White);

        }

        #endregion
    }
}