using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NPP.SmartSchedue.Api.Contracts.Domain.Equipment;
using NPP.SmartSchedue.Api.Core.Repositories;
using ZhonTai.Admin.Core.Db.Transaction;

namespace NPP.SmartSchedue.Api.Repositories.Equipment
{
    /// <summary>
    /// 设备维护仓储实现
    /// </summary>
    public class EquipmentMaintenanceRepository : AppRepositoryBase<EquipmentMaintenanceEntity>, IEquipmentMaintenanceRepository
    {
        public EquipmentMaintenanceRepository(UnitOfWorkManagerCloud uowm) : base(uowm)
        {
        }

        /// <summary>
        /// 根据设备ID获取维护记录
        /// </summary>
        public async Task<List<EquipmentMaintenanceEntity>> GetByEquipmentIdAsync(long equipmentId)
        {
            return await Select
                .Where(m => m.EquipmentId == equipmentId)
                .Where(m => m.IsDeleted == false)
                .OrderByDescending(m => m.MaintenanceDate)
                .ToListAsync();
        }

        /// <summary>
        /// 检查设备是否有进行中的维护
        /// </summary>
        public async Task<bool> HasInProgressMaintenanceAsync(long equipmentId)
        {
            return await Select
                .Where(m => m.EquipmentId == equipmentId)
                .Where(m => m.Status == MaintenanceStatus.InProgress)
                .Where(m => m.IsDeleted == false)
                .AnyAsync();
        }

        /// <summary>
        /// 获取指定日期需要维护的设备ID列表
        /// </summary>
        public async Task<List<long>> GetMaintenanceEquipmentIdsAsync(DateTime date)
        {
            // 获取计划在指定日期进行维护的设备ID
            var plannedMaintenanceIds = await Select
                .Where(m => m.MaintenanceDate.Date == date.Date)
                .Where(m => m.Status == MaintenanceStatus.Planned || m.Status == MaintenanceStatus.InProgress)
                .Where(m => m.IsDeleted == false)
                .ToListAsync(m => m.EquipmentId);

            // 获取进行中的维护（可能跨日）
            var inProgressMaintenanceIds = await Select
                .Where(m => m.Status == MaintenanceStatus.InProgress)
                .Where(m => m.StartTime.HasValue && m.StartTime.Value.Date <= date.Date)
                .Where(m => !m.EndTime.HasValue || m.EndTime.Value.Date >= date.Date)
                .Where(m => m.IsDeleted == false)
                .ToListAsync(m => m.EquipmentId);

            // 合并去重
            var allMaintenanceIds = plannedMaintenanceIds
                .Union(inProgressMaintenanceIds)
                .Distinct()
                .ToList();

            return allMaintenanceIds;
        }
    }
}