using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nirvana.Data
{
    public class ReadDbContext
    {
        public static string ConnectionString = Configs.GetString("NirvanaConnection");
        public static Dictionary<string, SqlFilterItem> DefaultFilter = new Dictionary<string, SqlFilterItem>
        {
        };

        public static SqlSugarClient GetInstance()
        {
            try
            {
                var Connection = new ConnectionConfig() { ConnectionString = ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true };
                var reval = new SqlSugarClient(Connection);

                DefaultFilter.Keys.ToList().ForEach(x =>
                {
                    reval.QueryFilter.Add(DefaultFilter[x]);
                });//给查询添加默认过滤器 （所有查询加上 isdeleted=0 or null）

                //.AddDisableUpdateColumns("CreateTime", "Creator");//添加禁止更新列
                reval.Ado.IsEnableLogEvent = true;

                reval.Aop.OnLogExecuting = (sql, pars) =>  //SQL执行前事件
                {
                    //在这儿打段点可以查看生成的SQL语句
                    Console.WriteLine(sql);
                };

                reval.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
                {
                    // 获取执行时间
                    // var time = reval.Ado.SqlExecutionTime;
                   // reval.Ado.Close();
                };
                //reval.Aop.OnError = (exp) =>//执行SQL 错误事件
                //{
                //    //执行的SQL
                //   Console.WriteLine(exp.Sql);
                //    //执行的参数
                //    var param = exp.Parametres;       
                //};
                reval.Aop.OnExecutingChangeSql = (sql, pars) => //SQL执行前 可以修改SQL
                {
                    return new KeyValuePair<string, SugarParameter[]>(sql, pars);
                };
                return reval;
            }
            catch (Exception)
            {
                throw new Exception("连接数据库出错，请检查您的连接字符串和网络。");
            }
        }
    }
}
