using CoreDatabase;
using CoreDatabase.Models.Department;
using DepartmentContract.BindingModels;
using DepartmentContract.Services.IGenericEntityService;
using DepartmentContract.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using ToolsModule.ManagmentEntity;
namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntityService
{
///
/// Реализация IEmployeeService
///
public class EmployeeService :
AbstractGenerticEntityService,
IEmployeeService
{
protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, EmployeeSetBindingModel model) => OperationResultModel.Success(null);
protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, Employee entity, EmployeeGetBindingModel model)
{
if (entity.User == null)
{
return OperationResultModel.Error("Error:", "Не найден пользователь от сотрудника", ResultServiceStatusCode.NotFound);
}
if (context.Set().Any(x => x.EmployeeId == model.Id && !x.IsDeleted))
{
return OperationResultModel.Error("Error:", "Есть аудитории, у которых этот сотрудник указан ответственным", ResultServiceStatusCode.ExsistItem);
}
return OperationResultModel.Success(null);
}
protected override IQueryable AdditionalCheckingWhenReadingList(IQueryable query, EmployeeGetBindingModel model)
{
if (model.UserId.HasValue)
{
query = query.Where(x => x.UserId == model.UserId);
}
return query;
}
protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, EmployeeSetBindingModel model) => OperationResultModel.Success(null);
protected override void AdditionalDeleting(DbContext context, Employee entity, EmployeeGetBindingModel model)
{
entity.User.IsDeleted = true;
entity.User.DateDelete = DateTime.Now;
context.SaveChanges();
var links = context.Set().Where(x => x.EmployeeId == model.Id);
foreach (var link in links)
{
link.IsDeleted = true;
link.DateDelete = DateTime.Now;
}
context.SaveChanges();
}
protected override Employee GetUniqueEntity(EmployeeSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.LastName == model.LastName && x.FirstName == model.FirstName &&
x.Patronymic == model.Patronymic && x.Id != model.Id);
protected override IQueryable IncludingWhenReading(IQueryable query) => query
.Include(x => x.EmployeePosts).Include("EmployeePosts.Post");
protected override IQueryable OrderingWhenReading(IQueryable query) => query
.OrderByDescending(x => x.EmployeePosts.Max(y => y.Post.Order))
.ThenBy(x => x.LastName)
.ThenBy(x => x.FirstName);
}
}