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
                IUserInfoToken eduUserInfo = new EduUserInfoToken()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.WebAdmin,
                    uid = model.Id.ToString()
                };

                //生成ERP-Token
                IUserInfoToken erpUserInfo = new ErpTokenUserInfo()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.ERP,
                    uid = model.Id.ToString(),
                    groupId = model.Group_Id
                };

                string token = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_User_Key, eduUserInfo);
                string erpToken = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_ERP_User_Key, erpUserInfo);
                var treeList = menuModule.GetTreeMenuModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                {
                    MenuType = accountType
                });
                UserInfo obj = new UserInfo
                {
                    Id = model.Id,
                    AccountType=model.AccountType,
                    Group_Id = model.Group_Id,
                    GroupName = model.GroupName,
                    School_Id = model.School_Id,
                    AccountName = model.AccountName,
                    SchoolName = model.SchoolName,
                    Token = token,
                    ErpToken = erpToken,
                    MenuList = treeList,
                    GroupLogo = model.GroupLogo,
                    UserIcon = model.UserIcon,
                    ApiRequestFromEnum = Common.Enum.ApiRequestFromEnum.WebAdmin,
                    DeptId = model.Dept_Id,
                    DeptName = model.DeptName,
                    PostId = model.Post_Id,
                    PostName = model.PostName,
                };
                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)
            {
                UserInfo userInfo = UserReidsCache.GetUserLoginInfo(Uid);
                if (userInfo != null)
                {
                    var treeList = menuModule.GetTreeMenuModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                    {
                        MenuType =(int) userInfo.AccountType
                    });
                    userInfo.MenuList = treeList;
                }
                return ApiResult.Success(data: userInfo);
            }
            else
            {
                return ApiResult.Failed();
            }
        }
    }
}