using Helper;
using Sunny.UI;
using ZSMusic.Winform.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 ZSMusic.Model;
using ZSMusic.BLLEX;
using Win32Helper;
using Newtonsoft.Json;
using System.ComponentModel.Design;

namespace ZSMusic.Winform
{
    public enum PlayMode { 顺序播放 = 0, 随机播放 = 1, 列表循环 = 2, 单曲循环 = 3 }
    public delegate void Ex(Exception ex);
    public partial class FrmMain : UIForm
    {
        /// <summary>
        /// 从DataGridView中获取实体
        /// </summary>
        /// <param name="row">行</param>
        /// <returns></returns>
        public static Music FromDataGridView(System.Windows.Forms.DataGridViewRow row)
        {
            DataRowView row_view = (DataRowView)row.DataBoundItem;
            DataTable dt = row_view.DataView.Table.Clone();//克隆DataTable结构
            dt.ImportRow(row_view.Row);
            ModelConvertHelper<Music> h = new ModelConvertHelper<Music>();
            return h.Row2Model<Music>(dt.Rows[0]);
        }

        public void ShowError(Exception ex)
        {
            if (Debugger.IsAttached)
            {
                throw ex;
            }
            FrmEx f = new FrmEx();
            f.Style = UIStyle.Red;
            f.Ex = ex;
            f.ShowDialog();
        }
        public FrmMiniPlayer MiniPlayer { get; set; }
        /// <summary>
        /// 主窗体构造
        /// </summary>
        public FrmMain(Music s = null)
        {
            InitializeComponent();
            Result = new List<Music>();
            this.Text = Program.Info.ToString();
            if (Debugger.IsAttached)
            {
                this.Text += " [调试模式]";
            }
            MiniPlayer = new FrmMiniPlayer();
            MiniPlayer.MyParent = this;
            player.URL = "";
            if (s != null)
                CurrentMusic = s;
        }
        #region 属性与字段集
        /// <summary>
        /// 播放模式
        /// </summary>
        public PlayMode Mode
        {
            get { return (PlayMode)UserSettings.Current.播放模式; }
            set { UserSettings.Current.播放模式 = (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 (player.URL != s.Url)
                {
                    player.URL = s.Url;
                }
                ThreadPool.QueueUserWorkItem(delegate
                {
                    PlayMusic(s);
                }, null);
                lblInfo.Text = s.ToString();
                MiniPlayer.lblInfo.Text = string.Format("{0}\n{1}", s.Name, s.Artist);
                Image pic = lstLove.Items.Contains(s) ? Properties.Resources.love : Properties.Resources.unlove;
                btnLove.BackgroundImage = pic;
                MiniPlayer.btnLove.BackgroundImage = pic;
                if (!playList.Items.Contains(s))
                { playList.Items.Add(s); }
                if (!lstHistory.Items.Contains(s))
                { lstHistory.Items.Add(s); }
            }
        }
        private void PlayMusic(Music s)
        {
            try
            {
                IsBusy = true;
                if (!HttpHelper.CheckUri(s.Url))
                {
                    s = MusicHelper.GetData(s);
                }
                if (!HttpHelper.CheckUri(s.Url))
                {
                    s = MusicHelper.ReSearch(s, UserSettings.Current.重新查找精确度);
                }
                ThreadPool.QueueUserWorkItem(delegate
                {
                    LoadPic(s);
                }, null);
                player.URL = s.Url;
                LoadLrc(Lyric.Parse(s.Lrc));
                lstError.Items.Remove(s);
                IsBusy = false;
            }
            catch (Exception ex)
            {
                s.Tag = ex;
                playList.Items.Remove(s);
                lstLove.Items.Remove(s);

                lstError.Items.Add(s);
                this.Invoke(new Ex(ShowError), ex);
            }
        }
        private void LoadPic(Music s)
        {
            try
            {
                picMusic.Image = Properties.Resources.load;
                MiniPlayer.picSong.Image = Properties.Resources.load;
                Image pic = ImageHelper.GetImage(s.PicUrl);
                if (pic == null)
                { pic = Properties.Resources.logo; }
                picMusic.BackgroundImage = pic;
                MiniPlayer.picSong.BackgroundImage = pic;
                MiniPlayer.picSong.Image = null;
                picMusic.Image = null;
                GC.Collect();
            }
            catch (Exception ex)
            {
                //this.Invoke(new Ex(ShowError), ex);
            }

        }

        /// <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)
        {
            Console.WriteLine(JsonConvert.SerializeObject(Program.Info));
            SetDesign();
            LoadSettings();
            if (UserSettings.Current.问候语)
            { Welcome(); }
            if (UserSettings.Current.检查更新 && !Debugger.IsAttached)
            {
                ThreadPool.QueueUserWorkItem(delegate
                {
                    Update();
                }, null);
            }
            ThreadPool.QueueUserWorkItem(delegate
            {
                LoadSources();
            }, null);
            LoadPlayList();
            if (UserSettings.Current.启动后自动播放 && playList.Items.Count > 0)
            { CurrentMusic = playList.Items[0] as Music; }
            if (UserSettings.Current.首次运行)
            {
                if (Debugger.IsAttached)
                { (new FrmDebugMode()).ShowDialog(); }
                (new FrmWelcome()).ShowDialog();
            }
        }
        /// <summary>
        /// 问候语
        /// </summary>
        public void Welcome()
        {
            notify.ShowBalloonTip(10000, UserSettings.Current.title, UserSettings.Current.text, ToolTipIcon.Info);

        }

        public void Update()
        {
            try
            {
                btn检查更新.Enabled = false;
                List<VersionInfo> list = MusicHelper.GetUpdate();
                if (list.Count == 0)
                {
                    this.ShowSuccessTip("当前已是最新版本,无需更新");
                    return;
                }
                if (list[0].DALVersion > Program.Info.DALVersion)
                {
                    HttpHelper.Down(Application.StartupPath + "\\DALUpdate\\ZSMusic.DAL.dll", list[0].DALUrl);
                    MessageBox.Show("解析接口已更新,请关闭软件,将ZSMusic.DAL.dll复制替换到程序目录,重启软件完成更新", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Process.Start("explorer.exe", Application.StartupPath + "\\DALUpdate");
                }
                if (list[0].UIVersion > Program.Info.UIVersion)
                {
                    FrmUpdate.TargetVervionInfo = list;
                    FrmUpdate.LocalVersionInfo = Program.Info;
                    this.Invoke(new MethodInvoker(ShowUpdateForm));
                }
                else { this.ShowSuccessTip("当前已是最新版本,无需更新"); }
            }
            catch (Exception ex)
            {
                this.Invoke(new Ex(ShowError), ex);
            }
            finally
            {
                btn检查更新.Enabled = true;
            }
        }

        private void ShowUpdateForm()
        {
            FrmUpdate f = new FrmUpdate();
            f.ShowDialog();
        }
        /// <summary>
        /// 加载音乐源
        /// </summary>
        public void LoadSources()
        {
        start: try
            {
                if (MusicHelper.Online)
                { this.ShowInfoTip("正在联机获取音源列表"); }
                List<MusicSource> list = MusicHelper.GetAllSources();
                cboSource.Items.Clear();
                foreach (MusicSource item in list)
                {
                    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; }
            }
            catch (Exception ex)
            {
                DialogResult dr = MessageBox.Show(this, ex.Message, "联机获取音源失败", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
                switch (dr)
                {
                    case DialogResult.Abort:
                        Application.Exit();
                        break;
                    case DialogResult.Retry:
                        goto start;
                    default:
                        break;
                }
            }
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall || Debugger.IsAttached)
            {
                goto end;
            }
            if (UserSettings.Current.退出显示提示)
            {
                FrmClose f = new FrmClose();
                f.Style = this.Style;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    if (f.rdo最小化托盘.Checked)
                    {
                        e.Cancel = true;
                        this.Hide();
                        UserSettings.Current.退出显示提示 = !f.chk不再提示.Checked;
                        chk退出时显示提示.Checked = !f.chk不再提示.Checked;
                        chk退出到托盘.Checked = f.rdo最小化托盘.Checked;
                        UserSettings.Current.退出到托盘 = f.rdo最小化托盘.Checked;
                        return;
                    }
                    else
                    {
                        UserSettings.Current.退出显示提示 = !f.chk不再提示.Checked;
                        chk退出时显示提示.Checked = !f.chk不再提示.Checked;
                        chk退出到托盘.Checked = f.rdo最小化托盘.Checked;
                        UserSettings.Current.退出到托盘 = f.rdo最小化托盘.Checked;
                        goto end;
                    }
                }
                else
                {
                    e.Cancel = true;
                    return;
                }
            }
            else
            {
                if (UserSettings.Current.退出到托盘)
                {
                    e.Cancel = true;
                    this.Hide();
                    return;
                }
            }
        end: SaveSettings();
            SavePlayList();
        }
        public void LoadPlayList()
        {
            playList.Items.Clear();
            lstLove.Items.Clear();
            lstHistory.Items.Clear();
            lstCollection.Items.Clear();
            lstError.Items.Clear();
            playList.Items.AddRange(Program.CurrentUser.PlayList.ToArray());
            lstLove.Items.AddRange(Program.CurrentUser.Love.ToArray());
            lstHistory.Items.AddRange(Program.CurrentUser.History.ToArray());
            lstCollection.Items.AddRange(Program.CurrentUser.MusicCollections.ToArray());
            lstError.Items.AddRange(Program.CurrentUser.ErrorMusic.ToArray());
        }
        public void SavePlayList()
        {
            Program.SaveUser();
            Program.CurrentUser.PlayList.Clear();
            foreach (Music item in playList.Items)
            {
                Program.CurrentUser.PlayList.Add(item);
            }
            Program.CurrentUser.Love.Clear();
            foreach (Music item in lstLove.Items)
            {
                Program.CurrentUser.Love.Add(item);
            }
            Program.CurrentUser.History.Clear();
            foreach (Music item in lstHistory.Items)
            {
                Program.CurrentUser.History.Add(item);
            }
            Program.CurrentUser.ErrorMusic.Clear();
            foreach (Music item in lstError.Items)
            {
                Program.CurrentUser.ErrorMusic.Add(item);
            }
            Program.CurrentUser.MusicCollections.Clear();
            foreach (MusicCollection item in lstCollection.Items)
            {
                Program.CurrentUser.MusicCollections.Add(item);
            }
            Program.SaveUser();
        }
        public void LoadSettings()
        {
            UserSettings.Current = File.Exists("Settings.json") ? JsonConvert.DeserializeObject<UserSettings>(File.ReadAllText("Settings.json")) : UserSettings.Default;
            MusicHelper.Online = UserSettings.Current.在线解析;
            MusicHelper.Address = UserSettings.Current.服务器地址;
            UserSettings.Current.下载路径 = string.IsNullOrWhiteSpace(UserSettings.Current.下载路径) ? Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) : UserSettings.Current.下载路径;
            chk问候语.Checked = UserSettings.Current.问候语;
            chk检查更新.Checked = UserSettings.Current.检查更新;
            this.Opacity = UserSettings.Current.不透明度;
            txtSimilar.Text = UserSettings.Current.重新查找精确度.ToString();
            txtTimeout.Text = UserSettings.Current.超时时间.ToString();
            HttpHelper.TimeOut = UserSettings.Current.超时时间;
            txtNum.Text = UserSettings.Current.每页显示数量.ToString();
            player.settings.volume = UserSettings.Current.音量;
            trcVol.Value = UserSettings.Current.音量;
            trc不透明度.Value = (int)(this.Opacity * 100);
            this.Style = UserSettings.Current.主题;
            cbo主题.SelectedItem = UserSettings.Current.主题;
            HttpHelper.UseProxy = UserSettings.Current.使用代理;
            chkhttp代理.Checked = UserSettings.Current.使用代理;
            HttpHelper.Proxy = UserSettings.Current.http代理;
            txtProxy.Text = UserSettings.Current.http代理;
            this.TopMost = UserSettings.Current.总在最前;
            chk总在最前.Checked = UserSettings.Current.总在最前;
            chk退出到托盘.Checked = UserSettings.Current.退出到托盘;
            chk退出时显示提示.Checked = UserSettings.Current.退出显示提示;
            chk迷你播放器.Checked = UserSettings.Current.迷你播放器;
            MiniPlayer.Visible = UserSettings.Current.迷你播放器;
            bool IsEnabledDownload = UserSettings.Current.启用下载 || Debugger.IsAttached;
            btnDownload.Visible = IsEnabledDownload;
            下载ToolStripMenuItem.Visible = IsEnabledDownload;
            批量下载ToolStripMenuItem1.Visible = IsEnabledDownload;
            chk自动播放.Checked = UserSettings.Current.启动后自动播放;
            if (IsEnabledDownload)
            {
                专辑.Width = 240;
                down.Visible = true;
            }
            else
            {
                专辑.Width = 270;
                down.Visible = false;
            }
        }
        public void SaveSettings()
        {
            UserSettings.Current.问候语 = chk问候语.Checked;
            UserSettings.Current.检查更新 = chk检查更新.Checked;
            UserSettings.Current.不透明度 = this.Opacity;
            UserSettings.Current.重新查找精确度 = Convert.ToDouble(txtSimilar.Text);
            UserSettings.Current.超时时间 = int.Parse(txtTimeout.Text);
            HttpHelper.TimeOut = int.Parse(txtTimeout.Text);
            UserSettings.Current.每页显示数量 = Convert.ToInt32(txtNum.Text);
            UserSettings.Current.总在最前 = this.TopMost;
            UserSettings.Current.主题 = this.Style;
            UserSettings.Current.使用代理 = HttpHelper.UseProxy;
            UserSettings.Current.http代理 = HttpHelper.Proxy;
            UserSettings.Current.退出到托盘 = chk退出到托盘.Checked;
            UserSettings.Current.退出显示提示 = chk退出时显示提示.Checked;
            UserSettings.Current.迷你播放器 = MiniPlayer.Visible;
            UserSettings.Current.启动后自动播放 = chk自动播放.Checked;
            //UserSettings.Current.Save();
            File.WriteAllText("Settings.json", JsonConvert.SerializeObject(UserSettings.Current));
        }

