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 EquipmentCalibrationRepository : AppRepositoryBase<EquipmentCalibrationEntity>, IEquipmentCalibrationRepository
    {
        public EquipmentCalibrationRepository(UnitOfWorkManagerCloud uowm) : base(uowm)
        {
        }

        /// <summary>
        /// 根据设备ID获取校验记录
        /// </summary>
        public async Task<List<EquipmentCalibrationEntity>> GetByEquipmentIdAsync(long equipmentId)
        {
            return await Select
                .Where(c => c.EquipmentId == equipmentId)
                .Where(c => c.IsDeleted == false)
                .OrderByDescending(c => c.CalibrationDate)
                .ToListAsync();
        }

        /// <summary>
        /// 检查设备是否有进行中的校验
        /// </summary>
        public async Task<bool> HasInProgressCalibrationAsync(long equipmentId)
        {
            return await Select
                .Where(c => c.EquipmentId == equipmentId)
                .Where(c => c.Status == CalibrationStatus.InProgress)
                .Where(c => c.IsDeleted == false)
                .AnyAsync();
        }

        /// <summary>
        /// 获取指定日期需要校验的设备ID列表
        /// </summary>
        public async Task<List<long>> GetCalibrationEquipmentIdsAsync(DateTime date)
        {
            // 获取计划在指定日期进行校验的设备ID
            var plannedCalibrationIds = await Select
                .Where(c => c.CalibrationDate.Date == date.Date)
                .Where(c => c.Status == CalibrationStatus.Planned || c.Status == CalibrationStatus.InProgress)
                .Where(c => c.IsDeleted == false)
                .ToListAsync(c => c.EquipmentId);

            // 获取进行中的校验（可能跨日）
            var inProgressCalibrationIds = await Select
                .Where(c => c.Status == CalibrationStatus.InProgress)
                .Where(c => c.StartTime.HasValue && c.StartTime.Value.Date <= date.Date)
                .Where(c => !c.EndTime.HasValue || c.EndTime.Value.Date >= date.Date)
                .Where(c => c.IsDeleted == false)
                .ToListAsync(c => c.EquipmentId);

            // 合并去重
            var allCalibrationIds = plannedCalibrationIds
                .Union(inProgressCalibrationIds)
                .Distinct()
                .ToList();

            return allCalibrationIds;
        }
    }
}