using DotNetCore.CAP;
using Furion;
using Microsoft.Extensions.DependencyInjection;
using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YBDevice.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //数据库配置
            services.AddSqlSugar(new ConnectionConfig
            {
                ConnectionString = App.Configuration["NirvanaConnection"],//连接字符串
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute //从特性读取主键自增信息
            },
            db =>
            {
                //处理日志事务
#if DEBUG
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    if (sql.StartsWith("SELECT"))
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                    }
                    if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    if (sql.StartsWith("DELETE"))
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                    }
                    //App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
                    App.PrintToMiniProfiler("SqlSugar", "Info", SqlProfiler.ParameterFormat(sql, pars));
                    Console.WriteLine(sql);
                    Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
                    Console.WriteLine();
                };
#endif
                //审计日志
                db.Aop.OnDiffLogEvent = async it =>
                {
                    //获取当前操作客户ID，客户名称
                    var user = App.User;
                    if (user == null)
                    {
                        return;
                    }
                    if (!user.HasClaim(x => x.Type == "BusinessId"))
                    {
                        return;
                    }
                    //操作前记录
                    var editBeforeData = it.BeforeData;
                    if (editBeforeData == null)
                    {
                        return;
                    }
                    //操作后记录
                    var editAfterData = it.AfterData;
                    if(editAfterData == null)
                    {
                        return;
                    }
                    if(it.BusinessData == null)
                    {
                        return;
                    }
                    var data = it.BusinessData as AduitLogS2SDto;
                    var time = it.Time;
                    var difftype = it.DiffType;
                    var bclaim = user.FindFirst("BusinessId");
                    int BusinessId = bclaim != null ? bclaim.Value.ToInt() : 0;
                    var rclaim = user.FindFirst("RealName");
                    string RealName = rclaim != null ? rclaim.Value.ToStr() : "未知";
                    string title = data != null ? data.Title : (difftype == DiffType.insert ? "添加" : (difftype == DiffType.update ? "更新" : "删除"));
                    //增加审计日志
                    var _cap = App.RootServices.GetService<ICapPublisher>();
                    if (_cap == null)
                    {
                        return;
                    }
                    List<AduitLogS2SDto> list = new List<AduitLogS2SDto>();
                    foreach (var item in editBeforeData)
                    {
                        foreach (var column in item.Columns)
                        {
                            var afterdata = editAfterData.FirstOrDefault(x => x.TableName == item.TableName);
                            if (afterdata != null)
                            {
                                var aftercolumndata = afterdata.Columns.FirstOrDefault(x => x.ColumnName == column.ColumnName);
                                if (aftercolumndata != null && !aftercolumndata.Value.Equals(column.Value))
                                {
                                    list.Add(new AduitLogS2SDto
                                    {
                                        BusinessId = BusinessId,
                                        ColumnName = column.ColumnName,
                                        NewValue = aftercolumndata.Value.ToString(),
                                        OldValue = column.Value.ToString(),
                                        Operate = difftype,
                                        TableName = item.TableName,
                                        Title = title,
                                        UserName = RealName
                                    });
                                }
                            }
                        }
                    }
                    foreach (var item in list)
                    {
                        await _cap.PublishAsync("system.service.insertauditlogger", item);
                    }
                };
            }
            );
        }
    }
}
