using QQPlus.Framework.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.IO;
using System.Text.RegularExpressions;

namespace QQPlus.Faq
{
    public class FaqPlugin : Plugin
    {
        public FaqPlugin()
        {
            this.Id = "QQPlus.Faq";
            this.PluginName = "问答系统";
            this.Description = "常见问题解答、自动学习";
            this.Author = "QQPlus";

            DbBase.DataSource = string.Format("Data Source={0};Pooling=true;FailIfMissing=false", Path.Combine(PluginPath, "Faq.db"));
        }

        public override bool Install()
        {
            lock (DbBase.LockDb)
            {
                using (DbBase db = new DbBase())
                {
                    Version v = new Version();
                    if (!db.Conn.TableExists("_history"))
                    {
                        //初始化
                        db.Conn.Execute(@"CREATE TABLE [_history] (
[Id] INTEGER  PRIMARY KEY NOT NULL,
[Ver] NVARCHAR(50)  NULL
);
INSERT INTO [_history] (ver) values('1.0.0.0');

CREATE TABLE [Config](
[Id] INTEGER PRIMARY KEY NOT NULL,
[Content] TEXT  NULL
);
INSERT INTO [Config] (Content) values('');

CREATE TABLE [Faq] (
[Id] INTEGER PRIMARY KEY NOT NULL,
[Question] TEXT  NULL,
[Answer] TEXT  NULL,
[ExternalId] INTEGER NOT NULL,
[QQ] INTEGER NOT NULL,
[Status] BOOLEAN DEFAULT '1' NOT NULL
);");
                    }
                }
            }
            return base.Install();
        }

        public override bool ShowForm()
        {
            new FormMain().ShowDialog();
            LoadConfig();
            return base.ShowForm();
        }

        public override bool Start()
        {
            LoadConfig();

            sdk = new QQClientSDK();
            sdk.ReceiveClusterIM += sdk_ReceiveClusterIM;
            sdk.ReceiveNormalIM += sdk_ReceiveNormalIM;
            return base.Start();
        }

        void sdk_ReceiveNormalIM(object sender, ReceiveNormalIMQQEventArgs e)
        {
            if (!config.EnableQQ)
                return;

            //问答查询
            Faq f1 = null;
            StringBuilder sbSql = new StringBuilder("SELECT * FROM Faq WHERE Status=1 ");
            DynamicParameters where = new DynamicParameters();

            sbSql.Append(" AND Question = @Question");
            where.Add("Question", e.Message);


            sbSql.Append(" ORDER BY RANDOM(*) LIMIT 1");
            lock (DbBase.LockDb)
            {
                using (DbBase db = new DbBase())
                {
                    f1 = db.Conn.Query<Faq>(sbSql.ToString(), where).ToList().FirstOrDefault();
                }
            }

            if (f1 != null)
            {
                client.SendMessage(e.QQ, f1.Answer);
                e.Cancel = true;
            }
        }

        FaqConfig config = null;
        void LoadConfig()
        {
            config = PluginConfig.Init<FaqConfig>();
        }

        void sdk_ReceiveClusterIM(object sender, ReceiveClusterIMQQEventArgs e)
        {
            if (!config.EnableCluster)
                return;

            if (string.IsNullOrWhiteSpace(config.Prefix) || e.Message.StartsWith(config.Prefix))
            {
                string msg = e.Message.Substring(config.Prefix.Length);
                var m = Regex.Match(msg, @"^问[:：](.*?)答[:：](.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    if (config.All || config.Admin.Contains(e.ClusterMember.QQ))
                    {
                        Faq faq = new Faq() { Question = m.Groups[1].Value.Trim(), Answer = m.Groups[2].Value.Trim().Replace("\r","\n"), ExternalId = e.Cluster.ExternalId, QQ = e.ClusterMember.QQ, Status = config.Status };
                        lock (DbBase.LockDb)
                        {
                            using (DbBase db = new DbBase())
                            {
                                db.Conn.Insert(faq);
                            }
                        }
                        if (config.Status)
                            client.SendClusterMessage(e.Cluster.ExternalId, "学习成功");
                        else
                            client.SendClusterMessage(e.Cluster.ExternalId, "学习成功，审核后生效");

                        e.Cancel = true;
                        return;
                    }
                }

                //问答查询
                Faq f1 = null;
                StringBuilder sbSql = new StringBuilder("SELECT * FROM Faq WHERE Status=1 ");
                DynamicParameters where = new DynamicParameters();

                if (config.ClusterOnly)
                {
                    sbSql.Append(" AND ExternalId = @ExternalId");
                    where.Add("ExternalId", e.Cluster.ExternalId);
                }

                sbSql.Append(" AND Question = @Question");
                where.Add("Question", msg);


                sbSql.Append(" ORDER BY RANDOM(*) LIMIT 1");
                lock (DbBase.LockDb)
                {
                    using (DbBase db = new DbBase())
                    {
                        f1 = db.Conn.Query<Faq>(sbSql.ToString(), where).ToList().FirstOrDefault();
                    }
                }

                if (f1 != null)
                {
                    client.SendClusterMessage(e.Cluster.ExternalId, f1.Answer);
                    e.Cancel = true;
                }
            }
        }
    }
}
