using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Ocsp;
using System.Text.Json;
using System.Runtime.InteropServices;
using TencentCloud.Scf.V20180416.Models;
using Quartz.Impl.AdoJobStore.Common;
using TencentCloud.Gaap.V20180529.Models;

namespace molilian.api.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class UserController : ControllerBase
    {
        readonly IAuthorizationProvider provider = new AdminProvider();
        protected IHttpContextAccessor _accessor;
        public UserController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        [HttpPost]
        public ActionResult login([FromBody] JsonElement form)
        {
            var domain = _accessor.HttpContext.GetApiDomain();
            string username = form.Read("username", string.Empty);
            string password = form.Read("password", string.Empty);
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return new APIResult(new { msg = "账号密码不正确" }, APIResultCodeEnum.InvalidRequest);

            var user = new DBContext.Table("admins").Get<dynamic>("username=@username", new { username });
            if (user == null) return new APIResult(new { msg = "账号密码不正确" }, APIResultCodeEnum.InvalidRequest);
            if (user.status != 1) return new APIResult(new { msg = "账号密码不正确" }, APIResultCodeEnum.InvalidRequest);

            string dbPassword = user.password;

            var config = TkConfigCore.Get();
            string pwd = $"{password}{config.pass_salt}".MD5();
            if (!dbPassword.Equals(pwd)) return new APIResult(new { msg = "账号密码不正确" }, APIResultCodeEnum.InvalidRequest);

            //检查登录,然后发布token
            var accessToken = provider.Create(user.id, username, password, user.roles, domain, _accessor.HttpContext.GetUserIp());
            if (accessToken == null)
            {
                return new APIResult(new { msg = "账号/密码无效或已被禁用" }, APIResultCodeEnum.InvalidRequest);
            }
            return new APIResult(new { data = accessToken });
        }


        [HttpPost]
        public ActionResult logout()
        {
            (var ticket, var domain) = _accessor.HttpContext.GetAccessToken();
            provider.Revoke(domain, ticket);
            return new APIResult(new { success = true, message = "ok" });
        }


        [HttpPost]
        public ActionResult menu()
        {
            return new APIResult(new { success = true, message = "ok" });
        }

        [HttpPost]
        public ActionResult info()
        {
            return new APIResult(new { success = true, message = "ok" });
        }

    }
}