using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.Entity.Visitor.Entity;
using Dlhis.Entity.Visitor.Enums;
using Dlhis.ScheduledTask.Attributes;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.ScheduledTask.Jobs;
///
/// 访客预约移除
///
[RecurringJob(nameof(AutoRemoveAppointmentJob), "0 0/5 * * * ?", Name = "访客预约移除")]
public class AutoRemoveAppointmentJob : BaseJob
{
///
public AutoRemoveAppointmentJob(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
///
protected override async Task RunAsync(IServiceProvider serviceProvider)
{
var now = DateTime.Now;
var details = await DbContext.Queryable()
.Where(x => (x.IsEnterDoorArea && x.DoorStatus == VisitorAppointmentDetailStatusEnumType.Arrived) ||
(x.IsEnterWorkplace && x.WorkplaceStatus == VisitorAppointmentDetailStatusEnumType.Arrived))
.ToListAsync();
foreach (var detail in details)
{
var areaCodes = GetValidAreaCodes(detail).ToList();
if (areaCodes.IsEmpty())
{
continue;
}
var existsAreaCodes = await DbContext.Queryable().Where(x => areaCodes.Contains(x.CustomCode)).Select(x => x.CustomCode).ToListAsync();
//当前分配的设备组code
var deviceGroupCodes = await DbContext.Queryable()
.Where(x => existsAreaCodes.Contains(x.CustomCode))
.Select(x => x.DeviceGroupCode)
.ToListAsync();
var deviceCodes = await DbContext.Queryable().Where(x => deviceGroupCodes.Contains(x.GroupCode)).Select(x => x.DeviceCode).ToListAsync();
var deviceUniqueNos = await DbContext.Queryable().Where(x => deviceCodes.Contains(x.Code)).Select(x => new { x.UniqueNo, x.TenantId }).ToListAsync();
await DbContext.InsertAsync(deviceUniqueNos.Select(x => new DeviceTaskEntity
{
DeviceType = DeviceTypeEnumType.Door,
DeviceUniqueNo = x.UniqueNo,
Status = DeviceTaskStatusEnumType.Wait,
UserNo = detail.UserNo,
Type = DeviceTaskEnumType.Delete,
Priority = 100,
TenantId = x.TenantId,
Source = "访客时间到期自动移除",
Version = 0
}).ToList());
if (detail.IsEnterDoorArea && detail.DoorStatus == VisitorAppointmentDetailStatusEnumType.Arrived && detail.DoorEnd <= now)
{
detail.DoorStatus = VisitorAppointmentDetailStatusEnumType.Leave;
}
if (detail.IsEnterWorkplace && detail.WorkplaceStatus == VisitorAppointmentDetailStatusEnumType.Arrived && detail.WorkplaceEnd <= now)
{
detail.WorkplaceStatus = VisitorAppointmentDetailStatusEnumType.Leave;
}
await DbContext.UpdateAsync(detail);
}
}
///
/// 获取有效的区域编码,需要根据申请时间和当前时间判断
///
///
///
private static IEnumerable GetValidAreaCodes(VisitorAppointmentDetailEntity detail)
{
var now = DateTime.Now;
if (detail.IsEnterDoorArea && detail.DoorStatus == VisitorAppointmentDetailStatusEnumType.Arrived && detail.DoorEnd <= now)
{
yield return detail.ApplyDoorArea;
}
if (detail.IsEnterWorkplace && detail.WorkplaceStatus == VisitorAppointmentDetailStatusEnumType.Arrived && detail.WorkplaceEnd <= now)
{
foreach (var item in detail.ApplyWorkplaceAreas)
{
yield return item;
}
}
}
}