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.Contracts.Core.Enums;
using NPP.SmartSchedue.Api.Core.Repositories;
using ZhonTai.Admin.Core.Db.Transaction;

namespace NPP.SmartSchedue.Api.Repositories.Notification;

/// <summary>
/// 人员组仓储实现
/// </summary>
public class PersonnelGroupRepository : AppRepositoryBase<PersonnelGroupEntity>, IPersonnelGroupRepository
{
    public PersonnelGroupRepository(UnitOfWorkManagerCloud uowm) : base(uowm)
    {
    }

    /// <summary>
    /// 根据启用状态获取人员组列表
    /// </summary>
    public async Task<List<PersonnelGroupEntity>> GetByEnabledAsync(bool enabled)
    {
        return await Select
            .Where(p => p.IsEnabled == enabled)
            .ToListAsync();
    }

    /// <summary>
    /// 根据人员组类型获取人员组列表
    /// </summary>
    public async Task<List<PersonnelGroupEntity>> GetByGroupTypeAsync(PersonnelGroupTypeEnum groupType)
    {
        return await Select
            .Where(p => p.GroupType == (int)groupType)
            .ToListAsync();
    }

    /// <summary>
    /// 检查人员组名称是否存在
    /// </summary>
    public async Task<bool> ExistsGroupNameAsync(string groupName, long? excludeId = null)
    {
        var query = Select.Where(p => p.GroupName == groupName);
        
        if (excludeId.HasValue)
            query = query.Where(p => p.Id != excludeId.Value);
            
        return await query.AnyAsync();
    }

    /// <summary>
    /// 获取包含指定人员的人员组列表
    /// </summary>
    public async Task<List<PersonnelGroupEntity>> GetGroupsContainingPersonnelAsync(long personnelId)
    {
        var allGroups = await Select.Where(p => p.IsEnabled == true).ToListAsync();
        var matchingGroups = new List<PersonnelGroupEntity>();

        foreach (var group in allGroups)
        {
            try
            {
                // 检查静态人员列表
                if (!string.IsNullOrWhiteSpace(group.StaticPersonnelIds))
                {
                    var staticPersonnelIds = JsonConvert.DeserializeObject<List<long>>(group.StaticPersonnelIds);
                    if (staticPersonnelIds != null && staticPersonnelIds.Contains(personnelId))
                    {
                        matchingGroups.Add(group);
                        continue;
                    }
                }

                // 这里需要根据动态规则检查人员是否属于该组
                // 由于需要查询人员表，这部分逻辑可能需要在Service层实现
                // 或者通过额外的查询来完成
            }
            catch (JsonException)
            {
                // JSON格式错误，跳过
                continue;
            }
        }

        return matchingGroups;
    }

    /// <summary>
    /// 获取包含指定部门的人员组列表
    /// </summary>
    public async Task<List<PersonnelGroupEntity>> GetGroupsContainingDepartmentAsync(long departmentId)
    {
        var allGroups = await Select.Where(p => p.IsEnabled == true).ToListAsync();
        var matchingGroups = new List<PersonnelGroupEntity>();

        foreach (var group in allGroups)
        {
            try
            {
                // 检查动态部门规则
                if (!string.IsNullOrWhiteSpace(group.DynamicDepartmentIds))
                {
                    var departmentIds = JsonConvert.DeserializeObject<List<long>>(group.DynamicDepartmentIds);
                    if (departmentIds != null && departmentIds.Contains(departmentId))
                    {
                        matchingGroups.Add(group);
                    }
                }
            }
            catch (JsonException)
            {
                // JSON格式错误，跳过
                continue;
            }
        }

        return matchingGroups;
    }

    /// <summary>
    /// 获取包含指定职位的人员组列表
    /// </summary>
    public async Task<List<PersonnelGroupEntity>> GetGroupsContainingPositionAsync(string position)
    {
        var allGroups = await Select.Where(p => p.IsEnabled == true).ToListAsync();
        var matchingGroups = new List<PersonnelGroupEntity>();

        foreach (var group in allGroups)
        {
            try
            {
                // 检查动态职位规则
                if (!string.IsNullOrWhiteSpace(group.DynamicPositions))
                {
                    var positions = JsonConvert.DeserializeObject<List<string>>(group.DynamicPositions);
                    if (positions != null && positions.Any(p => 
                        string.Equals(p, position, System.StringComparison.OrdinalIgnoreCase)))
                    {
                        matchingGroups.Add(group);
                    }
                }
            }
            catch (JsonException)
            {
                // JSON格式错误，跳过
                continue;
            }
        }

        return matchingGroups;
    }

    /// <summary>
    /// 计算人员组的实际人员数量
    /// 这个方法返回一个估算值，实际计算需要在Service层进行
    /// 因为需要查询人员表和考虑动态规则
    /// </summary>
    public async Task<int> CalculatePersonnelCountAsync(long personnelGroupId)
    {
        var group = await Select.Where(p => p.Id == personnelGroupId).FirstAsync();
        if (group == null) return 0;

        int count = 0;

        try
        {
            // 统计静态人员
            if (!string.IsNullOrWhiteSpace(group.StaticPersonnelIds))
            {
                var staticPersonnelIds = JsonConvert.DeserializeObject<List<long>>(group.StaticPersonnelIds);
                if (staticPersonnelIds != null)
                {
                    count += staticPersonnelIds.Count;
                }
            }

            // 注意：动态人员的统计需要在Service层实现，因为需要查询人员表
            // 这里只返回静态人员数量作为基础值
        }
        catch (JsonException)
        {
            // JSON格式错误
        }

        return count;
    }
}