using Furion;
using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using YBEE.EQM.Core;

namespace YBEE.EQM.EntityFramework.Core
{
    [AppDbContext("DbMain", DbProvider.MySql)]
    public class DefaultDbContext : AppDbContext<DefaultDbContext>
    {
        public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
        {
            // 启用实体数据更改监听
            EnabledEntityChangedListener = true;
            // 忽略空值更新
            InsertOrUpdateIgnoreNullValues = true;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(App.Configuration.GetConnectionString("DbMain"), new MySqlServerVersion(new Version(8, 0, 31))).UseSnakeCaseNamingConvention();
        }

        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
        {
            // 获取当前事件对应上下文
            var dbContext = eventData.Context;
            // 获取所有更改，删除，新增的实体，但排除审计实体（避免死循环）
            var entities = dbContext.ChangeTracker.Entries().Where(u =>
                                        u.Entity.GetType() != typeof(SysLogOp) &&
                                        u.Entity.GetType() != typeof(SysLogVis) &&
                                        u.Entity.GetType() != typeof(SysLogEx) &&
                                        (u.State == EntityState.Modified || u.State == EntityState.Deleted || u.State == EntityState.Added)
                                        ).ToList();
            if (entities == null || entities.Count < 1)
            {
                return;
            }

            // 当前操作者信息
            var userId = App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var userName = App.User?.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
            // 当前操作者机构信息
            var orgId = App.User?.FindFirst(ClaimConst.CLAINM_ORGID)?.Value;
            var orgName = App.User?.FindFirst(ClaimConst.CLAINM_ORGNAME)?.Value;

            foreach (var entity in entities)
            {
                if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase)) ||
                    entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase<short>)) ||
                    entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase<long>))
                )
                {
                    dynamic obj;
                    if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase<short>)))
                    {
                        obj = entity.Entity as DEntityBase<short>;
                    }
                    else if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase<long>)))
                    {
                        obj = entity.Entity as DEntityBase<long>;
                    }
                    else
                    {
                        obj = entity.Entity as DEntityBase;
                    }


                    if (entity.State == EntityState.Added)
                    {
                        obj.CreateTime = DateTime.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.CreateSysUserId = int.Parse(userId);
                        }
                    }
                    else if (entity.State == EntityState.Modified)
                    {
                        // 排除创建人
                        entity.Property(nameof(DEntityBase.CreateSysUserId)).IsModified = false;
                        // 排除创建日期
                        entity.Property(nameof(DEntityBase.CreateTime)).IsModified = false;

                        obj.UpdateTime = DateTime.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.UpdateSysUserId = int.Parse(userId);
                        }
                    }
                }
            }
        }
    }
}