using EasyTemplate.Tool;
using Microsoft.AspNetCore.Mvc;
using RouteAttribute = Microsoft.AspNetCore.Mvc.RouteAttribute;

namespace EasyTemplate.Blazor.Web.Controller;

/// <summary>
/// 注意，如果需要扫码登录或是支付回调，可以使用该控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
    public HomeController(IHttpContextAccessor contextAccessor, SqlSugarRepository<SystemUser> user, INotificationService notificationService)
    {
        ContextAccessor = contextAccessor;
        User = user;
        NotificationService = notificationService;
    }

    /// <summary>
    /// 这里必须使用IgnoreAntiforgeryToken属性，绕过blazor的防伪验证
    /// </summary>
    /// <param name="userid"></param>
    /// <param name="name"></param>
    /// <param name="data"></param>
    /// <param name="phone"></param>
    /// <returns></returns>
    [HttpGet("scan_sign_in_call_back")]
    [IgnoreAntiforgeryToken] // <-- 关键特性：忽略该端点的防伪验证
    public async Task<IActionResult> ScanSignInCallback(long userid, string name, string data, string phone)
    {
        var user = await User.AsQueryable().FirstAsync(x => x.Id == userid);
        if (user == null) 
        {
            //这里必须使用重定向，它会指向/wwwroot/html/error.html页面，该页面专门用于扫码登录报错
            //error.html的query参数包含：
            //  code：错误代码
            //  title：提示
            //  message：错误信息
            //  image：info,success,warning,error
            return Redirect("/html/error.html?code=504&title=提示&message=该账户不存在，请联系管理员&image=info");
        }
        return Redirect("/");//重定向到首页
    }

    /// <summary>
    /// 
    /// </summary>
    private readonly IHttpContextAccessor ContextAccessor;
    /// <summary>
    /// 
    /// </summary>
    private readonly SqlSugarRepository<SystemUser> User;
    /// <summary>
    /// 
    /// </summary>
    private readonly INotificationService NotificationService;
}
