using DS.Module.Core;
using DS.Module.Core.Data;
using DS.Module.Core.Extensions;
using DS.Module.Core.Log;
using DS.Module.UserModule;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using SqlSugar;
namespace DS.Module.SqlSugar;
///
/// SqlSugar 启动服务
///
public static class SqlsugarInstall
{
// ///
// /// 数据库连接字符串
// ///
// private static string DbInfo = AppSetting.Configuration["ConnectionStrings:DbInfo"];
//
// ///
// /// 数据库类型
// ///
// private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"];
//public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
// private readonly IUser user;
// private ILogger _logger;
///
/// 将模块服务添加到依赖注入服务容器中
///
/// 依赖注入服务容器
///
public static IServiceCollection AddSqlSugarInstall(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
Console.WriteLine("开始加载sqlsugar模块");
Console.WriteLine("数据库配置id:" + AppSetting.app(new string[] { "DBInfo", "DefaultDbConnId" }));
var dbs = AppSetting.app("DBInfo", "DBS");
//默认数据库
List dbList = new List();
DbConfig defaultdb = new DbConfig()
{
ConnId = AppSetting.app(new string[] { "DBInfo", "DefaultDbConnId" }),
Connection = AppSetting.app(new string[] { "DBInfo", "DefaultDbString" }),
DbType = AppSetting.app(new string[] { "DBInfo", "DefaultDbType" }).ObjToInt()
};
dbList.Add(defaultdb);
//业务数据库集合
foreach (var item in dbs)
{
dbList.Add(item);
}
var connectConfigList = SqlsugarHelper.ReturnConnectionConfig(dbList);
//foreach (var item in dbList)
//{
// //防止数据库重复,导致的事务异常
// if (connectConfigList.Any(a => a.ConfigId == (dynamic)item.ConnId || a.ConnectionString == item.Connection))
// {
// continue;
// }
// connectConfigList.Add(new ConnectionConfig()
// {
// ConnectionString = item.Connection,
// DbType = (DbType)item.DbType,
// IsAutoCloseConnection = true,
// ConfigId = item.ConnId,
// InitKeyType = InitKeyType.Attribute,
// MoreSettings = new ConnMoreSettings()
// {
// IsAutoRemoveDataCache = true //自动清理缓存
// },
// // 自定义特性
// ConfigureExternalServices = new ConfigureExternalServices()
// {
// }
// });
//}
var httpContextAccessor = services.GetService();
var user = services.GetService();
if (user.IsNullOrEmpty())
{
user = new AspNetUser(httpContextAccessor)
{
UserId = "1288018625843826688",
TenantId = "1288018625843826688",
CompanyId = "1288018625843826688",
OrgId = "1288018625843826688"
};
}
//全局上下文生效
SqlSugarScope sqlSugar = new SqlSugarScope(connectConfigList,
db =>
{
// 封装AOP
// SqlsugarAopHelper.AopForSqlsugar(db, user, dbList, connectConfigList);
//Console.WriteLine("开始加载sqlsugar模块 要走过滤 起了");
foreach (var c in connectConfigList)
{
var dbProvider = db.GetConnectionScope((string)c.ConfigId);
// var user = services.GetService();
//单例参数配置,所有上下文生效
dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
//执行前事件
//Logger.Log(LogLevel.Info,
// DateTime.Now.ToString() + "\r\n" +
// UtilMethods.GetSqlString(c.DbType, sql, pars));
//Console.WriteLine("执行的sql:" + DateTime.Now.ToString() + "\r\n" +
// UtilMethods.GetSqlString(c.DbType, sql, pars));
string sqlStr = sql;
foreach (var item in pars)
{
if (item.Value != null && item.Value != DBNull.Value)
{
string? strValue = string.Empty;
if (item.DbType == System.Data.DbType.String)
{
strValue = "'" + (string)item.Value + "'";
}
else if (item.DbType == System.Data.DbType.Boolean)
{
strValue = (bool)item.Value ? "1" : "0";
}
else
{
strValue = item.Value.ToString();
}
sqlStr = sqlStr.Replace(item.ParameterName, strValue);
}
}
Console.WriteLine("执行的SQL:" + Environment.NewLine + sqlStr);
};
//数据处理事件
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
if (entityInfo.PropertyName == "Id")
{
if (entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
{
entityInfo.SetValue(GuidHelper.GetSnowflakeId());
}
if (entityInfo.EntityColumnInfo.IsPrimarykey &&
entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
{
var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo
.EntityValue);
if (id == null || (long)id == 0)
entityInfo.SetValue(SnowFlakeSingle.Instance.NextId());
}
}
if (entityInfo.PropertyName == "CreateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "TenantId")
{
var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
if (tenantId == null || tenantId == 0)
entityInfo.SetValue(user.GetTenantId());
}
if (entityInfo.PropertyName == "OrgId")
{
var orgId = ((dynamic)entityInfo.EntityValue).OrgId;
if (orgId == null || orgId == 0)
entityInfo.SetValue(user.GetOrgId());
}
if (entityInfo.PropertyName == "CreateBy")
{
if (!user.UserId.IsNullOrEmpty())
{
entityInfo.SetValue(user.UserId);
}
else
{
entityInfo.SetValue(1288018625843826688);
}
}
if (entityInfo.PropertyName == "Deleted")
entityInfo.SetValue(false);
}
// 更新操作
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
if (entityInfo.PropertyName == "UpdateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "UpdateBy" && user != null)
entityInfo.SetValue(user.UserId);
}
};
dbProvider.Aop.OnDiffLogEvent = it =>
{
//排除日志库操作
if (Convert.ToInt64(c.ConfigId) != 1288018625843826680)
{
#region 插入日志审计表
//操作前记录 包含: 字段描述 列名 值 表名 表描述
var editBeforeData = it.BeforeData; //插入Before为null,之前还没进库
//操作后记录 包含: 字段描述 列名 值 表名 表描述
var editAfterData = it.AfterData;
var sql = it.Sql;
var parameter = it.Parameters;
var data = it.BusinessData; //这边会显示你传进来的对象
var time = it.Time;
var diffType = it.DiffType; //enum insert 、update and delete
var diffData = SqlSugarDiffUtil.GetDiff(editBeforeData,editAfterData);
var auditData = new SysLogAudit()
{
KeyId =Convert.ToInt64(diffData.Id),
Sql = it.Sql,
Param = JsonConvert.SerializeObject(it.Parameters),
OperateType = diffType.ToString(),
OldValue = JsonConvert.SerializeObject(editBeforeData),
NewValue = JsonConvert.SerializeObject(editAfterData),
DiffData = diffData.DiffData,
AopData = JsonConvert.SerializeObject(it.BusinessData),
// CreateUser = user.UserName
};
db.GetConnection(1288018625843826680).Insertable(auditData).ExecuteCommand();
#endregion
}
};
//全局过滤租户
dbProvider.QueryFilter.AddTableFilter(m => m.TenantId == user.GetTenantId());
//全局过滤机构Id
dbProvider.QueryFilter.AddTableFilter(m => m.OrgId == user.GetOrgId());
//全局软删除过滤
dbProvider.QueryFilter.AddTableFilter(m => m.Deleted == false);
}
});
services.AddSingleton(sqlSugar); //这边是SqlSugarScope用AddSingleton
return services;
}
}