using System;
using System.Collections.Generic;
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.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();

        [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);

                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
                    },
                    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 = (int)userInfo.AccountType
                    }, 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
                    };
                }
                if (Common.Config.IsPushMessage==1)
                {
                    for (var i = 0; i < 10; i++)
                    {
                        Random rd = new Random();
                        int num = rd.Next(0, 1000);
                        Common.Message.PushMessageModel model = new Common.Message.PushMessageModel()
                        {
                            CategoryId = 0,
                            Content = DateTime.Now.ToString("yyyyMMdd HH:mm:ss fff") + "推送内容" + i.ToString(),
                            CoverImg = "",
                            CreateByName = userInfo.AccountName,
                            JumpUrl = "",
                            ReceiveId = userInfo.Id.ToString(),
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = DateTime.Now.ToString("yyyyMMdd HH:mm:ss fff") + "推送标题" + i.ToString(),
                        };
                        //手机推送
                        if (num % 4 == 1)
                        {
                            model.Platform = 1;
                        }
                        //Web推送
                        else if (num % 4 == 2)
                        {
                            model.Platform = 2;
                            model.ReceiveId = userInfo.Id.ToString();
                        }
                        //短信推送
                        else if (num % 4 == 3)
                        {
                            model.Platform = 3;
                            model.MsgTemplateCode = "短信模板代码";
                            model.MsgSign = "签名";
                            model.ReceiveId = "13551126755";
                        }
                        //邮件推送
                        else
                        {
                            model.Platform = 4;
                            model.ReceiveId = "1006186972@qq.com";
                        }
                        Common.Message.MessageHelper.SendMessage(model);
                    }
                }

                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),
                    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);
            }
        }
    }
}