using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Mall.Model.Extend.User;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using JWT;
using Mall.Common;
using JWT.Algorithms;
using JWT.Serializers;
using Mall.Common.Enum;

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class TenantController : BaseController
    {
        private Module.User.TenantModule TenantModule = new Module.User.TenantModule();
        // JObject parm = JObject.Parse(RequestParm.msg.ToString());
        //UserInfo userInfo = UserReidsCache.GetUserLoginInfo(base.RequestParm.uid);
        public ApiResult Login()
        {
            var query = JsonConvert.DeserializeObject<RB_Tenant_Extend>(RequestParm.msg.ToString());
            var model = TenantModule.GetTenantListModule(query).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("未找到此用户");
            }
            else
            {
                if (model.Password != query.Password)
                {
                    return ApiResult.Failed("密码错误");
                }
                TokenUserInfo userInfo = new TokenUserInfo { uid = model.TenantId.ToString(), requestFrom = ApiRequestFromEnum.Web };
                string token = "";
                #region JWT
                IDateTimeProvider provider = new UtcDateTimeProvider();
                var now = provider.GetNow().AddMinutes(-1);
                var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
                var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
                var payload = new Dictionary<string, object>
                                {
                                        {"iat",secondsSinceEpoch },
                                        {"exp",secondsSinceEpoch+Config.JwtExpirTime},
                                        {"mall_userInfo",userInfo }
                                };
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                string secret = Config.JwtSecretKey;
                token = encoder.Encode(payload, secret);
                #endregion


                return ApiResult.Success("", model);
            }
        }
    }
}