using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MilitaryTrainingManagement.Authorization;
using MilitaryTrainingManagement.Models.DTOs;
using MilitaryTrainingManagement.Models.Enums;
using MilitaryTrainingManagement.Services.Interfaces;

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 上报管理控制器
/// 需求：3.1, 3.2, 4.1, 4.2, 4.3
/// </summary>
[Authorize]
public class ReportsController : BaseApiController
{
    private readonly IReportingService _reportingService;
    private readonly IDataAggregatorService _dataAggregatorService;
    private readonly IOrganizationalAuthorizationService _authorizationService;

    public ReportsController(
        IReportingService reportingService,
        IDataAggregatorService dataAggregatorService,
        IOrganizationalAuthorizationService authorizationService)
    {
        _reportingService = reportingService;
        _dataAggregatorService = dataAggregatorService;
        _authorizationService = authorizationService;
    }

    /// <summary>
    /// 获取当前单位的分配记录
    /// 需求3.1：显示类别、物资名称、单位、配额、实际完成和完成率
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetByUnit([FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10)
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        var allDistributions = await _reportingService.GetDistributionsByUnitAsync(unitId.Value);
        var distributionsList = allDistributions.ToList();
        var totalCount = distributionsList.Count;
        
        var pagedDistributions = distributionsList
            .Skip((pageNumber - 1) * pageSize)
            .Take(pageSize)
            .Select(MapToReportResponse);
            
        return Ok(new
        {
            items = pagedDistributions,
            totalCount,
            pageNumber,
            pageSize,
            totalPages = (int)Math.Ceiling(totalCount / (double)pageSize)
        });
    }

    /// <summary>
    /// 获取指定单位的分配记录
    /// 需求4.4：基于组织层级的数据访问控制
    /// </summary>
    [HttpGet("unit/{targetUnitId}")]
    public async Task<IActionResult> GetByTargetUnit(int targetUnitId)
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();
        if (unitId == null || unitLevel == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        // 检查访问权限
        var canAccess = await _reportingService.CanViewUnitDataAsync(unitId.Value, targetUnitId, unitLevel.Value);
        if (!canAccess)
        {
            return Forbid();
        }

        var distributions = await _reportingService.GetDistributionsByUnitAsync(targetUnitId);
        var response = distributions.Select(MapToReportResponse);
        return Ok(response);
    }

    /// <summary>
    /// 获取分配记录详情
    /// 需求4.3：提供具体上报记录的访问，包括时间戳和上报人员
    /// </summary>
    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();
        if (unitId == null || unitLevel == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        var distribution = await _reportingService.GetDistributionByIdAsync(id);
        if (distribution == null)
        {
            return NotFound(new { message = "分配记录不存在" });
        }

        // 检查访问权限
        var canAccess = await _reportingService.CanViewUnitDataAsync(unitId.Value, distribution.TargetUnitId, unitLevel.Value);
        if (!canAccess)
        {
            return Forbid();
        }

        return Ok(MapToReportResponse(distribution));
    }

    /// <summary>
    /// 提交上报数据
    /// 需求3.2：允许团级用户输入实际完成值并提交到营级
    /// 需求3.5：连级用户只能查看，不能直接上报
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> SubmitReport([FromBody] SubmitReportRequest request)
    {
        var userId = GetCurrentUserId();
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();

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

        // 需求3.5：连级用户只能查看，不能直接上报
        if (unitLevel == OrganizationalLevel.Company)
        {
            return Forbid();
        }

        // 验证请求
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            // 检查分配记录是否存在
            var distribution = await _reportingService.GetDistributionByIdAsync(request.DistributionId);
            if (distribution == null)
            {
                return NotFound(new { message = "分配记录不存在" });
            }

            // 检查是否有权限为该单位提交上报
            var canReport = await _reportingService.CanViewUnitDataAsync(unitId.Value, distribution.TargetUnitId, unitLevel.Value);
            if (!canReport)
            {
                return Forbid();
            }

            var result = await _reportingService.SubmitReportAsync(
                request.DistributionId,
                request.ActualCompletion,
                userId.Value);

            return Ok(MapToReportResponse(result));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (UnauthorizedAccessException)
        {
            return Forbid();
        }
    }

