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

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 人员管理控制器
/// </summary>
[Authorize]
public class PersonnelController : BaseApiController
{
    private readonly IPersonnelService _personnelService;
    private readonly IFileUploadService _fileUploadService;
    private readonly IOrganizationalAuthorizationService _authorizationService;
    private readonly IAuditService _auditService;

    public PersonnelController(
        IPersonnelService personnelService, 
        IFileUploadService fileUploadService,
        IOrganizationalAuthorizationService authorizationService,
        IAuditService auditService)
    {
        _personnelService = personnelService;
        _fileUploadService = fileUploadService;
        _authorizationService = authorizationService;
        _auditService = auditService;
    }

    /// <summary>
    /// 根据出生年月计算年龄
    /// </summary>
    private int CalculateAge(string? birthDate)
    {
        if (string.IsNullOrWhiteSpace(birthDate))
            return 25; // 如果没有出生年月，返回默认值25岁

        try
        {
            // birthDate格式为 "YYYY-MM"
            var parts = birthDate.Split('-');
            if (parts.Length != 2)
                return 25;

            if (!int.TryParse(parts[0], out var year) || !int.TryParse(parts[1], out var month))
                return 25;

            var birthDateTime = new DateTime(year, month, 1);
            var today = DateTime.Today;
            var age = today.Year - birthDateTime.Year;
            
            // 如果今年的生日还没到，年龄减1
            if (today.Month < birthDateTime.Month)
                age--;

            return age > 0 ? age : 25; // 确保年龄为正数
        }
        catch
        {
            return 25; // 解析失败返回默认值
        }
    }

    /// <summary>
    /// 获取人员列表（基于层级权限控制）
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetPersonnel(
        [FromQuery] int pageNumber = 1,
        [FromQuery] int pageSize = 10,
        [FromQuery] string? status = null,
        [FromQuery] int? unitId = null,
        [FromQuery] string? position = null,
        [FromQuery] string? hasTraining = null,
        [FromQuery] string? hasAchievements = null)
    {
        var currentUnitId = GetCurrentUnitId();
        var userLevel = GetCurrentUnitLevel();
        
        if (currentUnitId == null || userLevel == null)
        {
            return Unauthorized();
        }

        var allPersonnel = await _personnelService.GetVisiblePersonnelAsync(currentUnitId.Value, userLevel.Value);
        
        // 状态筛选
        if (!string.IsNullOrEmpty(status) && Enum.TryParse<PersonnelStatus>(status, out var statusFilter))
        {
            allPersonnel = allPersonnel.Where(p => p.Status == statusFilter);
        }
        
        // 单位筛选
        if (unitId.HasValue)
        {
            allPersonnel = allPersonnel.Where(p => p.SubmittedByUnitId == unitId.Value);
        }
        
        // 专业岗位筛选
        if (!string.IsNullOrEmpty(position))
        {
            allPersonnel = allPersonnel.Where(p => p.Position.Contains(position));
        }
        
        // 是否参加过培训筛选
        if (!string.IsNullOrEmpty(hasTraining))
        {
            if (hasTraining == "yes")
            {
                allPersonnel = allPersonnel.Where(p => !string.IsNullOrEmpty(p.TrainingParticipation));
            }
            else if (hasTraining == "no")
            {
                allPersonnel = allPersonnel.Where(p => string.IsNullOrEmpty(p.TrainingParticipation));
            }
        }
        
        // 是否有取得成绩筛选
        if (!string.IsNullOrEmpty(hasAchievements))
        {
            if (hasAchievements == "yes")
            {
                allPersonnel = allPersonnel.Where(p => !string.IsNullOrEmpty(p.Achievements));
            }
            else if (hasAchievements == "no")
            {
                allPersonnel = allPersonnel.Where(p => string.IsNullOrEmpty(p.Achievements));
            }
        }

        var totalCount = allPersonnel.Count();
        var items = allPersonnel
            .Skip((pageNumber - 1) * pageSize)
            .Take(pageSize)
            .Select(MapToResponse)
            .ToList();

        return Ok(new
        {
            items,
            totalCount,
            pageNumber,
            pageSize,
            totalPages = (int)Math.Ceiling(totalCount / (double)pageSize)
        });
    }

    /// <summary>
    /// 获取筛选选项（单位列表、岗位列表）
    /// </summary>
    [HttpGet("filter-options")]
    public async Task<IActionResult> GetFilterOptions()
    {
        var currentUnitId = GetCurrentUnitId();
        var userLevel = GetCurrentUnitLevel();
        
        if (currentUnitId == null || userLevel == null)
        {
            return Unauthorized();
        }

        var allPersonnel = await _personnelService.GetVisiblePersonnelAsync(currentUnitId.Value, userLevel.Value);
        
        // 获取所有可见的单位
        var units = allPersonnel
            .Select(p => new { id = p.SubmittedByUnitId, name = p.SubmittedByUnit?.Name ?? "" })
            .Distinct()
            .OrderBy(u => u.name)
            .ToList();
        
        // 获取所有岗位
        var positions = allPersonnel
            .Select(p => p.Position)
            .Where(p => !string.IsNullOrEmpty(p))
            .Distinct()
            .OrderBy(p => p)
            .ToList();

        return Ok(new
        {
            units,
            positions
        });
    }

