using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MilitaryTrainingManagement.Data;
using MilitaryTrainingManagement.Models.Enums;

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 统计数据控制器
/// </summary>
[Authorize]
public class StatsController : BaseApiController
{
    private readonly ApplicationDbContext _context;

    public StatsController(ApplicationDbContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 获取首页统计数据
    /// </summary>
    [HttpGet("dashboard")]
    public async Task<IActionResult> GetDashboardStats()
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();

        if (unitId == null || unitLevel == null)
            return Unauthorized(new { message = "无法获取用户组织信息" });

        // 获取当前单位及下级单位ID列表
        var unitIds = await GetUnitAndSubordinateIds(unitId.Value);

        // 统计配额数
        int allocationsCount;
        if (unitLevel == OrganizationalLevel.Division)
        {
            // 师团级：统计创建的配额数
            allocationsCount = await _context.MaterialAllocations
                .Where(a => a.CreatedByUnitId == unitId.Value)
                .CountAsync();
        }
        else
        {
            // 团部及以下：统计分配给本单位及下级单位的配额数
            allocationsCount = await _context.MaterialAllocations
                .Include(a => a.Distributions)
                .Where(a => a.Distributions.Any(d => unitIds.Contains(d.TargetUnitId)))
                .CountAsync();
        }

        // 统计完成率
        var distributions = await _context.AllocationDistributions
            .Where(d => unitIds.Contains(d.TargetUnitId))
            .ToListAsync();

        decimal completionRate = 0;
        if (distributions.Any())
        {
            var totalQuota = distributions.Sum(d => d.UnitQuota);
            var totalCompletion = distributions.Sum(d => d.ActualCompletion ?? 0);
            if (totalQuota > 0)
            {
                completionRate = Math.Round((totalCompletion / totalQuota) * 100, 1);
            }
        }

        // 统计人员数
        var personnelCount = await _context.Personnel
            .Where(p => unitIds.Contains(p.SubmittedByUnitId) && p.Status == PersonnelStatus.Approved)
            .CountAsync();

        // 统计待审批数（仅师团级别显示）
        var pendingApprovals = 0;
        if (unitLevel == OrganizationalLevel.Division)
        {
            pendingApprovals = await _context.ApprovalRequests
                .Where(r => r.Status == ApprovalStatus.Pending)
                .CountAsync();

            // 加上待审批的人员
            pendingApprovals += await _context.Personnel
                .Where(p => p.Status == PersonnelStatus.Pending)
                .CountAsync();
        }

        return Ok(new
        {
            allocations = allocationsCount,
            completionRate = completionRate,
            personnel = personnelCount,
            pendingApprovals = pendingApprovals
        });
    }

    /// <summary>
    /// 获取各团物资配额统计（饼状图数据）
    /// </summary>
    [HttpGet("regiment-allocations")]
    public async Task<IActionResult> GetRegimentAllocationsStats()
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();

        if (unitId == null || unitLevel == null)
            return Unauthorized(new { message = "无法获取用户组织信息" });

        // 获取所有团级单位
        List<int> regimentIds;
        if (unitLevel == OrganizationalLevel.Division)
        {
            // 师团级：获取所有下属团
            regimentIds = await _context.OrganizationalUnits
                .Where(u => u.ParentId == unitId.Value && u.Level == OrganizationalLevel.Regiment)
                .Select(u => u.Id)
                .ToListAsync();
        }
        else if (unitLevel == OrganizationalLevel.Regiment)
        {
            // 团级：只显示自己
            regimentIds = new List<int> { unitId.Value };
        }
        else
        {
            // 营部及以下：获取所属团
            var currentUnit = await _context.OrganizationalUnits.FindAsync(unitId.Value);
            if (currentUnit == null)
                return Ok(new List<object>());

            // 向上查找团级单位
            var parentUnit = currentUnit;
            while (parentUnit != null && parentUnit.Level != OrganizationalLevel.Regiment)
            {
                if (parentUnit.ParentId == null) break;
                parentUnit = await _context.OrganizationalUnits.FindAsync(parentUnit.ParentId);
            }

            if (parentUnit?.Level == OrganizationalLevel.Regiment)
            {
                regimentIds = new List<int> { parentUnit.Id };
            }
            else
            {
                return Ok(new List<object>());
            }
        }

        var result = new List<object>();

        foreach (var regimentId in regimentIds)
        {
            var regiment = await _context.OrganizationalUnits.FindAsync(regimentId);
            if (regiment == null) continue;

            // 获取该团及下级单位的所有ID
            var unitIds = await GetUnitAndSubordinateIds(regimentId);

            // 获取分配给该团及下级单位的所有配额
            var distributions = await _context.AllocationDistributions
                .Where(d => unitIds.Contains(d.TargetUnitId))
                .ToListAsync();

            var totalQuota = distributions.Sum(d => d.UnitQuota);
            var totalConsumed = distributions.Sum(d => d.ActualCompletion ?? 0);

            result.Add(new
            {
                regimentId = regimentId,
                regimentName = regiment.Name,
                totalQuota = totalQuota,
                totalConsumed = totalConsumed,
                percentage = totalQuota > 0 ? Math.Round((totalConsumed / totalQuota) * 100, 1) : 0
            });
        }

        return Ok(result);
    }

    private async Task<List<int>> GetUnitAndSubordinateIds(int unitId)
    {
        var result = new List<int> { unitId };
        var children = await _context.OrganizationalUnits
            .Where(u => u.ParentId == unitId)
            .Select(u => u.Id)
            .ToListAsync();

        foreach (var childId in children)
        {
            var subIds = await GetUnitAndSubordinateIds(childId);
            result.AddRange(subIds);
        }

        return result;
    }
}