    /// <summary>
    /// 更新上报数据
    /// 需求5.1：允许在上级批准前编辑已提交的报告
    /// </summary>
    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateReport(int id, [FromBody] SubmitReportRequest request)
    {
        var userId = GetCurrentUserId();
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();

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

        // 连级用户不能修改
        if (unitLevel == OrganizationalLevel.Company)
        {
            return Forbid();
        }

        try
        {
            var distribution = await _reportingService.GetDistributionByIdAsync(id);
            if (distribution == null)
            {
                return NotFound(new { message = "分配记录不存在" });
            }

            // 检查是否有权限修改
            var canModify = await _reportingService.CanViewUnitDataAsync(unitId.Value, distribution.TargetUnitId, unitLevel.Value);
            if (!canModify)
            {
                return Forbid();
            }

            var result = await _reportingService.SubmitReportAsync(id, request.ActualCompletion, userId.Value);
            return Ok(MapToReportResponse(result));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 获取汇总数据
    /// 需求4.1：师团用户查看所有下级单位的总配额、实际完成和整体完成率
    /// 需求4.2：团级用户查看直接下级单位的详细数据
    /// 需求2.2：对营部及以下级别用户应用可见性过滤
    /// </summary>
    [HttpGet("aggregated")]
    public async Task<IActionResult> GetAggregatedData()
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();
        if (unitId == null || unitLevel == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        try
        {
            var data = await _reportingService.GetHierarchicalAggregatedDataAsync(unitId.Value, unitLevel.Value);
            return Ok(data);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 获取指定单位的汇总数据
    /// 需求4.4：基于组织层级的数据访问控制
    /// </summary>
    [HttpGet("aggregated/{targetUnitId}")]
    public async Task<IActionResult> GetAggregatedDataByUnit(int targetUnitId)
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();
        if (unitId == null || unitLevel == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        // 检查访问权限
        var canAccess = await _reportingService.CanViewUnitDataAsync(unitId.Value, targetUnitId, unitLevel.Value);
        if (!canAccess)
        {
            return Forbid();
        }

        try
        {
            var data = await _dataAggregatorService.CalculateHierarchicalAggregationAsync(targetUnitId);
            return Ok(data);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 获取按配额分组的汇总数据
    /// </summary>
    [HttpGet("aggregated/by-allocation")]
    public async Task<IActionResult> GetAggregatedByAllocation()
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        var data = await _dataAggregatorService.AggregateByAllocationAsync(unitId.Value);
        return Ok(data);
    }

    /// <summary>
    /// 获取直接下级单位汇总
    /// 需求4.2：显示直接下级单位的详细配额、实际完成和完成率数据
    /// </summary>
    [HttpGet("subordinates")]
    public async Task<IActionResult> GetSubordinateSummaries()
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        var summaries = await _dataAggregatorService.GetDirectSubordinateSummariesAsync(unitId.Value);
        return Ok(summaries);
    }

    /// <summary>
    /// 获取详细上报记录
    /// 需求4.3：提供具体上报记录的访问，包括时间戳和上报人员
    /// </summary>
    [HttpGet("detailed")]
    public async Task<IActionResult> GetDetailedReports()
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();
        if (unitId == null || unitLevel == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        var reports = await _reportingService.GetDetailedReportsAsync(unitId.Value, unitLevel.Value);
        return Ok(reports);
    }

    /// <summary>
    /// 计算完成率
    /// 需求3.3：完成率 = 实际完成 / 配额
    /// </summary>
    [HttpGet("{id}/completion-rate")]
    public async Task<IActionResult> GetCompletionRate(int id)
    {
        var unitId = GetCurrentUnitId();
        var unitLevel = GetCurrentUnitLevel();
        if (unitId == null || unitLevel == null)
        {
            return Unauthorized(new { message = "无法获取用户组织信息" });
        }

        var distribution = await _reportingService.GetDistributionByIdAsync(id);
        if (distribution == null)
        {
            return NotFound(new { message = "分配记录不存在" });
        }

        // 检查访问权限
        var canAccess = await _reportingService.CanViewUnitDataAsync(unitId.Value, distribution.TargetUnitId, unitLevel.Value);
        if (!canAccess)
        {
            return Forbid();
        }

        var rate = await _reportingService.CalculateCompletionRateAsync(id);
        return Ok(new { completionRate = rate });
    }

    /// <summary>
    /// 映射分配记录到响应DTO
    /// </summary>
    private static ReportResponse MapToReportResponse(Models.Entities.AllocationDistribution distribution)
    {
        return new ReportResponse
        {
            Id = distribution.Id,
            AllocationId = distribution.AllocationId,
            Category = distribution.Allocation?.Category ?? string.Empty,
            MaterialName = distribution.Allocation?.MaterialName ?? string.Empty,
            Unit = distribution.Allocation?.Unit ?? string.Empty,
            TargetUnitId = distribution.TargetUnitId,
            TargetUnitName = distribution.TargetUnit?.Name ?? string.Empty,
            UnitQuota = distribution.UnitQuota,
            ActualCompletion = distribution.ActualCompletion,
            CompletionRate = distribution.CompletionRate,
            ReportedAt = distribution.ReportedAt,
            ReportedByUserId = distribution.ReportedByUserId,
            ReportedByUserName = distribution.ReportedByUser?.DisplayName
        };
    }
}
