using Auth.Models;
using Long.Common.Basedata;
using Long.DAO.Basedata;
using Long.Utils.Encryptor;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Runtime.CompilerServices;

namespace Auth.Controllers;

public class AccountController : Controller
{
    private readonly ISystemUserDatabase _systemUserDatabase = new SystemUserDatabase();
    private readonly IUserDatabase _userDatabase = new UserDatabase();
    private string _encryptionKey;

    public AccountController(IConfiguration configuration)
    {
        this._encryptionKey = configuration["EncryptorKey"] ?? "";
    }

    /// <summary>
    /// 登录页
    /// </summary>
    /// <param name="returnUrl"></param>
    /// <returns></returns>
    [HttpGet]
    public IActionResult Login(string returnUrl)
    {
        return View(returnUrl);
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="loginModel"></param>
    /// <returns></returns>
    /// <exception cref="ApplicationException"></exception>
    [HttpPost]
    public async Task<IActionResult> Login(LoginModel loginModel)
    {
        if (!ModelState.IsValid) { 
            throw new ApplicationException("数据不完整");
        }
        if (loginModel.ClientId == "admin")
        {
            // 系统用户登录
            var systemUser = await _systemUserDatabase.GetByUserNameAsync(loginModel.UserName);
            if (systemUser != null && DESEncryptor.Encrypt(loginModel.Password, _encryptionKey) == systemUser.Password)
            {
                AuthenticationProperties props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
                };
                //await HttpContext.SignInAsync(systemUser.Id.ToString(),, props);
            }
        }
        return Json(null);
    }
}
