using AutoMapper.QueryableExtensions;
using EntityFrameworkCore.Triggered;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Triggers.AfterSaveTrigger
{
    /// <summary>
    /// 账户日志 记录账户每次操作的信息
    /// </summary>
    /// <param name="_identityUserRepository"></param>
    public class UserLogAfterTrigger(IRepository<IdentityUser> _identityUserRepository) : IAfterSaveTrigger<UserLog>
    {
        public async Task AfterSave(ITriggerContext<UserLog> context, CancellationToken cancellationToken)
        {
            var userlog = context.Entity;

            if (context.ChangeType == ChangeType.Added)
            {

                if (userlog.TargetIdentityUserId != null)
                {

                    //判断是否需要记录详情

                    if (userlog.OptType == UserOptType.AddUser || userlog.OptType == UserOptType.UpdateUser || userlog.OptType == UserOptType.UpdateUserRole
                      || userlog.OptType == UserOptType.AccountEnable || userlog.OptType == UserOptType.AccountLocked)
                    {
                        var obj = await _identityUserRepository.Where(t => t.Id == userlog.TargetIdentityUserId).Select(t => new UserLogJsonObj()
                        {
                            DepartmentName = t.DepartmentName,
                            EMail = t.EMail,
                            FirstName = t.FirstName,
                            LastName = t.LastName,
                            OrganizationName = t.OrganizationName,
                            Phone = t.Phone,
                            PositionName = t.PositionName,
                            Sex = t.Sex,
                            Status = t.Status,
                            UserCode = t.UserCode,
                            UserName = t.UserName,
                            UserRoleList = t.UserRoleList.Select(t => new UserRoleLogObj()
                            {
                                IsUserRoleDisabled = t.IsUserRoleDisabled,
                                UserTypeEnum = t.UserTypeEnum,
                                UserTypeShortName = t.UserTypeRole.UserTypeShortName
                            }).ToList()

                        }).FirstOrDefaultAsync();



                        userlog.JsonObj = obj.ToJsonStr();
                    }



                }

                if (userlog.ActionIdentityUserId != null && userlog.ActionUserName.IsNullOrWhiteSpace())
                {
                    userlog.ActionUserName = await _identityUserRepository.Where(t => t.Id == userlog.ActionIdentityUserId).Select(t => t.UserName).FirstOrDefaultAsync();
                }

                await _identityUserRepository.SaveChangesAsync();


            }
        }
    }



}
