using QQPlus.Framework.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dapper;
using QQPlus.Framework.SDK;

namespace QQPlus.Faq
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            FaqConfig config = PluginConfig.Init<FaqConfig>();
            chkAll.Checked = config.All;
            chkClusterOnly.Checked = config.ClusterOnly;
            chkStatus.Checked = config.Status;
            txtPrefix.Text = config.Prefix;
            chkEnableCluster.Checked = config.EnableCluster;
            chkEnableQQ.Checked = config.EnableQQ;
            if (config.Admin != null)
                txtAdmin.Text = string.Join(",", config.Admin);

            List<Faq> faqs = null;
            using (DbBase db = new DbBase())
            {
                faqs = db.Conn.GetAll<Faq>().ToList();
            }
            faqs.ToList().ForEach(faq =>
                {
                    lvFaq.Items.Add(new ListViewItem(new string[] { faq.Id.ToString(), faq.Question, faq.Answer, faq.ExternalId.ToString(), faq.QQ.ToString(), faq.Status ? "开" : "关" }));
                }
            );
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            var config = new FaqConfig() { EnableQQ = chkEnableQQ.Checked, EnableCluster = chkEnableCluster.Checked, Prefix = txtPrefix.Text.Trim(), Admin = Util.StrToList(txtAdmin.Text), ClusterOnly = chkClusterOnly.Checked, All = chkAll.Checked, Status = chkStatus.Checked };
            config.Save();
        }

        private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog() { Filter = "文本文档(*.txt)|*.txt" };
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] lines = File.ReadAllLines(dlg.FileName, Encoding.Default);

                if (lines.Length > 0)
                {
                    lvFaq.BeginUpdate();
                    using (DbBase db = new DbBase())
                    {
                        lines.ToList().ForEach(line =>
                            {
                                if (!string.IsNullOrWhiteSpace(line))
                                {
                                    line = line.Replace("\\n", "\n");
                                    var str = line.Split(new string[] { "====" }, StringSplitOptions.RemoveEmptyEntries);
                                    Faq faq = null;
                                    if (str.Length == 2)
                                    {
                                        faq = new Faq() { Question = str[0], Answer = str[1], ExternalId = 1, QQ = 0, Status = true };
                                    }
                                    else if (str.Length == 5)
                                    {
                                        faq = new Faq() { Question = str[0], Answer = str[1], ExternalId = long.Parse(str[2]), QQ = long.Parse(str[3]), Status = bool.Parse(str[4]) };
                                    }

                                    faq.Id = db.Conn.Insert(faq);
                                    lvFaq.Items.Add(new ListViewItem(new string[] { faq.Id.ToString(), faq.Question, faq.Answer, faq.ExternalId.ToString(), faq.QQ.ToString(), faq.Status ? "开" : "关" }));
                                }
                            }
                        );
                    }
                    lvFaq.EndUpdate();
                }
            }
        }

        private void 开关ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<long> ids = new List<long>();
            for (int i = 0; i < lvFaq.SelectedItems.Count; i++)
            {
                var item = lvFaq.SelectedItems[i];
                ids.Add(long.Parse(item.SubItems[0].Text));
                if (item.SubItems[5].Text == "开")
                    item.SubItems[5].Text = "关";
                else
                    item.SubItems[5].Text = "开";
            }

            if (ids.Count > 0)
            {
                using (DbBase db = new DbBase())
                {
                    db.Conn.Execute("UPDATE Faq SET Status=~Status WHERE Id in @ids", new { @ids = ids.ToArray() });
                }
                MessageBox.Show("更新成功");
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<long> ids = new List<long>();
            lvFaq.BeginUpdate();
            while (lvFaq.SelectedItems.Count > 0)
            {
                var item = lvFaq.SelectedItems[lvFaq.SelectedItems.Count - 1];
                ids.Add(long.Parse(item.SubItems[0].Text));
                lvFaq.Items.Remove(item);
            }
            lvFaq.EndUpdate();

            if (ids.Count > 0)
            {
                using (DbBase db = new DbBase())
                {
                    db.Conn.Execute("DELETE FROM Faq WHERE Id in @ids", new { @ids = ids.ToArray() });
                }
                MessageBox.Show("删除成功");
            }
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lvFaq.SelectedItems.Count; i++)
            {
                var item = lvFaq.SelectedItems[i];
                sb.AppendFormat("{0}===={1}===={2}===={3}===={4}\r\n", ReplaceLine(item.SubItems[1].Text), ReplaceLine(item.SubItems[2].Text), item.SubItems[3].Text, item.SubItems[4].Text, item.SubItems[5].Text == "开"? "true":"false");
            }

            if (lvFaq.SelectedItems.Count > 0)
            {
                SaveFileDialog dlg = new SaveFileDialog() { Filter = "文本文档(*.txt)|*.txt" };
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(dlg.FileName, sb.ToString());
                    System.Diagnostics.Process.Start("Explorer", "/select," + dlg.FileName);
                }
            }
        }

        /// <summary>
        /// 替换换行为\n
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        string ReplaceLine(string str)
        {
            if (str == null)
                return str;

            return str.Replace("\n", "\\n");
        }

    }
}