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

namespace NPP.SmartSchedue.Api.Repositories.Notification;

/// <summary>
/// 通知设置仓储实现
/// </summary>
public class NotificationSettingRepository : AppRepositoryBase<NotificationSettingEntity>, INotificationSettingRepository
{
    public NotificationSettingRepository(UnitOfWorkManagerCloud uowm) : base(uowm)
    {
    }

    /// <summary>
    /// 根据启用状态获取通知设置列表
    /// </summary>
    public async Task<List<NotificationSettingEntity>> GetByEnabledAsync(bool enabled)
    {
        return await Select
            .Where(n => n.IsEnabled == enabled)
            .Include(n => n.PersonnelGroup)
            .ToListAsync();
    }

    /// <summary>
    /// 根据人员组ID获取通知设置列表
    /// </summary>
    public async Task<List<NotificationSettingEntity>> GetByPersonnelGroupIdAsync(long personnelGroupId)
    {
        return await Select
            .Where(n => n.PersonnelGroupId == personnelGroupId)
            .Include(n => n.PersonnelGroup)
            .ToListAsync();
    }

    /// <summary>
    /// 根据通知方式获取通知设置列表
    /// </summary>
    public async Task<List<NotificationSettingEntity>> GetByNotificationTypeAsync(int notificationType)
    {
        return await Select
            .Where(n => (n.NotificationTypes & notificationType) != 0)
            .Where(n => n.IsEnabled == true)
            .Include(n => n.PersonnelGroup)
            .ToListAsync();
    }

    /// <summary>
    /// 根据触发条件获取匹配的通知设置列表
    /// 这里实现一个简化的匹配逻辑，实际项目中可能需要更复杂的条件匹配引擎
    /// </summary>
    public async Task<List<NotificationSettingEntity>> GetMatchingNotificationSettingsAsync(
        string businessType, 
        Dictionary<string, object> businessContext)
    {
        var allSettings = await Select
            .Where(n => n.IsEnabled == true)
            .Include(n => n.PersonnelGroup)
            .ToListAsync();

        // 过滤匹配的通知设置
        var matchingSettings = new List<NotificationSettingEntity>();
        
        foreach (var setting in allSettings)
        {
            if (string.IsNullOrWhiteSpace(setting.TriggerConditions))
            {
                // 如果没有设置触发条件，则匹配所有业务类型
                matchingSettings.Add(setting);
                continue;
            }

            try
            {
                // 解析触发条件（简化实现，实际项目中可能需要更复杂的条件引擎）
                var triggerConditions = JsonConvert.DeserializeObject<Dictionary<string, object>>(setting.TriggerConditions);
                
                // 检查业务类型匹配
                if (triggerConditions.ContainsKey("businessType"))
                {
                    var requiredBusinessType = triggerConditions["businessType"]?.ToString();
                    if (!string.IsNullOrWhiteSpace(requiredBusinessType) && 
                        !string.Equals(requiredBusinessType, businessType, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                }

                // 这里可以添加更多的条件匹配逻辑
                // 例如：检查业务数据中的特定字段值等

                matchingSettings.Add(setting);
            }
            catch (JsonException)
            {
                // 触发条件格式错误，跳过此设置
                continue;
            }
        }

        return matchingSettings;
    }

    /// <summary>
    /// 检查通知设置名称是否存在
    /// </summary>
    public async Task<bool> ExistsNotificationNameAsync(string notificationName, long? excludeId = null)
    {
        var query = Select.Where(n => n.NotificationName == notificationName);
        
        if (excludeId.HasValue)
            query = query.Where(n => n.Id != excludeId.Value);
            
        return await query.AnyAsync();
    }

    /// <summary>
    /// 获取需要在当前时间执行的通知设置列表
    /// 根据决策点2：简单时间段，只支持开始时间-结束时间
    /// </summary>
    public async Task<List<NotificationSettingEntity>> GetActiveNotificationSettingsForTimeAsync(DateTime currentTime)
    {
        var allEnabledSettings = await Select
            .Where(n => n.IsEnabled == true)
            .Where(n => !string.IsNullOrWhiteSpace(n.StartTime) && !string.IsNullOrWhiteSpace(n.EndTime))
            .Include(n => n.PersonnelGroup)
            .ToListAsync();

        var activeSettings = new List<NotificationSettingEntity>();
        var currentTimeOnly = TimeOnly.FromDateTime(currentTime);

        foreach (var setting in allEnabledSettings)
        {
            try
            {
                if (TimeOnly.TryParseExact(setting.StartTime, "HH:mm", out var startTime) &&
                    TimeOnly.TryParseExact(setting.EndTime, "HH:mm", out var endTime))
                {
                    // 处理跨天的情况（如：22:00-06:00）
                    if (startTime <= endTime)
                    {
                        // 同一天内的时间段
                        if (currentTimeOnly >= startTime && currentTimeOnly <= endTime)
                        {
                            activeSettings.Add(setting);
                        }
                    }
                    else
                    {
                        // 跨天的时间段
                        if (currentTimeOnly >= startTime || currentTimeOnly <= endTime)
                        {
                            activeSettings.Add(setting);
                        }
                    }
                }
            }
            catch
            {
                // 时间格式解析失败，跳过此设置
                continue;
            }
        }

        return activeSettings;
    }
}