        #endregion
        #region 音乐加载

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtWord.Text) || txtWord.Text == empty)
            {
                UIMessageTip.ShowError("请输入关键字");
                return;
            }
            pn = 1;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Search(txtWord.Text, true);
            }, null);
        }


        public void Search(string word, bool cls, string source = null)
        {
            IsBusy = true;
            btnSearch.Enabled = false;
            搜索曲名SToolStripMenuItem.Enabled = false;
            搜索艺术家ToolStripMenuItem.Enabled = false;
            加载更多ToolStripMenuItem.Enabled = false;
            try
            {
                string s = source == null ? ((MusicSource)cboSource.SelectedItem).Value : source;
                if (cls)
                { Result.Clear(); }
                DateTime dt = DateTime.Now;
                Result.AddRange(MusicHelper.Search(s, word, pn, UserSettings.Current.每页显示数量));
                TimeSpan span = DateTime.Now - dt;
                this.ShowSuccessTip(string.Format("搜索完毕,共有{0}首歌,耗时{1:f1}秒", Result.Count, span.TotalSeconds));

                this.Invoke(new MethodInvoker(ShowResult));
            }
            catch (Exception ex)
            {
                this.Invoke(new Ex(ShowError), ex);
            }
            IsBusy = false;
            btnSearch.Enabled = true;
            搜索曲名SToolStripMenuItem.Enabled = true;
            搜索艺术家ToolStripMenuItem.Enabled = true;
            加载更多ToolStripMenuItem.Enabled = true;
        }
        private void 搜索曲名SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvMusic.CurrentRow == null)
            {
                UIMessageTip.ShowError("您未选择任何歌曲");
                return;
            }
            Music s = FromDataGridView(dgvMusic.CurrentRow);
            txtWord.Text = s.Name;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Search(txtWord.Text, true);
            }, null);
        }
        private void 加载更多ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pn++;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Search(txtWord.Text, false);
            }, null);
        }
        private void 搜索艺术家ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvMusic.CurrentRow == null)
            {
                UIMessageTip.ShowError("您未选择任何歌曲");
                return;
            }
            Music m = FromDataGridView(dgvMusic.CurrentRow);
            txtWord.Text = m.Artist;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Search(txtWord.Text, true);
            }, null);
        }

        public void ShowResult()
        {
            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)
        {
            PlayMusic(e.Argument);
            return;
            IsBusy = true;
            try
            {
                Music s = LoadMusic(e.Argument);
                CurrentMusic = s;
                if (UserSettings.Current.边听边存)
                {
                    Download(s);
                }
            }
            catch (Exception ex)
            {
                this.Invoke(new Ex(ShowError), ex);
            }
            finally { IsBusy = false; }
        }

        private void PlayMusic(object o)
        {
            IsBusy = true;
            try
            {
                Music s = LoadMusic(o);
                CurrentMusic = s;
                if (UserSettings.Current.边听边存)
                {
                    Download(s);
                }
            }
            catch (Exception ex)
            {
                this.Invoke(new Ex(ShowError), ex);
            }
            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.Invoke(new Ex(ShowError), ex);
            }
            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 = FromDataGridView(dgv.SelectedRows[0]);
            }
            if (s == null)
            {
                throw new NullReferenceException("您未选中任何歌曲");
            }
            this.ShowInfoTip("正在获取音乐地址");
            //如果歌曲未被加载则加载歌曲
            s = MusicHelper.GetData(s);
            if (!HttpHelper.CheckUri(s.Url))
            {
                //歌曲仍未加载成功,自动搜索其它音乐平台
                this.ShowInfoTip("未能解析出地址,自动搜索其它音乐平台");
                s = MusicHelper.ReSearch(s, UserSettings.Current.重新查找精确度);
            }
            return s;
        }
        public void Download(List<Music> list)
        {
            if (!Directory.Exists(UserSettings.Current.下载路径))
            {
                this.ShowErrorTip("请检查下载路径是否正确" + "\r\n" + UserSettings.Current.下载路径);
                return;
            }
            File.WriteAllText("temp.json", JsonConvert.SerializeObject(list), Encoding.Default);
            string config = string.Format(
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n<appSettings>\r\n<add key =\"path\" value=\"{0}\"/>\r\n<add key =\"pic\" value=\"{1}\"/>\r\n<add key =\"lrc\" value=\"{2}\"/>\r\n<add key =\"format\" value=\"{3}\"/>\r\n</appSettings>\r\n</configuration>",
                UserSettings.Current.下载路径, UserSettings.Current.下载封面, UserSettings.Current.下载歌词, UserSettings.Current.文件命名格式);
            File.WriteAllText("ZSMusic.Downloader.exe.config", config, Encoding.UTF8);
            Process.Start("ZSMusic.Downloader.exe");
            this.ShowInfoTip("已开始后台下载");
        }

        public void Download(Music m)
        {
            Download(new List<Music> { m });
        }

        private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Music m = FromDataGridView(dgvMusic.SelectedRows[0]);
            Download(m);
        }

        public void RefreshMusic()
        {
            IsBusy = true;
            btnRefresh.Enabled = false;
            刷新toolStripMenuItem.Enabled = false;
            try
            {
                CurrentMusic = LoadMusic(CurrentMusic);
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }
            finally
            {
                IsBusy = false;
                btnRefresh.Enabled = !false;
                刷新toolStripMenuItem.Enabled = !false;
            }
        }
        #endregion
        #region 窗体设计
        /// <summary>
        /// 加载窗体设计
        /// </summary>
        public void SetDesign()
        {
            if (!UserSettings.Current.启用高级选项 && !Debugger.IsAttached)
            {
                tabControl.TabPages.Remove(更多功能);
            }
            //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)
        {
            Win32.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 || (UserSettings.Current.快速切歌调试模式 && Duration >= UserSettings.Current.快速切歌间隔))
                {
                    Skip();
                }
            }
            catch (Exception)
            { }
        }

        public void Skip()
        {
            try
            {
                if (playList.Items.Count == 0) { return; }
                switch (Mode)
                {
                    case PlayMode.顺序播放:
                        CurrentMusic = (Music)playList.Items[Index + 1];
                        break;
                    case PlayMode.随机播放:
                        CurrentMusic = (Music)playList.Items[Helper.MathEx.RNGRandom(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;
            UserSettings.Current.音量 = 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;

                            lrcView.TopIndex = i - 1 - 7;
                            MiniPlayer.lrcView.TopIndex = i - 1 - 4;
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            { }
        }
        public void lrcView_ItemClick(object sender, MouseEventArgs 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 = 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;
                case "Smart":
                    //string str = (s.Name + s.Artist + s.Album).ToLower();
                    cdn = string.Format("Name not like '%ive%' and Name not like '%伴奏%' and Name not like '%现场%' and Name not like '%over%' and Name not like '%翻自%' and Name not like '%改编%' and Name not like '%DJ%' and Name not like '%emix%' and Name not like '%混音%' and Name not like '%翻%' and Name not like '%片段%' and Name not like '%声版%' and Name not like '%原唱%' and Name not like '%电音%' and Name not like '%（%' and Name not like '%）%' and Name not like '%(%' and Name not like '%)%'");
                    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 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)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                Update();
            }, null);
        }

        private void 加载更多ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (btnSearch.Enabled)
            {
                pn++;
                ThreadPool.QueueUserWorkItem(delegate
                {
                    Search(txtWord.Text, false);
                }, null);
            }
            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 = FromDataGridView(dgvMusic.CurrentRow);
            playList.Items.Add(s);
        }
        private void 收藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Music s = FromDataGridView(dgvMusic.CurrentRow);
            lstLove.Items.Add(s);
        }

        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 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;
        }

        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.随机播放)
            {
                CurrentMusic = (Music)playList.Items[Helper.MathEx.RNGRandom(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();
            LoadSettings();
            LoadSources();
        }
        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 (lstLove.Items.Contains(CurrentMusic))
            {
                lstLove.Items.Remove(CurrentMusic);
            }
            else { lstLove.Items.Add(CurrentMusic); }
            Image pic = lstLove.Items.Contains(CurrentMusic) ? 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 btnPlayMenu_MouseUp(object sender, MouseEventArgs e)
        {
            menuPlay.Show(btnPlayMenu, e.Location);
        }
        public void 刷新toolStripMenuItem_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                RefreshMusic();
            }, null);
        }
        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 (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;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Search("@" + b.Tag.ToString(), true, "wy");
            }, null);
            tabControl.SelectedIndex = 0;
        }
        #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

        private void 生成二维码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(player.URL))
            {
                this.ShowSuccessTip("使用手机浏览器扫码方可下载,下载链接不是永久的哦!");
                new FrmQrCode(player.URL).ShowDialog();
            }
        }

        private void 复制歌曲信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string json = JsonConvert.SerializeObject(CurrentMusic);
            Clipboard.SetText(json);
            this.ShowSuccessTip("已复制");
        }

        private void lRCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentLrc != null)
            {
                Clipboard.SetText(CurrentLrc.Export);
                this.ShowSuccessTip("已复制");
            }
        }

        private void tXTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentLrc != null)
            {
                Clipboard.SetText(CurrentLrc.Text);
                this.ShowSuccessTip("已复制");
            }
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private UIListBox GetList()
        {
            UIListBox list = new UIListBox();
            switch (tabMyMusic.SelectedIndex)
            {
                case 0:
                    list = playList;
                    break;
                case 1:
                    list = lstLove;
                    break;

                case 2:
                    list = lstHistory;
                    break;
                case 3:
                    list = lstCollection;

                    break;
                case 4:
                    list = lstError;
                    break;
                default:
                    break;
            }
            return list;
        }
        private void btnUp_Click(object sender, EventArgs e)
        {
            try
            {
                UIListBox list = GetList();

                int i = list.SelectedIndex;
                if (i > 0)
                {
                    object aa = list.SelectedItem;
                    object uptest = list.Items[i - 1];
                    //把当前选择行的值与上一行互换 并将选择索引减1
                    list.Items[i - 1] = aa;
                    list.Items[i] = uptest;
                    list.SelectedIndex = i - 1;
                }
                else
                {
                    //button2.Enabled = false;
                }
            }
            catch (Exception)
            { }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            try
            {
                UIListBox list = GetList();
                int i = list.SelectedIndex;
                if (i < list.Items.Count - 1)
                {
                    object aa = list.SelectedItem;
                    object uptest = list.Items[i + 1];
                    //把当前选择行的值与下一行互换 并将选择索引加1
                    list.Items[i + 1] = aa;
                    list.Items[i] = uptest;
                    list.SelectedIndex = i + 1;
                }
            }
            catch (Exception)
            { }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            UIListBox list = GetList();
            list.Items.Remove(list.SelectedItem);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog("确认清空?"))
            {
                UIListBox list = GetList();
                list.Items.Clear();
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (openJson.ShowDialog() == DialogResult.OK)
            {
                UIListBox list = GetList();
                list.Items.AddRange(JsonConvert.DeserializeObject<List<Music>>(File.ReadAllText(openJson.FileName)).ToArray());
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (saveJson.ShowDialog() == DialogResult.OK)
            {
                UIListBox list = GetList();
                string json = JsonConvert.SerializeObject(list.Items);
                File.WriteAllText(saveJson.FileName, json);
            }
        }
        private void btnAdvancedEdit_Click(object sender, EventArgs e)
        {
            SavePlayList();
            Program.SaveUser();
            FrmEdit f = new FrmEdit();
            f.propertyGrid.SelectedObject = Program.CurrentUser;
            f.ShowDialog();
            Program.SaveUser();
            LoadPlayList();
        }

        private void chk问候语_ValueChanged(object sender, bool value)
        {
            if (chk问候语.Checked) Welcome();
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            FrmAbout f = new FrmAbout();
            f.ShowDialog();
        }

        private void lrcView_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                //e.DrawBackground();
                //e.DrawFocusRectangle();
                StringFormat strFmt = new System.Drawing.StringFormat();
                strFmt.Alignment = StringAlignment.Center; //文本垂直居中
                strFmt.LineAlignment = StringAlignment.Center; //文本水平居中
                if (e.Index == lrcView.SelectedIndex)
                {
                    e.Graphics.DrawString(lrcView.Items[e.Index].ToString(), e.Font, new SolidBrush(this.RectColor), e.Bounds, strFmt);
                }
                else
                {
                    e.Graphics.DrawString(lrcView.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds, strFmt);
                }
            }
            catch (Exception)
            { }
        }



        private void btnDownload_Click(object sender, EventArgs e)
        {
            Download(CurrentMusic);
        }

        private void btnAdvanced_Click(object sender, EventArgs e)
        {
            if (Debugger.IsAttached || UserSettings.Current.启用高级选项)
            {
                FrmAdvanced f = new FrmAdvanced();
                f.Style = this.Style;
                f.MainForm = this;
                f.ShowDialog();
            }
            else
            {
                this.ShowErrorTip("您需要成为开发者才能使用此功能");
                FrmQuestion F = new FrmQuestion();
                if (F.ShowDialog() == DialogResult.OK)
                {
                    FrmAdvanced f = new FrmAdvanced();
                    f.Style = this.Style;
                    f.MainForm = this;
                    f.ShowDialog();
                }
            }
        }


        private void lrcView_SelectedIndexChanged(object sender, EventArgs e)
        {
            lrcView.Invalidate(false);
        }

        private void 批量添加到播放列表_Click(object sender, EventArgs e)
        {
            Result.Clear();
            foreach (DataGridViewRow row in dgvMusic.Rows)
            {
                Result.Add(FromDataGridView(row));
            }
            playList.Items.AddRange(Result.ToArray());
        }

        private void 批量收藏_Click(object sender, EventArgs e)
        {
            Result.Clear();
            foreach (DataGridViewRow row in dgvMusic.Rows)
            {
                Result.Add(FromDataGridView(row));
            }
            lstLove.Items.AddRange(Result.ToArray());
        }

        private void 批量下载ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Result.Clear();
            foreach (DataGridViewRow row in dgvMusic.Rows)
            {
                Result.Add(FromDataGridView(row));
            }
            Download(Result);
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveJson.ShowDialog() == DialogResult.OK)
            {
                Result.Clear();
                foreach (DataGridViewRow row in dgvMusic.Rows)
                {
                    Result.Add(FromDataGridView(row));
                }
                string json = JsonConvert.SerializeObject(Result);
                File.WriteAllText(saveJson.FileName, json);

            }
        }



        string[] 社会主义核心价值观 = new string[] { "富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善" };
        int a = 0;
        private void FrmMain_MouseCaptureChanged(object sender, EventArgs e)
        {
            if (Debugger.IsAttached)
            { return; }
            this.ShowSuccessTip(社会主义核心价值观[a]);
            a++;
            if (a == 12)
            { a = 0; }
        }

        private void btnTTS_Click(object sender, EventArgs e)
        {
            TTS.FrmTTS f = new TTS.FrmTTS();
            f.Show();
        }

        private void dgvMusic_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                switch (dgvMusic.Columns[e.ColumnIndex].Name)
                {
                    case "play":
                        PlayMusic(sender);
                        break;
                    case "add":
                        添加到播放列表ToolStripMenuItem_Click(sender, e);
                        break;
                    case "down":
                        下载ToolStripMenuItem_Click(sender, e);
                        break;
                    default:
                        break;
                }
            }
        }





    }
}