asg_backend/asg_form/Controllers/InviteReferee.cs
2024-10-10 21:54:39 +08:00

86 lines
2.9 KiB
C#

using Manganese.Array;
using Masuit.Tools;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
namespace asg_form.Controllers
{
public class InviteReferee : ControllerBase
{
private readonly RoleManager<Role> roleManager;
private readonly UserManager<User> userManager;
public InviteReferee(
RoleManager<Role> roleManager, UserManager<User> userManager)
{
this.roleManager = roleManager;
this.userManager = userManager;
}
public class InviteBg
{
public int id { get; set; }
public int user_id { get; set; }
public List<(int invitor_id, int match_id)>? my_request { get; set; } = new List<(int, int)>();
}
public class inv
{
public int invitedId { get; set; }
public int matchId { get; set; }
}
[Route("api/v1/Invite")]
[HttpPost]
[Authorize]
public async Task<ActionResult<object>> GetReferee([FromBody] inv msg)
{
string Invitorid = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
var user = await userManager.FindByIdAsync(Invitorid);
long userId = user.Id;
using (TestDbContext sb = new TestDbContext())
{
try
{
var userInvited = await userManager.Users.FirstOrDefaultAsync(x => x.Id == msg.invitedId);
if (userInvited == null) return Ok(new { code = 404, message = "用户未找到" });
var invitationRecord = await sb.T_Invitation.FindAsync(msg.invitedId);
if (invitationRecord != null)
{
if (invitationRecord.my_request.Any(req => req.invitor_id == userId && req.match_id == msg.matchId))
{
return Ok(new { code = 409, message = "邀请已存在" });
}
}
invitationRecord = new InviteBg
{
user_id = msg.invitedId,
my_request = new List<(int, int)>()
};
invitationRecord.my_request.Add((invitor_id: userId, match_id: msg.matchId));
await sb.SaveChangesAsync();
var data = new
{
invitedId = userId,
matchId = msg.matchId,
};
return Ok(new { code = 200, message = "邀请成功", data });
}
catch (Exception ex)
{
return Ok(new { code = 500, message = "服务器错误", details = ex.Message });
}
}
}
}
}