    /// <summary>
    /// 映射人员实体到响应DTO
    /// </summary>
    private static PersonnelResponse MapToResponse(Personnel personnel)
    {
        return new PersonnelResponse
        {
            Id = personnel.Id,
            Name = personnel.Name,
            PhotoPath = personnel.PhotoPath,
            Unit = personnel.Unit,
            Position = personnel.Position,
            Rank = personnel.Rank,
            Gender = personnel.Gender,
            IdNumber = personnel.IdNumber,
            ProfessionalTitle = personnel.ProfessionalTitle,
            EducationLevel = personnel.EducationLevel,
            Age = personnel.Age,
            Height = personnel.Height,
            ContactInfo = personnel.ContactInfo,
            Hometown = personnel.Hometown,
            TrainingParticipation = personnel.TrainingParticipation,
            Achievements = personnel.Achievements,
            SupportingDocuments = personnel.SupportingDocuments,
            Ethnicity = personnel.Ethnicity,
            PoliticalStatus = personnel.PoliticalStatus,
            BirthDate = personnel.BirthDate,
            EnlistmentDate = personnel.EnlistmentDate,
            Specialty = personnel.Specialty,
            SubmittedByUnitId = personnel.SubmittedByUnitId,
            SubmittedByUnitName = personnel.SubmittedByUnit?.Name,
            ApprovedLevel = personnel.ApprovedLevel,
            ApprovedByUnitId = personnel.ApprovedByUnitId,
            ApprovedByUnitName = personnel.ApprovedByUnit?.Name,
            Status = personnel.Status,
            SubmittedAt = personnel.SubmittedAt,
            ApprovedAt = personnel.ApprovedAt,
            PendingUpgradeByUnitId = personnel.PendingUpgradeByUnitId
        };
    }

