using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MilitaryTrainingManagement.Data;
using MilitaryTrainingManagement.Models.DTOs;
using MilitaryTrainingManagement.Models.Entities;
using MilitaryTrainingManagement.Services.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 组织管理控制器
/// </summary>
[Authorize]
public class OrganizationsController : BaseApiController
{
    private readonly IOrganizationService _organizationService;
    private readonly IAuthenticationService _authService;
    private readonly ApplicationDbContext _context;
    private readonly IAuditService _auditService;

    public OrganizationsController(
        IOrganizationService organizationService, 
        IAuthenticationService authService,
        ApplicationDbContext context,
        IAuditService auditService)
    {
        _organizationService = organizationService;
        _authService = authService;
        _context = context;
        _auditService = auditService;
    }
    
    private string? GetClientIpAddress()
    {
        return HttpContext.Connection.RemoteIpAddress?.ToString();
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var units = await _organizationService.GetAllAsync();
        return Ok(units);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var unit = await _organizationService.GetByIdAsync(id);
        if (unit == null)
        {
            return NotFound();
        }
        return Ok(unit);
    }

    [HttpGet("{id}/subordinates")]
    public async Task<IActionResult> GetSubordinates(int id)
    {
        var subordinates = await _organizationService.GetSubordinatesAsync(id);
        return Ok(subordinates);
    }

    /// <summary>
    /// 获取可用于配额分配的单位列表（包含当前单位，只包含师级和团级）
    /// </summary>
    [HttpGet("{id}/allocation-units")]
    public async Task<IActionResult> GetAllocationUnits(int id)
    {
        var unit = await _organizationService.GetByIdAsync(id);
        if (unit == null)
        {
            return NotFound(new { message = "组织不存在" });
        }

        var units = new List<OrganizationalUnit>();
        
        // 添加当前单位（师级）
        units.Add(unit);
        
        // 获取所有下级单位
        var subordinates = await _organizationService.GetSubordinatesAsync(id);
        
        // 只保留师级和团级单位
        var filteredSubordinates = subordinates.Where(u => 
            u.Level == Models.Enums.OrganizationalLevel.Division || 
            u.Level == Models.Enums.OrganizationalLevel.Regiment
        );
        
        units.AddRange(filteredSubordinates);
        
        return Ok(units);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateOrganizationRequest request)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        var unit = await _organizationService.CreateAsync(request.Name, request.Level, request.ParentId);
        
        // 记录审计日志
        await _auditService.LogApprovalAsync(
            "OrganizationalUnit",
            unit.Id,
            "Create",
            $"创建组织单位：{request.Name}，级别：{request.Level}",
            userId,
            unitId,
            GetClientIpAddress());
        
        return CreatedAtAction(nameof(GetById), new { id = unit.Id }, unit);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateOrganizationRequest request)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        var unit = await _organizationService.UpdateAsync(id, request.Name);
        
        // 记录审计日志
        await _auditService.LogApprovalAsync(
            "OrganizationalUnit",
            id,
            "Update",
            $"更新组织单位名称为：{request.Name}",
            userId,
            unitId,
            GetClientIpAddress());
        
        return Ok(unit);
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        // 获取组织信息用于日志
        var orgUnit = await _organizationService.GetByIdAsync(id);
        var orgName = orgUnit?.Name ?? "未知";
        
        try
        {
            await _organizationService.DeleteAsync(id);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "OrganizationalUnit",
                id,
                "Delete",
                $"删除组织单位：{orgName}",
                userId,
                unitId,
                GetClientIpAddress());
            
            return NoContent();
        }
        catch (ArgumentException ex)
        {
            return NotFound(new { message = ex.Message });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 获取组织关联的账户列表
    /// </summary>
    [HttpGet("{id}/accounts")]
    public async Task<IActionResult> GetAccounts(int id)
    {
        var unit = await _organizationService.GetByIdAsync(id);
        if (unit == null)
        {
            return NotFound(new { message = "组织不存在" });
        }

        var accounts = await _context.UserAccounts
            .Where(u => u.OrganizationalUnitId == id)
            .Select(u => new
            {
                u.Id,
                u.Username,
                u.PlainPassword,
                u.DisplayName,
                u.IsActive,
                u.CreatedAt,
                u.LastLoginAt
            })
            .ToListAsync();

        return Ok(accounts);
    }

    /// <summary>
    /// 为组织创建账户
    /// </summary>
    [HttpPost("{id}/accounts")]
    public async Task<IActionResult> CreateAccount(int id, [FromBody] CreateAccountRequest request)
    {
        var unit = await _organizationService.GetByIdAsync(id);
        if (unit == null)
        {
            return NotFound(new { message = "组织不存在" });
        }

        // 检查用户名是否已存在
        var existingUser = await _context.UserAccounts
            .FirstOrDefaultAsync(u => u.Username == request.Username);
        if (existingUser != null)
        {
            return BadRequest(new { message = "用户名已存在" });
        }

        var account = new UserAccount
        {
            Username = request.Username,
            PasswordHash = _authService.HashPassword(request.Password),
            PlainPassword = request.Password, // 保存明文密码供管理员查看
            DisplayName = unit.Name + "管理员",
            OrganizationalUnitId = id,
            CreatedAt = DateTime.UtcNow
        };

        _context.UserAccounts.Add(account);
        await _context.SaveChangesAsync();

        // 记录审计日志
        var currentUnitId = GetCurrentUnitId();
        var currentUserId = GetCurrentUserId();
        await _auditService.LogApprovalAsync(
            "UserAccount",
            account.Id,
            "Create",
            $"创建账户：{request.Username}，所属组织：{unit.Name}",
            currentUserId,
            currentUnitId,
            GetClientIpAddress());

        return Ok(new { message = "账户创建成功", username = account.Username });
    }

    /// <summary>
    /// 删除账户
    /// </summary>
    [HttpDelete("{organizationId}/accounts/{accountId}")]
    public async Task<IActionResult> DeleteAccount(int organizationId, int accountId)
    {
        var account = await _context.UserAccounts
            .FirstOrDefaultAsync(u => u.Id == accountId && u.OrganizationalUnitId == organizationId);

        if (account == null)
        {
            return NotFound(new { message = "账户不存在" });
        }

        // 检查是否有关联的上报记录
        var hasConsumptionReports = await _context.ConsumptionReports
            .AnyAsync(r => r.ReportedByUserId == accountId);
        if (hasConsumptionReports)
        {
            return BadRequest(new { message = "该账户有上报记录，无法删除" });
        }

        // 检查是否有关联的配额分配上报
        var hasDistributionReports = await _context.AllocationDistributions
            .AnyAsync(d => d.ReportedByUserId == accountId);
        if (hasDistributionReports)
        {
            return BadRequest(new { message = "该账户有配额上报记录，无法删除" });
        }

        // 检查是否有关联的人员审批历史
        var hasApprovalHistory = await _context.PersonnelApprovalHistories
            .AnyAsync(h => h.ReviewedByUserId == accountId);
        if (hasApprovalHistory)
        {
            return BadRequest(new { message = "该账户有审批记录，无法删除" });
        }

        var username = account.Username;
        _context.UserAccounts.Remove(account);
        await _context.SaveChangesAsync();

        // 记录审计日志
        var currentUnitId = GetCurrentUnitId();
        var currentUserId = GetCurrentUserId();
        await _auditService.LogApprovalAsync(
            "UserAccount",
            accountId,
            "Delete",
            $"删除账户：{username}",
            currentUserId,
            currentUnitId,
            GetClientIpAddress());

        return Ok(new { message = "账户删除成功" });
    }
}
