using Furion;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;

namespace BPA.MES.Base.Core
{
    /// <summary>
    /// 名    称 ：数据库启动类
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：  2023/3/23 14:09:30 
    /// 描    述 ：  
    /// </summary>
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, string dbName = "ConnectionString")
        {
            //如果多个数数据库传 List<ConnectionConfig>
            var dbs = App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs")[0];
            var configConnection = new ConnectionConfig()
            {
                DbType = dbs.DbType,
                ConnectionString = dbs.ConnectionString,
                IsAutoCloseConnection = dbs.IsAutoCloseConnection,
            };
            SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
                db =>
                {
                    //单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(sql);//输出sql
                    };
                    db.Aop.DataExecuting = (oldValue, entityInfo) =>
                    {
                        if (entityInfo.PropertyName == "CreateTime" && entityInfo.OperationType == DataFilterType.InsertByObject)
                        {
                            entityInfo.SetValue(DateTime.Now);
                        };
                    };
                }
                );
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
    }
}
