using AgriculturalPlatform.Api.Data;
using AgriculturalPlatform.Api.Dtos;
using AgriculturalPlatform.Api.Models;
using AgriculturalPlatform.Api.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AgriculturalPlatform.Api.Controllers;
[ApiController]
[Route("api/users")]
[Authorize]
public class UsersController(AppDbContext db, DataScopeService scope, CurrentUserService currentUser) : ControllerBase
{
/// 用户列表(分页 + 数据权限)
[HttpGet]
public async Task>> List(
string? role, string? orgId,
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, [FromQuery] string? keyword = null)
{
var visible = await scope.GetVisibleOrgIdsAsync(currentUser.Get());
var query = db.Users.Include(u => u.Org).Include(u => u.SysRole).AsQueryable();
if (visible is not null)
query = query.Where(u => u.OrgId != null && visible.Contains(u.OrgId.Value));
if (!string.IsNullOrWhiteSpace(role) && Enum.TryParse(role, out var userRole))
query = query.Where(u => u.Role == userRole);
if (int.TryParse(orgId, out var oid))
query = query.Where(u => u.OrgId == oid);
if (!string.IsNullOrWhiteSpace(keyword))
query = query.Where(u => u.Username.Contains(keyword) || u.RealName.Contains(keyword) || u.Phone.Contains(keyword));
var total = await query.CountAsync();
var items = await query.OrderByDescending(u => u.Id)
.Skip((page - 1) * pageSize).Take(pageSize)
.ToListAsync();
return Ok(new PagedResult(items.ToDtos(), total));
}
/// 新增用户
[HttpPost]
public async Task> Create(UserSaveRequest req)
{
if (await db.Users.AnyAsync(u => u.Username == req.Username))
return BadRequest(new { message = "用户名已存在" });
if (!Enum.TryParse(req.Role, out var role))
return BadRequest(new { message = "角色不正确" });
var user = new User
{
Username = req.Username,
PasswordHash = BCrypt.Net.BCrypt.HashPassword(req.Password ?? "123456"),
RealName = req.RealName,
Phone = req.Phone,
Role = role,
RoleId = req.RoleId,
OrgId = req.OrgId,
IsActive = req.IsActive
};
db.Users.Add(user);
await db.SaveChangesAsync();
return Ok((await db.Users.Include(u => u.Org).Include(u => u.SysRole).FirstAsync(u => u.Id == user.Id)).ToDto());
}
/// 修改用户
[HttpPut("{id:int}")]
public async Task> Update(int id, UserSaveRequest req)
{
var user = await db.Users.FindAsync(id);
if (user is null) return NotFound();
if (req.Username != user.Username && await db.Users.AnyAsync(u => u.Username == req.Username))
return BadRequest(new { message = "用户名已存在" });
user.Username = req.Username;
user.RealName = req.RealName;
user.Phone = req.Phone;
if (Enum.TryParse(req.Role, out var role)) user.Role = role;
user.RoleId = req.RoleId;
user.OrgId = req.OrgId;
user.IsActive = req.IsActive;
if (!string.IsNullOrWhiteSpace(req.Password))
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(req.Password);
await db.SaveChangesAsync();
return Ok((await db.Users.Include(u => u.Org).Include(u => u.SysRole).FirstAsync(u => u.Id == user.Id)).ToDto());
}
/// 重置密码
[HttpPut("{id:int}/reset-password")]
public async Task ResetPassword(int id, [FromBody] string? newPassword = null)
{
var user = await db.Users.FindAsync(id);
if (user is null) return NotFound();
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(newPassword ?? "123456");
await db.SaveChangesAsync();
return Ok(new { message = "密码已重置为 " + (newPassword ?? "123456") });
}
/// 删除用户(禁止删除自己)
[HttpDelete("{id:int}")]
public async Task Delete(int id)
{
var cu = currentUser.Get()!;
if (id == cu.Id) return BadRequest(new { message = "不能删除当前登录账号" });
var user = await db.Users.FindAsync(id);
if (user is null) return NotFound();
db.Users.Remove(user);
await db.SaveChangesAsync();
return Ok(new { message = "删除成功" });
}
}