using System;
using System.Collections.Generic;
using System.Linq;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.System;
using Edu.Model.ViewModel.User;
using Edu.Module.Public;
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>
        private readonly PublicModule publicModule = new PublicModule();
        /// <summary>
        /// 教师处理类
        /// </summary>
        private readonly TeacherModule teacherModule = new TeacherModule();

        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult Test()
        {
            return ApiResult.Success();
        }

        /// <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: $"登录失败，账号或密码错误!");
            }
            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);






                #region 获取甲鹤教育Token
                string JHTenantId = Config.JHTenantId;
                string JHMallBaseId = Config.JHMallBaseId;


                IUserInfoToken mallJHUserInfo = new ErpTokenUserInfo()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.Mall,
                    uid = JHTenantId,
                    groupId = model.Group_Id
                };
              
                #region JWT

               // string mallToken = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_Mall_User_Key, mallJHUserInfo);

                #endregion

                #endregion




                #region 获取甲鹤教育Token


                #region JWT
                JWT.IDateTimeProvider provider2 = new JWT.UtcDateTimeProvider();
                var now2 = provider2.GetNow().AddMinutes(-1);
                var unixEpoch2 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
                var secondsSinceEpoch2 = Math.Round((now2 - unixEpoch2).TotalSeconds);
                var payload2 = new Dictionary<string, object>
                                {
                                        {"iat",secondsSinceEpoch2 },
                                        {"exp",secondsSinceEpoch2+Config.JwtExpirTime},
                                        {"mall_userInfoJH",mallJHUserInfo }
                                };
                JWT.Algorithms.IJwtAlgorithm algorithm2 = new JWT.Algorithms.HMACSHA256Algorithm();
                JWT.IJsonSerializer serializer2 = new JWT.Serializers.JsonNetSerializer();
                JWT.IBase64UrlEncoder urlEncoder2 = new JWT.JwtBase64UrlEncoder();
                JWT.IJwtEncoder encoder2 = new JWT.JwtEncoder(algorithm2, serializer2, urlEncoder2);
                string secret2 = Config.MallJwtSecretKey;
                string malltokenJH = encoder2.Encode(payload2, secret2);
                #endregion

                #endregion


                var treeList = menuModule.GetPostMenuTreeModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                {
                    MenuType = accountType
                }, out List<RB_Menu_ViewModel> userCenterList, postIds: model.Post_Id.ToString());
                //获取功能权限列表
                var actionList = menuModule.GetPostMenuFunctionListModule(model.Post_Id.ToString());
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();

                UserInfo obj = new UserInfo
                {
                    Id = model.Id,
                    AccountId = model.AccountId,
                    UserMobile = model.Account,
                    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,
                    MallToken = malltokenJH,
                    JHMallBaseId = JHMallBaseId,
                    JHTenantId = JHTenantId,
                    MenuList = treeList,
                    UserCenterList = userCenterList,
                    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,
                    Email = model.Email,
                    ActionMenuList = actionList?.Select(qitem => new { qitem.FunctionCode, qitem.FunctionName, qitem.MenuName, qitem.MenuUrl }),
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    },
                    StudyAbroadObj = publicModule.GetStudyAbroadListModule()
                };
                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.GetPostMenuTreeModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                    {
                        MenuType = 1
                    }, out List<RB_Menu_ViewModel> userCenterList, userInfo.PostId.ToString());
                    userInfo.MenuList = treeList;
                    userInfo.UserCenterList = userCenterList;
                    //获取功能权限列表
                    var actionList = menuModule.GetPostMenuFunctionListModule(userInfo.PostId.ToString());
                    userInfo.ActionMenuList = actionList?.Select(qitem => new { qitem.FunctionCode, qitem.FunctionName, qitem.MenuName, qitem.MenuUrl });
                    userInfo.StudyAbroadObj = publicModule.GetStudyAbroadListModule();
                    //上传配置
                    var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = userInfo.Group_Id, IsDefault = 1 })?.FirstOrDefault();
                    userInfo.UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    };
                }
                return ApiResult.Success(data: userInfo);
            }
            else
            {
                return ApiResult.Failed();
            }
        }




        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult LoginTeacher()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            string account = jobj.GetStringValue("Account");
            string password = jobj.GetStringValue("Password");
            int accountType = jobj.GetInt("AccountType", 2);
            int classRoomId = jobj.GetInt("ClassRoomId", 0);
            if (classRoomId == 0)
            {
                return ApiResult.Failed("请传入教室id");
            }
            var model = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = AccountTypeEnum.Teacher
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed(message: $"本教室没有找到您的课");
            }
            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 }】已禁用,如需使用请联系管理员!");
                }
                var list = new Module.Course.ClassModule().GetClassTimeByRoomId(classRoomId, model.Group_Id);

                var tempList = list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.TeacherId == model.AccountId && x.NewPlanDateTime.HasValue && System.DateTime.Now >= x.NewPlanDateTime.Value.AddMinutes(-10) && x.NewEndPlanDateTime.HasValue && System.DateTime.Now < x.NewEndPlanDateTime.Value.AddMinutes(30));

                if (tempList == null || !tempList.Any())
                {
                    return ApiResult.Failed("本教室没有找到您的课");
                }
                var classModel = tempList.OrderBy(x => x.NewPlanDateTime).FirstOrDefault();
                var extModel = new Module.Course.ClassRoomModule().GetClassRoomModule(classModel.ClassRoomId);
                var classInfo = new
                {
                    ClassName = classModel.ClassName ?? "",
                    CourseName = classModel.CourseName ?? "",
                    ClassTime = classModel.NewPlanDateTime.HasValue ? classModel.NewPlanDateTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    ClassHours = new Module.Course.ClassModule().GetNowClassHours(classModel),
                    IsLessPlan = classModel.LessonPlanId > 0 ? 1 : 0,
                    RoomPicList = string.IsNullOrWhiteSpace(extModel.RoomPic) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(extModel.RoomPic),
                    SuiPaiList = string.IsNullOrWhiteSpace(classModel.SuiPai) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(classModel.SuiPai),
                    VideoUrl = classModel.VideoUrl ?? "",
                    classModel.ClassId,
                    classModel.ClassTimeId,
                    classModel.ClassPlanId,
                    classModel.ClassRoomId,
                    classModel.ClassStatus,
                    ClassEndTime = classModel.NewEndPlanDateTime.HasValue ? classModel.NewEndPlanDateTime.Value.ToString("HH:mm") : "",
                };


                //生成教育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.GetPostMenuTreeModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                {
                    MenuType = accountType
                }, out List<RB_Menu_ViewModel> userCenterList, postIds: model.Post_Id.ToString());
                //获取功能权限列表
                var actionList = menuModule.GetPostMenuFunctionListModule(model.Post_Id.ToString());
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();

                UserInfo obj = new UserInfo
                {
                    Id = model.Id,
                    AccountId = model.AccountId,
                    UserMobile = model.Account,
                    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,
                    UserCenterList = userCenterList,
                    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,
                    ActionMenuList = actionList?.Select(qitem => new { qitem.FunctionCode, qitem.FunctionName, qitem.MenuName, qitem.MenuUrl }),
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    },
                    ClassInfo = classInfo,
                    StudyAbroadObj = publicModule.GetStudyAbroadListModule()
                };
                UserReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success(data: obj);
            }
        }


        /// <summary>
        /// 人脸识别登录
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult LoginTeacherById()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            int tId = jobj.GetInt("TId");
            int classRoomId = jobj.GetInt("ClassRoomId", 0);
            if (classRoomId == 0)
            {
                return ApiResult.Failed("请传入教室id");
            }
            var modelTeacher = teacherModule.GetTeacherByTId(tId, 0);
            if (modelTeacher == null)
            {
                return ApiResult.Failed("老师不存在");
            }
            var model = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
            {
                AccountId = tId,
                AccountType = AccountTypeEnum.Teacher
            })?.FirstOrDefault();
            if (model.Status == Common.Enum.DateStateEnum.Delete)
            {
                return ApiResult.Failed(message: $"此账号【{ model.Account }】已禁用,如需使用请联系管理员!");
            }
            var list = new Module.Course.ClassModule().GetClassTimeByRoomId(classRoomId, model.Group_Id);

            var tempList = list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.TeacherId == model.AccountId && x.NewPlanDateTime.HasValue && System.DateTime.Now >= x.NewPlanDateTime.Value.AddMinutes(-10) && x.NewEndPlanDateTime.HasValue && System.DateTime.Now < x.NewEndPlanDateTime.Value.AddMinutes(30));
            if (tempList == null || !tempList.Any())
            {
                list = new Module.Course.ClassModule().GetClassTimeByTId(tId, model.Group_Id);

                tempList = list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.TeacherId == model.AccountId && x.NewPlanDateTime.HasValue && System.DateTime.Now >= x.NewPlanDateTime.Value.AddMinutes(-10) && x.NewEndPlanDateTime.HasValue && System.DateTime.Now < x.NewEndPlanDateTime.Value);
                if (tempList == null || !tempList.Any())
                {
                    tempList = list.OrderBy(x => x.NewEndPlanDateTime).Where(x => x.TeacherId == model.AccountId && x.NewEndPlanDateTime.HasValue && System.DateTime.Now < x.NewEndPlanDateTime.Value && x.NewEndPlanDateTime.HasValue && System.DateTime.Now.ToString("yyyy-MM-dd") == x.NewEndPlanDateTime.Value.ToString("yyyy-MM-dd"));
                }
                var result = new
                {
                    modelTeacher.FirstOrDefault()?.TeacherName,
                    tempList = tempList.Select(x => new { x.RoomName, x.TeacherName, NewPlanDateTime = x.NewPlanDateTime.HasValue ? x.NewPlanDateTime.Value.ToString("yyyy-MM-dd HH:mm") : "", NewEndPlanDateTime = x.NewEndPlanDateTime.HasValue ? x.NewEndPlanDateTime.Value.ToString("yyyy-MM-dd HH:mm") : "" })
                };
                return ApiResult.Failed(message: $"本教室没有找到您的课", data: result);
            }
            else
            {
                var classModel = tempList.OrderBy(x => x.NewPlanDateTime).FirstOrDefault();
                var extModel = new Module.Course.ClassRoomModule().GetClassRoomModule(classModel.ClassRoomId);
                var classInfo = new
                {
                    ClassName = classModel.ClassName ?? "",
                    CourseName = classModel.CourseName ?? "",
                    ClassTime = classModel.NewPlanDateTime.HasValue ? classModel.NewPlanDateTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    ClassHours = new Module.Course.ClassModule().GetNowClassHours(classModel),
                    IsLessPlan = classModel.LessonPlanId > 0 ? 1 : 0,
                    RoomPicList = string.IsNullOrWhiteSpace(extModel.RoomPic) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(extModel.RoomPic),
                    SuiPaiList = string.IsNullOrWhiteSpace(classModel.SuiPai) ? new List<string>() : JsonHelper.DeserializeObject<List<string>>(classModel.SuiPai),
                    VideoUrl = classModel.VideoUrl ?? "",
                    classModel.ClassId,
                    classModel.ClassTimeId,
                    classModel.ClassPlanId,
                    classModel.ClassRoomId,
                    classModel.ClassStatus,
                    ClassEndTime = classModel.NewEndPlanDateTime.HasValue ? classModel.NewEndPlanDateTime.Value.ToString("HH:mm") : "",
                };


                //生成教育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.GetPostMenuTreeModule(new Model.ViewModel.System.RB_Menu_ViewModel()
                {
                    MenuType = 2
                }, out List<RB_Menu_ViewModel> userCenterList, postIds: model.Post_Id.ToString());
                //获取功能权限列表
                var actionList = menuModule.GetPostMenuFunctionListModule(model.Post_Id.ToString());
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();

                UserInfo obj = new UserInfo
                {
                    Id = model.Id,
                    AccountId = model.AccountId,
                    UserMobile = model.Account,
                    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,
                    UserCenterList = userCenterList,
                    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,
                    ActionMenuList = actionList?.Select(qitem => new { qitem.FunctionCode, qitem.FunctionName, qitem.MenuName, qitem.MenuUrl }),
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    },
                    ClassInfo = classInfo,
                    StudyAbroadObj = publicModule.GetStudyAbroadListModule()
                };
                UserReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success(data: obj);
            }


        }


    }
}