using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Core.Base;
using Furion;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace BPA.SAAS.Manage.Core
{
    /// <summary>
    /// 数据库上下文对象
    /// </summary>
    public static class DbContext
    {
        /// <summary>
        /// SqlSugar 数据库实例
        /// </summary>
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration)
        {
            var connectionConfigs = App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs");
            //如果多个数数据库传 List<ConnectionConfig>
            var configConnection = new ConnectionConfig()
            {
                ConnectionString = connectionConfigs[0].ConnectionString,
                DbType = DbType.MySql,//设置数据库类型
                IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息 
                ConfigId = "default",
            };

            SqlSugarDb.SqlSugarScope(configConnection);

            SqlSugarDb.SqlSugarScopeLog(new ConnectionConfig()
            {
                ConnectionString = connectionConfigs[1].ConnectionString,
                DbType = DbType.MySql,//设置数据库类型
                IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息 
                ConfigId = "default",
            });

            SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
                db =>
                {
                    db.QueryFilter.AddTableFilter<IDeleted>(it => it.IsDeleted == 0);
                    //db.QueryFilter.AddTableFilter<IStatus>(it => it.Status == 0);
                    if (!IsSuperAdmin() && App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value != null)
                    {
                        //非管理员账户过滤加盟商数据
                        var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
                        db.QueryFilter.AddTableFilter<IGroupId>(it => it.GroupId == groupId);
                    }
                    db.Aop.DataExecuting = (oldValue, entityInfo) =>
                    {
                        //新增添加加盟商id赋值
                        var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
                        if (entityInfo.PropertyName == "GroupId" && entityInfo.OperationType == DataFilterType.InsertByObject)
                        {
                            if (oldValue == null || oldValue == Convert.DBNull)
                            {
                                entityInfo.SetValue(groupId);
                            }
                        }
                    };
                
                    //单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //过滤已删除数据
                        //db.QueryFilter.AddTableFilter<IDeleted>(it => it.IsDeleted == 0);
                        ////db.QueryFilter.AddTableFilter<IStatus>(it => it.Status == 0);
                        //if (!IsSuperAdmin())
                        //{
                        //    //非管理员账户过滤加盟商数据
                        //    var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
                        //    db.QueryFilter.AddTableFilter<IGroupId>(it => it.GroupId == groupId);
                        //}
                      
                         //Console.WriteLine(sql);//输出sql
                        Console.WriteLine($"当前SQL语句：【{sql}】，参数：【{string.Join(",", pars.Select(t => t.Value))}】");
                    };
                });

            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
        // <summary>
        /// 判断是不是超级管理员
        /// </summary>
        /// <returns></returns>
        private static bool IsSuperAdmin()
        {
            if (App.User == null) return false;
            var sd = App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value;
            return App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == "1";
        }
    }
}