    /// <summary>
    /// 获取待审批的人员列表
    /// </summary>
    [HttpGet("pending-approval")]
    public async Task<IActionResult> GetPendingApproval()
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        var personnel = await _personnelService.GetPendingApprovalPersonnelAsync(unitId.Value);
        return Ok(personnel);
    }

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

        // 检查访问权限
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        var hasAccess = await _authorizationService.CanAccessUnitAsync(
            unitId.Value, personnel.SubmittedByUnitId);
        
        if (!hasAccess)
        {
            return Forbid();
        }

        return Ok(MapToResponse(personnel));
    }

    /// <summary>
    /// 提交人员数据（包含文件上传和验证）
    /// </summary>
    [HttpPost("submit")]
    public async Task<IActionResult> SubmitPersonnel([FromForm] SubmitPersonnelRequest request, 
        IFormFile? photo, IFormFile? supportingDocument)
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        var personnel = new Personnel
        {
            Name = request.Name,
            Unit = request.Unit,
            Position = request.Position,
            Rank = request.Rank,
            Gender = "男", // 默认值
            IdNumber = request.IdNumber,
            ProfessionalTitle = request.ProfessionalTitle,
            EducationLevel = request.EducationLevel,
            Age = CalculateAge(request.BirthDate), // 根据出生年月计算年龄
            Height = null,
            ContactInfo = null,
            Hometown = request.Hometown,
            TrainingParticipation = request.TrainingParticipation,
            Achievements = request.Achievements,
            Ethnicity = request.Ethnicity,
            PoliticalStatus = request.PoliticalStatus,
            BirthDate = request.BirthDate,
            EnlistmentDate = request.EnlistmentDate,
            Specialty = request.Specialty,
            SubmittedByUnitId = unitId.Value
        };

        try
        {
            var created = await _personnelService.SubmitPersonnelAsync(personnel, photo, supportingDocument);
            return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromForm] CreatePersonnelRequest request, 
        IFormFile? photo, IFormFile? supportingDocuments)
    {
        // 调试：打印接收到的数据
        Console.WriteLine($"接收到的数据: Name={request.Name}, Position={request.Position}, Rank={request.Rank}");
        
        // 返回详细的验证错误
        if (!ModelState.IsValid)
        {
            Console.WriteLine("模型验证失败:");
            foreach (var key in ModelState.Keys)
            {
                var modelErrors = ModelState[key]?.Errors;
                if (modelErrors != null && modelErrors.Count > 0)
                {
                    Console.WriteLine($"  {key}: {string.Join(", ", modelErrors.Select(e => e.ErrorMessage))}");
                }
            }
            
            var errors = ModelState
                .Where(x => x.Value?.Errors.Count > 0)
                .ToDictionary(
                    kvp => kvp.Key,
                    kvp => kvp.Value?.Errors.Select(e => e.ErrorMessage).ToArray()
                );
            return BadRequest(new { message = "验证失败", errors });
        }

        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        var personnel = new Personnel
        {
            Name = request.Name,
            Unit = request.Unit,
            Position = request.Position,
            Rank = request.Rank,
            Gender = "男", // 默认值
            IdNumber = request.IdNumber,
            ProfessionalTitle = request.ProfessionalTitle,
            EducationLevel = request.EducationLevel,
            Age = CalculateAge(request.BirthDate), // 根据出生年月计算年龄
            Height = null,
            ContactInfo = null,
            Hometown = request.Hometown,
            TrainingParticipation = request.TrainingParticipation,
            Achievements = request.Achievements,
            Ethnicity = request.Ethnicity,
            PoliticalStatus = request.PoliticalStatus,
            BirthDate = request.BirthDate,
            EnlistmentDate = request.EnlistmentDate,
            Specialty = request.Specialty,
            SubmittedByUnitId = unitId.Value
        };

        try
        {
            var created = await _personnelService.SubmitPersonnelAsync(personnel, photo, supportingDocuments);
            return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 更新人员信息（仅限未审批的人员）
    /// </summary>
    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, [FromForm] UpdatePersonnelRequest request,
        IFormFile? photo, IFormFile? supportingDocuments)
    {
        var personnel = await _personnelService.GetByIdAsync(id);
        if (personnel == null)
        {
            return NotFound();
        }

        // 检查是否可以修改
        var canModify = await _personnelService.CanModifyPersonnelAsync(id);
        if (!canModify)
        {
            return BadRequest("已审批的人员记录不能直接修改，请使用修改申请功能");
        }

        // 检查权限
        var unitId = GetCurrentUnitId();
        if (unitId == null || personnel.SubmittedByUnitId != unitId.Value)
        {
            return Forbid();
        }

        // 更新人员信息
        personnel.Name = request.Name;
        personnel.Position = request.Position;
        personnel.Rank = request.Rank;
        personnel.Gender = request.Gender;
        personnel.ProfessionalTitle = request.ProfessionalTitle;
        personnel.EducationLevel = request.EducationLevel;
        personnel.Age = request.Age;
        personnel.Height = request.Height;
        personnel.ContactInfo = request.ContactInfo;
        personnel.Hometown = request.Hometown;
        personnel.TrainingParticipation = request.TrainingParticipation;
        personnel.Achievements = request.Achievements;

        // 处理照片上传
        if (photo != null)
        {
            if (!string.IsNullOrEmpty(personnel.PhotoPath))
            {
                await _fileUploadService.DeleteFileAsync(personnel.PhotoPath);
            }
            personnel.PhotoPath = await _fileUploadService.UploadPhotoAsync(photo);
        }

        // 处理文档上传
        if (supportingDocuments != null)
        {
            var documentPath = await _fileUploadService.UploadDocumentAsync(supportingDocuments);
            if (string.IsNullOrEmpty(personnel.SupportingDocuments))
            {
                personnel.SupportingDocuments = documentPath;
            }
            else
            {
                personnel.SupportingDocuments += ";" + documentPath;
            }
        }

        var updated = await _personnelService.UpdateAsync(personnel);
        return Ok(updated);
    }

    /// <summary>
    /// 请求修改已审批的人员记录
    /// </summary>
    [HttpPost("{id}/request-modification")]
    public async Task<IActionResult> RequestModification(int id, [FromBody] PersonnelModificationRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Unauthorized();
        }

        try
        {
            var personnel = new Personnel
            {
                Name = request.ModifiedPersonnel.Name,
                Position = request.ModifiedPersonnel.Position,
                Rank = request.ModifiedPersonnel.Rank,
                Gender = request.ModifiedPersonnel.Gender,
                ProfessionalTitle = request.ModifiedPersonnel.ProfessionalTitle,
                EducationLevel = request.ModifiedPersonnel.EducationLevel,
                Age = request.ModifiedPersonnel.Age,
                Height = request.ModifiedPersonnel.Height,
                ContactInfo = request.ModifiedPersonnel.ContactInfo,
                Hometown = request.ModifiedPersonnel.Hometown,
                TrainingParticipation = request.ModifiedPersonnel.TrainingParticipation,
                Achievements = request.ModifiedPersonnel.Achievements
            };

            var approvalRequest = await _personnelService.RequestPersonnelModificationAsync(
                id, userId.Value, request.Reason, personnel);
            
            return Ok(approvalRequest);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 上传人员照片
    /// </summary>
    [HttpPost("{id}/photo")]
    public async Task<IActionResult> UploadPhoto(int id, IFormFile file)
    {
        var personnel = await _personnelService.GetByIdAsync(id);
        if (personnel == null)
        {
            return NotFound("人员记录不存在");
        }

        try
        {
            // 删除旧照片
            if (!string.IsNullOrEmpty(personnel.PhotoPath))
            {
                await _fileUploadService.DeleteFileAsync(personnel.PhotoPath);
            }

            var photoPath = await _fileUploadService.UploadPhotoAsync(file);
            personnel.PhotoPath = photoPath;
            await _personnelService.UpdateAsync(personnel);

            return Ok(new { photoPath });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 上传支持文档
    /// </summary>
    [HttpPost("{id}/documents")]
    public async Task<IActionResult> UploadDocument(int id, IFormFile file)
    {
        var personnel = await _personnelService.GetByIdAsync(id);
        if (personnel == null)
        {
            return NotFound("人员记录不存在");
        }

        try
        {
            var documentPath = await _fileUploadService.UploadDocumentAsync(file);
            
            // 追加到现有文档列表（用分号分隔）
            if (string.IsNullOrEmpty(personnel.SupportingDocuments))
            {
                personnel.SupportingDocuments = documentPath;
            }
            else
            {
                personnel.SupportingDocuments += ";" + documentPath;
            }
            
            await _personnelService.UpdateAsync(personnel);

            return Ok(new { documentPath });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 验证照片格式
    /// </summary>
    [HttpPost("validate-photo")]
    public async Task<IActionResult> ValidatePhoto(IFormFile file)
    {
        var result = await _fileUploadService.ValidatePhotoAsync(file);
        if (result.IsValid)
        {
            return Ok(new { isValid = true, width = result.Width, height = result.Height });
        }
        return BadRequest(new { isValid = false, error = result.ErrorMessage });
    }

    /// <summary>
    /// 审批人员
    /// </summary>
    [HttpPost("{id}/approve")]
    [Authorize(Policy = "BattalionLevel")] // 营级及以上权限
    public async Task<IActionResult> Approve(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        // 检查审批权限
        var canApprove = await _personnelService.CanApprovePersonnelAsync(userId.Value, id);
        if (!canApprove)
        {
            return StatusCode(403, new { message = "您没有权限审批此人员" });
        }

        try
        {
            // 获取人员信息用于审计日志
            var personnelBefore = await _personnelService.GetByIdAsync(id);
            
            // 不传递level参数，让服务层根据人员所在单位自动确定等级
            var personnel = await _personnelService.ApproveAsync(id, unitId.Value);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "Personnel", 
                id, 
                "Approve", 
                $"审批通过人才「{personnel.Name}」，等级：{GetLevelDisplayName(personnel.ApprovedLevel)}", 
                userId, 
                unitId,
                GetClientIpAddress());
            
            return Ok(MapToResponse(personnel));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }
    
    private string GetLevelDisplayName(PersonnelLevel? level)
    {
        return level switch
        {
            PersonnelLevel.Division => "师级",
            PersonnelLevel.Regiment => "团级",
            PersonnelLevel.Battalion => "营级",
            PersonnelLevel.Company => "连级",
            _ => "未定级"
        };
    }
    
    private string? GetClientIpAddress()
    {
        return HttpContext.Connection.RemoteIpAddress?.ToString();
    }

    /// <summary>
    /// 拒绝人员
    /// </summary>
    [HttpPost("{id}/reject")]
    [Authorize(Policy = "BattalionLevel")] // 营级及以上权限
    public async Task<IActionResult> Reject(int id, [FromBody] RejectPersonnelRequest request)
    {
        var userId = GetCurrentUserId();
        var unitId = GetCurrentUnitId();
        if (userId == null || unitId == null)
        {
            return Unauthorized();
        }

        // 检查审批权限
        var canApprove = await _personnelService.CanApprovePersonnelAsync(userId.Value, id);
        if (!canApprove)
        {
            return StatusCode(403, new { message = "您没有权限拒绝此人员" });
        }

        // 获取人员信息用于审计日志
        var personnelBefore = await _personnelService.GetByIdAsync(id);
        
        var personnel = await _personnelService.RejectAsync(id, userId.Value, unitId.Value, request.Reason);
        
        // 记录审计日志
        await _auditService.LogApprovalAsync(
            "Personnel", 
            id, 
            "Reject", 
            $"拒绝人才「{personnel.Name}」的审批申请，原因：{request.Reason ?? "无"}", 
            userId, 
            unitId,
            GetClientIpAddress());
        
        return Ok(MapToResponse(personnel));
    }

    /// <summary>
    /// 批量审批人员
    /// </summary>
    [HttpPost("batch-approve")]
    [Authorize(Policy = "RegimentLevel")] // 团级及以上权限
    public async Task<IActionResult> BatchApprove([FromBody] BatchApprovePersonnelRequest request)
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        try
        {
            var approvedPersonnel = await _personnelService.BatchApprovePersonnelAsync(
                request.PersonnelIds, unitId.Value, request.Level);
            
            return Ok(new { 
                approvedCount = approvedPersonnel.Count(),
                approvedPersonnel = approvedPersonnel
            });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 批量拒绝人员
    /// </summary>
    [HttpPost("batch-reject")]
    [Authorize(Policy = "RegimentLevel")] // 团级及以上权限
    public async Task<IActionResult> BatchReject([FromBody] BatchRejectPersonnelRequest request)
    {
        var userId = GetCurrentUserId();
        var unitId = GetCurrentUnitId();
        if (userId == null || unitId == null)
        {
            return Unauthorized();
        }

        try
        {
            var rejectedPersonnel = await _personnelService.BatchRejectPersonnelAsync(
                request.PersonnelIds, userId.Value, unitId.Value, request.Reason);
            
            return Ok(new { 
                rejectedCount = rejectedPersonnel.Count(),
                rejectedPersonnel = rejectedPersonnel
            });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 跨层级人员转移
    /// </summary>
    [HttpPost("{id}/transfer")]
    [Authorize(Policy = "BattalionLevel")] // 营级及以上权限
    public async Task<IActionResult> TransferPersonnel(int id, [FromBody] TransferPersonnelRequest request)
    {
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        try
        {
            var personnel = await _personnelService.TransferPersonnelAsync(
                id, request.TargetUnitId, unitId.Value);
            
            return Ok(personnel);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
        catch (UnauthorizedAccessException ex)
        {
            return Forbid(ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 获取人员审批历史
    /// </summary>
    [HttpGet("{id}/approval-history")]
    public async Task<IActionResult> GetApprovalHistory(int id)
    {
        var personnel = await _personnelService.GetByIdAsync(id);
        if (personnel == null)
        {
            return NotFound();
        }

        // 检查访问权限
        var unitId = GetCurrentUnitId();
        if (unitId == null)
        {
            return Unauthorized();
        }

        var hasAccess = await _authorizationService.CanAccessUnitAsync(
            unitId.Value, personnel.SubmittedByUnitId);
        
        if (!hasAccess)
        {
            return Forbid();
        }

        var history = await _personnelService.GetPersonnelApprovalHistoryAsync(id);
        
        // 映射为简化的响应对象，避免循环引用
        var response = history.Select(h => new
        {
            h.Id,
            h.PersonnelId,
            Action = h.Action.ToString(),
            PreviousStatus = h.PreviousStatus?.ToString(),
            NewStatus = h.NewStatus.ToString(),
            PreviousLevel = h.PreviousLevel?.ToString(),
            NewLevel = h.NewLevel?.ToString(),
            h.ReviewedByUserId,
            h.ReviewedByUnitId,
            ReviewedByUnitName = h.ReviewedByUnit?.Name,
            h.Comments,
            h.ReviewedAt
        });
        
        return Ok(response);
    }

    /// <summary>
    /// 删除人员记录
    /// </summary>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var personnel = await _personnelService.GetByIdAsync(id);
        if (personnel == null)
        {
            return NotFound(new { message = "人员记录不存在" });
        }

        // 检查权限：只有提交单位或上级单位可以删除
        var unitId = GetCurrentUnitId();
        var userLevel = GetCurrentUnitLevel();
        if (unitId == null || userLevel == null)
        {
            return Unauthorized();
        }

        // 检查是否是提交单位
        if (personnel.SubmittedByUnitId != unitId.Value)
        {
            // 检查是否有上级权限
            var hasAccess = await _authorizationService.CanAccessUnitAsync(
                unitId.Value, personnel.SubmittedByUnitId);
            
            if (!hasAccess)
            {
                return Forbid();
            }
        }

        // 待审批状态的人员可以直接删除
        // 已批准状态的人员，只有审批单位或更高级别单位可以删除
        if (personnel.Status == PersonnelStatus.Approved)
        {
            // 检查当前用户单位层级是否足够高（数值越小层级越高）
            var personnelLevelValue = personnel.ApprovedLevel.HasValue ? (int)personnel.ApprovedLevel.Value : 4;
            var userLevelValue = (int)userLevel.Value;
            
            // 用户层级必须高于或等于人员等级才能删除
            if (userLevelValue > personnelLevelValue)
            {
                return BadRequest(new { message = "您的权限不足以删除该等级的人员" });
            }
        }

        try
        {
            await _personnelService.DeleteAsync(id);
            return NoContent();
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 发起向上申报请求
    /// </summary>
    [HttpPost("{id}/request-upgrade")]
    [Authorize(Policy = "BattalionLevel")] // 营级及以上权限
    public async Task<IActionResult> RequestUpgrade(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        try
        {
            var personnel = await _personnelService.RequestUpgradeAsync(id, unitId.Value);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "Personnel", 
                id, 
                "RequestUpgrade", 
                $"发起向上申报：人才「{personnel.Name}」（{GetLevelDisplayName(personnel.ApprovedLevel)}）申请升级", 
                userId, 
                unitId,
                GetClientIpAddress());
            
            return Ok(MapToResponse(personnel));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 审批向上申报请求
    /// </summary>
    [HttpPost("{id}/approve-upgrade")]
    [Authorize(Policy = "BattalionLevel")] // 营级及以上权限
    public async Task<IActionResult> ApproveUpgrade(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        try
        {
            // 获取人员信息用于审计日志
            var personnelBefore = await _personnelService.GetByIdAsync(id);
            var previousLevel = personnelBefore?.ApprovedLevel;
            
            var personnel = await _personnelService.ApproveUpgradeAsync(id, unitId.Value);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "Personnel", 
                id, 
                "ApproveUpgrade", 
                $"批准人才「{personnel.Name}」的向上申报，等级从{GetLevelDisplayName(previousLevel)}升级为{GetLevelDisplayName(personnel.ApprovedLevel)}", 
                userId, 
                unitId,
                GetClientIpAddress());
            
            return Ok(MapToResponse(personnel));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 拒绝向上申报请求
    /// </summary>
    [HttpPost("{id}/reject-upgrade")]
    [Authorize(Policy = "BattalionLevel")] // 营级及以上权限
    public async Task<IActionResult> RejectUpgrade(int id, [FromBody] RejectUpgradeRequest request)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        try
        {
            // 获取人员信息用于审计日志
            var personnelBefore = await _personnelService.GetByIdAsync(id);
            
            var personnel = await _personnelService.RejectUpgradeAsync(id, unitId.Value, request.Comments);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "Personnel", 
                id, 
                "RejectUpgrade", 
                $"拒绝人才「{personnel.Name}」的向上申报，原因：{request.Comments}", 
                userId, 
                unitId,
                GetClientIpAddress());
            
            return Ok(MapToResponse(personnel));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 师部直接升级团级人才为师级
    /// </summary>
    [HttpPost("{id}/direct-upgrade")]
    [Authorize(Policy = "DivisionLevel")] // 师级权限
    public async Task<IActionResult> DirectUpgrade(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        try
        {
            var personnel = await _personnelService.DirectUpgradeAsync(id, unitId.Value);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "Personnel", 
                id, 
                "DirectUpgrade", 
                $"师部直接升级人才「{personnel.Name}」为师级人才", 
                userId, 
                unitId,
                GetClientIpAddress());
            
            return Ok(MapToResponse(personnel));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 重新提交被拒绝的人才审批
    /// </summary>
    [HttpPost("{id}/resubmit")]
    public async Task<IActionResult> ResubmitPersonnel(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        try
        {
            var personnel = await _personnelService.GetByIdAsync(id);
            if (personnel == null)
            {
                return NotFound(new { message = "人员记录不存在" });
            }

            // 检查权限：只有提交单位可以重新提交
            if (personnel.SubmittedByUnitId != unitId.Value)
            {
                return Forbid();
            }

            var resubmitted = await _personnelService.ResubmitPersonnelAsync(id);
            
            // 记录审计日志
            await _auditService.LogApprovalAsync(
                "Personnel", 
                id, 
                "Resubmit", 
                $"重新提交审批：人才「{resubmitted.Name}」重新提交审批申请", 
                userId, 
                unitId,
                GetClientIpAddress());
            
            return Ok(MapToResponse(resubmitted));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>
    /// 导出人才列表到Excel
    /// </summary>
    [HttpGet("export")]
    public async Task<IActionResult> ExportToExcel(
        [FromQuery] string? status = null,
        [FromQuery] int? unitId = null,
        [FromQuery] string? position = null,
        [FromQuery] string? hasTraining = null,
        [FromQuery] string? hasAchievements = null)
    {
        var currentUnitId = GetCurrentUnitId();
        var userLevel = GetCurrentUnitLevel();
        
        if (currentUnitId == null || userLevel == null)
        {
            return Unauthorized();
        }

        var allPersonnel = await _personnelService.GetVisiblePersonnelAsync(currentUnitId.Value, userLevel.Value);
        
        // 应用筛选条件
        if (!string.IsNullOrEmpty(status) && Enum.TryParse<PersonnelStatus>(status, out var statusFilter))
        {
            allPersonnel = allPersonnel.Where(p => p.Status == statusFilter);
        }
        if (unitId.HasValue)
        {
            allPersonnel = allPersonnel.Where(p => p.SubmittedByUnitId == unitId.Value);
        }
        if (!string.IsNullOrEmpty(position))
        {
            allPersonnel = allPersonnel.Where(p => p.Position.Contains(position));
        }
        if (!string.IsNullOrEmpty(hasTraining))
        {
            if (hasTraining == "yes")
                allPersonnel = allPersonnel.Where(p => !string.IsNullOrEmpty(p.TrainingParticipation));
            else if (hasTraining == "no")
                allPersonnel = allPersonnel.Where(p => string.IsNullOrEmpty(p.TrainingParticipation));
        }
        if (!string.IsNullOrEmpty(hasAchievements))
        {
            if (hasAchievements == "yes")
                allPersonnel = allPersonnel.Where(p => !string.IsNullOrEmpty(p.Achievements));
            else if (hasAchievements == "no")
                allPersonnel = allPersonnel.Where(p => string.IsNullOrEmpty(p.Achievements));
        }

        var personnelList = allPersonnel.ToList();

        using var workbook = new ClosedXML.Excel.XLWorkbook();
        var worksheet = workbook.Worksheets.Add("人才数据库");

        // 标题行
        worksheet.Cell(1, 1).Value = "人才数据库";
        worksheet.Range(1, 1, 1, 17).Merge();
        worksheet.Cell(1, 1).Style.Font.Bold = true;
        worksheet.Cell(1, 1).Style.Font.FontSize = 18;
        worksheet.Cell(1, 1).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center;

        // 统计更新时间
        worksheet.Cell(2, 1).Value = $"统计更新时间：{DateTime.Now:yyyy.M.d}";
        worksheet.Range(2, 1, 2, 4).Merge();

        // 设置表头（第3行）
        var headers = new[] { "序号", "姓名", "照片", "单位", "部职别", "军衔", 
            "士兵证号", "专业岗位", "政治面貌", "文化程度", "民族", "籍贯", 
            "出生年月", "入伍年月", "特长", "参加培训、集训情况", "取得成绩（成果）" };
        
        for (int i = 0; i < headers.Length; i++)
        {
            var cell = worksheet.Cell(3, i + 1);
            cell.Value = headers[i];
            cell.Style.Font.Bold = true;
            cell.Style.Fill.BackgroundColor = ClosedXML.Excel.XLColor.LightGray;
            cell.Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center;
            cell.Style.Alignment.Vertical = ClosedXML.Excel.XLAlignmentVerticalValues.Center;
            cell.Style.Border.OutsideBorder = ClosedXML.Excel.XLBorderStyleValues.Thin;
        }

        // 设置照片列宽度
        worksheet.Column(3).Width = 15;

        // 填充数据（从第4行开始）
        int row = 4;
        int seq = 1;
        var webRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
        
        foreach (var p in personnelList)
        {
            worksheet.Cell(row, 1).Value = seq++;
            worksheet.Cell(row, 2).Value = p.Name;
            
            // 处理照片 - 2寸照片比例 35mm x 49mm (约 3:4)
            worksheet.Row(row).Height = 70; // 设置行高
            if (!string.IsNullOrEmpty(p.PhotoPath))
            {
                try
                {
                    // PhotoPath 格式如 "/uploads/xxx.jpg"，需要转换为实际文件路径
                    var photoRelativePath = p.PhotoPath.TrimStart('/').Replace("/", Path.DirectorySeparatorChar.ToString());
                    var photoFullPath = Path.Combine(webRootPath, photoRelativePath);
                    
                    if (System.IO.File.Exists(photoFullPath))
                    {
                        var picture = worksheet.AddPicture(photoFullPath);
                        // 先移动到目标单元格
                        var targetCell = worksheet.Cell(row, 3);
                        picture.MoveTo(targetCell, 18, 3); // 偏移实现居中
                        // 2寸照片比例：宽35mm 高49mm，按比例缩放 (38 x 53 像素)
                        picture.WithSize(38, 53);
                    }
                    else
                    {
                        worksheet.Cell(row, 3).Value = "图片不存在";
                    }
                }
                catch
                {
                    worksheet.Cell(row, 3).Value = "图片加载失败";
                }
            }
            else
            {
                worksheet.Cell(row, 3).Value = "";
            }
            
            worksheet.Cell(row, 4).Value = p.Unit ?? p.SubmittedByUnit?.Name ?? "";
            worksheet.Cell(row, 5).Value = p.Position;
            worksheet.Cell(row, 6).Value = p.Rank;
            worksheet.Cell(row, 7).Value = p.IdNumber ?? "";
            worksheet.Cell(row, 8).Value = p.ProfessionalTitle ?? ""; // 专业岗位
            worksheet.Cell(row, 9).Value = p.PoliticalStatus ?? "";
            worksheet.Cell(row, 10).Value = p.EducationLevel ?? "";
            worksheet.Cell(row, 11).Value = p.Ethnicity ?? "";
            worksheet.Cell(row, 12).Value = p.Hometown ?? "";
            worksheet.Cell(row, 13).Value = p.BirthDate ?? "";
            worksheet.Cell(row, 14).Value = p.EnlistmentDate ?? "";
            worksheet.Cell(row, 15).Value = p.Specialty ?? ""; // 特长
            worksheet.Cell(row, 16).Value = p.TrainingParticipation ?? "";
            worksheet.Cell(row, 17).Value = p.Achievements ?? "";
            
            // 设置边框
            for (int col = 1; col <= 17; col++)
            {
                worksheet.Cell(row, col).Style.Border.OutsideBorder = ClosedXML.Excel.XLBorderStyleValues.Thin;
            }
            row++;
        }

        // 自动调整列宽
        worksheet.Columns().AdjustToContents();
        foreach (var column in worksheet.ColumnsUsed())
        {
            if (column.Width < 10)
                column.Width = 10;
            else if (column.Width > 30)
                column.Width = 30;
        }
        worksheet.Row(3).Height = 35;

        using var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;

        var fileName = $"人才列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
        return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
    }

    /// <summary>
    /// 下载导入模板
    /// </summary>
    [HttpGet("import-template")]
    public IActionResult DownloadImportTemplate()
    {
        using var workbook = new ClosedXML.Excel.XLWorkbook();
        var worksheet = workbook.Worksheets.Add("人才数据库");

        // 标题行
        worksheet.Cell(1, 1).Value = "人才数据库";
        worksheet.Range(1, 1, 1, 16).Merge();
        worksheet.Cell(1, 1).Style.Font.Bold = true;
        worksheet.Cell(1, 1).Style.Font.FontSize = 18;
        worksheet.Cell(1, 1).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center;

        // 统计更新时间
        worksheet.Cell(2, 1).Value = $"统计更新时间：{DateTime.Now:yyyy.M.d}";
        worksheet.Range(2, 1, 2, 4).Merge();

        // 设置表头（第3行）
        var headers = new[] { "序号", "姓名*", "照片（2寸以内）", "单位", "部职别*", "军衔*", 
            "士兵证号", "专业岗位*", "政治面貌", "文化程度", "民族", "籍贯", 
            "出生年月", "入伍年月", "特长", "参加培训、集训情况", "取得成绩（成果）可手填、可上传照片" };
        
        for (int i = 0; i < headers.Length; i++)
        {
            var cell = worksheet.Cell(3, i + 1);
            cell.Value = headers[i];
            cell.Style.Font.Bold = true;
            cell.Style.Fill.BackgroundColor = ClosedXML.Excel.XLColor.LightGray;
            cell.Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center;
            cell.Style.Alignment.Vertical = ClosedXML.Excel.XLAlignmentVerticalValues.Center;
            cell.Style.Alignment.WrapText = true;
            cell.Style.Border.OutsideBorder = ClosedXML.Excel.XLBorderStyleValues.Thin;
        }

        // 添加示例数据（第4行）
        worksheet.Cell(4, 1).Value = 1;
        worksheet.Cell(4, 2).Value = "张三";
        worksheet.Cell(4, 3).Value = "";
        worksheet.Cell(4, 4).Value = "一营一连";
        worksheet.Cell(4, 5).Value = "班长";
        worksheet.Cell(4, 6).Value = "上士";
        worksheet.Cell(4, 7).Value = "";
        worksheet.Cell(4, 8).Value = "通信";
        worksheet.Cell(4, 9).Value = "党员";
        worksheet.Cell(4, 10).Value = "大专";
        worksheet.Cell(4, 11).Value = "汉族";
        worksheet.Cell(4, 12).Value = "北京市";
        worksheet.Cell(4, 13).Value = "1995-06";
        worksheet.Cell(4, 14).Value = "2015-09";
        worksheet.Cell(4, 15).Value = "计算机";
        worksheet.Cell(4, 16).Value = "参加过2023年度集训";
        worksheet.Cell(4, 17).Value = "获得优秀学员称号";

        // 设置数据行边框
        for (int col = 1; col <= 17; col++)
        {
            worksheet.Cell(4, col).Style.Border.OutsideBorder = ClosedXML.Excel.XLBorderStyleValues.Thin;
        }

        // 添加说明
        var noteSheet = workbook.Worksheets.Add("填写说明");
        noteSheet.Cell(1, 1).Value = "填写说明";
        noteSheet.Cell(1, 1).Style.Font.Bold = true;
        noteSheet.Cell(2, 1).Value = "1. 带*号的字段为必填项（姓名、部职别、军衔、专业岗位）";
        noteSheet.Cell(3, 1).Value = "2. 照片列可留空，后续在系统中上传";
        noteSheet.Cell(4, 1).Value = "3. 出生年月格式：YYYY-MM，如 1995-06";
        noteSheet.Cell(5, 1).Value = "4. 入伍年月格式：YYYY-MM，如 2015-09";
        noteSheet.Cell(6, 1).Value = "5. 第3行为表头，请从第4行开始填写数据";
        noteSheet.Cell(7, 1).Value = "6. 示例数据行可以删除或覆盖";
        noteSheet.Cell(8, 1).Value = "7. 序号列可留空，系统会自动生成";

        // 自动调整列宽
        worksheet.Columns().AdjustToContents();
        foreach (var column in worksheet.ColumnsUsed())
        {
            if (column.Width < 10)
                column.Width = 10;
            else if (column.Width > 25)
                column.Width = 25;
        }
        worksheet.Row(3).Height = 40; // 表头行高
        noteSheet.Columns().AdjustToContents();
        noteSheet.Column(1).Width = 50;

        using var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;

        return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "人才导入模板.xlsx");
    }

    /// <summary>
    /// 从Excel导入人才
    /// </summary>
    [HttpPost("import")]
    public async Task<IActionResult> ImportFromExcel(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return BadRequest(new { message = "请选择要导入的文件" });
        }

        var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (extension != ".xlsx" && extension != ".xls")
        {
            return BadRequest(new { message = "只支持Excel文件格式(.xlsx, .xls)" });
        }

        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        if (unitId == null || userId == null)
        {
            return Unauthorized();
        }

        var importResults = new List<object>();
        var successCount = 0;
        var failCount = 0;

        try
        {
            using var stream = file.OpenReadStream();
            using var workbook = new ClosedXML.Excel.XLWorkbook(stream);
            var worksheet = workbook.Worksheet(1);
            
            // 跳过标题行(1)、时间行(2)、表头行(3)，从第4行开始读取数据
            var rows = worksheet.RowsUsed().Where(r => r.RowNumber() >= 4);

            foreach (var row in rows)
            {
                try
                {
                    // 新模板列顺序：序号(1), 姓名(2), 照片(3), 单位(4), 部职别(5), 军衔(6), 
                    // 士兵证号(7), 专业岗位(8), 政治面貌(9), 文化程度(10), 民族(11), 籍贯(12), 
                    // 出生年月(13), 入伍年月(14), 特长(15), 培训情况(16), 取得成绩(17)
                    
                    var name = row.Cell(2).GetString().Trim();
                    var unit = GetNullIfEmpty(row.Cell(4).GetString());
                    var position = row.Cell(5).GetString().Trim();
                    var rank = row.Cell(6).GetString().Trim();
                    var professionalTitle = row.Cell(8).GetString().Trim(); // 专业岗位

                    // 验证必填字段（姓名、部职别、军衔、专业岗位）
                    if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(position) || 
                        string.IsNullOrEmpty(rank) || string.IsNullOrEmpty(professionalTitle))
                    {
                        failCount++;
                        importResults.Add(new { row = row.RowNumber(), success = false, message = "必填字段不能为空（姓名、部职别、军衔、专业岗位）" });
                        continue;
                    }

                    // 检查士兵证号是否重复
                    var idNumber = GetNullIfEmpty(row.Cell(7).GetString());
                    if (!string.IsNullOrEmpty(idNumber))
                    {
                        var existingPersonnel = await _personnelService.GetByIdNumberAsync(idNumber);
                        if (existingPersonnel != null)
                        {
                            failCount++;
                            importResults.Add(new { row = row.RowNumber(), success = false, message = $"士兵证号 {idNumber} 已存在" });
                            continue;
                        }
                    }

                    var birthDate = GetNullIfEmpty(row.Cell(13).GetString());
                    var age = CalculateAge(birthDate);

                    var personnel = new Personnel
                    {
                        Name = name,
                        Gender = "男", // 默认性别，模板中没有性别列
                        Age = age,
                        IdNumber = idNumber ?? "", // 士兵证号
                        Unit = unit,
                        Position = position,
                        Rank = rank,
                        ProfessionalTitle = professionalTitle, // 专业岗位
                        Specialty = GetNullIfEmpty(row.Cell(15).GetString()), // 特长
                        PoliticalStatus = GetNullIfEmpty(row.Cell(9).GetString()),
                        EducationLevel = GetNullIfEmpty(row.Cell(10).GetString()),
                        Ethnicity = GetNullIfEmpty(row.Cell(11).GetString()),
                        Hometown = GetNullIfEmpty(row.Cell(12).GetString()),
                        BirthDate = birthDate,
                        EnlistmentDate = GetNullIfEmpty(row.Cell(14).GetString()),
                        TrainingParticipation = GetNullIfEmpty(row.Cell(16).GetString()),
                        Achievements = GetNullIfEmpty(row.Cell(17).GetString()),
                        SubmittedByUnitId = unitId.Value,
                        Status = PersonnelStatus.Pending,
                        SubmittedAt = DateTime.UtcNow
                    };

                    await _personnelService.CreateAsync(personnel);
                    successCount++;
                    importResults.Add(new { row = row.RowNumber(), success = true, name = name });
                }
                catch (Exception ex)
                {
                    failCount++;
                    importResults.Add(new { row = row.RowNumber(), success = false, message = ex.Message });
                }
            }

            // 记录审计日志
            await _auditService.LogAsync(
                "Personnel",
                0,
                "Import",
                null,
                $"批量导入人才：成功{successCount}条，失败{failCount}条",
                userId,
                GetClientIpAddress());

            return Ok(new
            {
                successCount,
                failCount,
                results = importResults
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = $"导入失败：{ex.Message}" });
        }
    }

    private static string GetLevelName(PersonnelLevel? level)
    {
        return level switch
        {
            PersonnelLevel.Division => "师级",
            PersonnelLevel.Regiment => "团级",
            PersonnelLevel.Battalion => "营级",
            PersonnelLevel.Company => "连级",
            _ => ""
        };
    }

    private static string GetStatusName(PersonnelStatus status)
    {
        return status switch
        {
            PersonnelStatus.Pending => "待审批",
            PersonnelStatus.Approved => "已批准",
            PersonnelStatus.Rejected => "已拒绝",
            _ => ""
        };
    }

    private static string? GetNullIfEmpty(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return null;
        return value.Trim();
    }
}
