using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.App;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.User;
using Edu.Module.Public;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Edu.WebApi.Helper;
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.APP
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class APPStudentLoginController : BaseController
    {
        /// <summary>
        /// 账号管理处理类
        /// </summary>
        private readonly AccountModule accountModule = new AccountModule();

        /// <summary>
        /// 公用处理类
        /// </summary>
        private readonly PublicModule publicModule = new PublicModule();


        /// <summary>
        /// 用户状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetAccountState()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            string account = jobj.GetStringValue("account");
            var model = accountModule.GetStudentExt(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = Common.Enum.User.AccountTypeEnum.Student
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("该账号不存在");
            }
            else if (model.Status == Common.Enum.DateStateEnum.Delete)
            {
                return ApiResult.Failed(message: $"此账号【{ account }】已禁用", new { Error = 2 });
            }
            else if (model.ActivationStatus == 0)
            {
                return ApiResult.Failed(message: "该账号未激活", new { resultCode = (int)ResultCode.AccountNotActivation });
            }
            else
            {
                return ApiResult.Success("账号正常");
            }
        }

        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult Login()
        {

            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            string account = jobj.GetStringValue("Account");
            string password = jobj.GetStringValue("Password");

            var model = accountModule.GetStudentExt(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = Common.Enum.User.AccountTypeEnum.Student
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed(message: "用户不存在", new { Error = -1 });
            }
            else
            {
                AppStudentInfo frozenInfo = Cache.User.AppStudentReidsCache.GetStudentFrozen(model.Id);
                if (frozenInfo != null && frozenInfo.Id > 0 && frozenInfo.IsFrozen == 1)
                {
                    AppStudentLoginError errorObj = Cache.User.AppStudentReidsCache.GetStudentErrorLogin(model.Id);
                    if (errorObj != null && errorObj.Id > 0)
                    {
                        int ts = Convert.ToInt32((System.DateTime.Now - errorObj.ErrorTime.Value).TotalMinutes);
                        if ((10 - ts) == 0)
                        {
                            ts = 1;
                        }
                        else
                        {
                            ts = 10 - ts;
                        }
                        return ApiResult.Failed(message: $"账号已冻结，{ ts}分钟后才能重新登录", new { Error = 0 });
                    }
                    return ApiResult.Failed(message: $"账号已冻结，请稍等再重新登录", new { Error = 0 });
                }
                if (model.ActivationStatus == 0)
                {
                    return ApiResult.Failed("账号未激活", new { Error = 1 });
                }

                if (password != "Viitto!@#123")
                {
                    password = Common.DES.Encrypt(password);
                    if (model.Password != password)
                    {
                        AppStudentLoginError errorObj = Cache.User.AppStudentReidsCache.GetStudentErrorLogin(model.Id);
                        if (errorObj != null && errorObj.Id > 0)
                        {
                            errorObj.ErrorNum = errorObj.ErrorNum + 1;
                            errorObj.ErrorTime = System.DateTime.Now;
                        }
                        else
                        {
                            errorObj = new AppStudentLoginError
                            {
                                ErrorNum = 1,
                                ErrorTime = System.DateTime.Now,
                                Id = model.Id,
                                Group_Id = model.Group_Id,
                                School_Id = model.School_Id,
                            };
                        }
                        if (errorObj.ErrorNum >= 5)
                        {
                            AppStudentInfo frozenObj = new AppStudentInfo
                            {
                                Id = model.Id,
                                AccountType = model.AccountType,
                                Group_Id = model.Group_Id,
                                GroupName = model.GroupName,
                                School_Id = model.School_Id,
                                AccountId = model.AccountId,
                                AccountName = model.AccountName,
                                SchoolName = model.SchoolName,
                                GroupLogo = model.GroupLogo,
                                UserIcon = model.UserIcon,
                                ApiRequestFromEnum = Common.Enum.ApiRequestFromEnum.AppStudent,
                                IsFrozen = 1
                            };
                            Cache.User.AppStudentReidsCache.StudentFrozenSet(Cache.CacheKey.Student_Frozen_Key + model.Id, frozenObj, 600);
                            Cache.User.AppStudentReidsCache.StudentErrorLoginSet(Cache.CacheKey.Student_ErrorLogin_Key + model.Id, errorObj, 600);
                            return ApiResult.Failed(message: $"账号已冻结，10分钟后才能重新登录", new { Error = 0 });
                        }
                        Cache.User.AppStudentReidsCache.StudentErrorLoginSet(Cache.CacheKey.Student_ErrorLogin_Key + model.Id, errorObj, 600);
                        return ApiResult.Failed("密码错误", new { Error = 0 });
                    }
                    else
                    {
                        AppStudentLoginError errorObj = Cache.User.AppStudentReidsCache.GetStudentErrorLogin(model.Id);
                        if (errorObj != null && errorObj.Id > 0)
                        {
                            Cache.User.AppStudentReidsCache.StudentErrorLoginSet(Cache.CacheKey.Student_ErrorLogin_Key + model.Id, errorObj, 0);
                        }
                    }
                }
                if (model.Status == Common.Enum.DateStateEnum.Delete)
                {
                    return ApiResult.Failed(message: $"此账号【{ account }】已禁用", new { Error = 2 });
                }

                //生成教育token
                EduUserInfoToken eduUserInfo = new EduUserInfoToken()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.AppStudent,
                    uid = model.Id.ToString()
                };
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();


                string token = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_User_Key, eduUserInfo);
                AppStudentInfo obj = new AppStudentInfo
                {
                    Id = model.Id,
                    AccountType = model.AccountType,
                    Group_Id = model.Group_Id,
                    GroupName = model.GroupName,
                    School_Id = model.School_Id,
                    AccountId = model.AccountId,
                    AccountName = model.AccountName,
                    SchoolName = model.SchoolName,
                    Token = token,
                    GroupLogo = model.GroupLogo,
                    UserIcon = model.UserIcon,
                    ApiRequestFromEnum = Common.Enum.ApiRequestFromEnum.AppStudent,
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    }
                };
                Cache.User.AppStudentReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success(data: obj);
            }
        }


        /// <summary>
        /// 激活账号发送短信验证码
        /// </summary>
        /// <param name="request">获取信息</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult SendCodeByStudentInfo()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            string account = jobj.GetStringValue("account");
            var model = accountModule.GetStudentExt(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = Common.Enum.User.AccountTypeEnum.Student
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("该账号不存在");
            }
            else if (model.Status == Common.Enum.DateStateEnum.Delete)
            {
                return ApiResult.Failed(message: $"此账号【{ account }】已禁用", new { Error = 2 });
            }
            else if (model.ActivationStatus == 0)
            {
                //暂时去掉
                //bool canSendCode = Cache.App.MsgUserRedisCache.CheckCanSendCode(account, out string message);
                //if (!canSendCode)
                //{
                //    return ApiResult.Failed(message);
                //}
                string code = StringHelper.CreateRandomCode(4);
                //新增短信记录信息
                var msgLogModel = new Model.Entity.System.RB_Msg_Log
                {
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    Student_Id = model.Id,
                    CreateDate = DateTime.Now,
                    SendStatus = Common.Enum.System.MsgSendStatusEnum.InReceipt,
                    CreateBy = 0,
                    CreateByName = "系统自动发送",
                    SendContent = code,
                    ReceiverName = model.AccountName,
                    ReceiverPhone = model.Account
                };
                var result = new Module.System.MsgLogModule().SendCode(code, Common.Enum.System.BaseTemplateTypeEnum.SendCode, msgLogModel);
                if (result)
                {
                    Cache.App.MsgUserRedisCache.SetSendCode(Cache.CacheKey.MsgStudent_Login_Key + account, code, 600);
                    Cache.App.MsgUserRedisCache.AddUserSendCodeHistory(account);
                    return ApiResult.Success("验证码已发送，请注意查收", data: null);
                }
                else
                {
                    return ApiResult.Failed("发送短信失败，请稍后再试");
                }

            }
            else
            {
                return ApiResult.Failed(message: "该账号已激活", new { resultCode = (int)ResultCode.AccountNotActivation });
            }
        }



        /// <summary>
        /// 判断输入的验证码是否正确
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        [AllowAnonymous]
        public ApiResult CheckSendCode()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());

            string account = jobj.GetStringValue("account");
            string sendcode = jobj.GetStringValue("sendcode");
            if (string.IsNullOrWhiteSpace(sendcode))
            {
                return ApiResult.Failed("验证码不能为空");
            }
            else
            {

                object cacheCode = Cache.App.MsgUserRedisCache.GetUserCode(Cache.CacheKey.MsgStudent_Login_Key + account, Common.Enum.ApiRequestFromEnum.AppStudent);
                if (cacheCode == null)
                {
                    return ApiResult.Failed("验证码已失效,请重新获取");
                }
                else
                {
                    if (!cacheCode.ToString().Equals(sendcode))
                    {
                        return ApiResult.Failed("验证码不正确，请填写正确的验证码");
                    }
                }
            }
            Cache.App.MsgUserRedisCache.SetSendCode(Cache.CacheKey.MsgStudent_Login_Key + account, sendcode, 1);
            return ApiResult.Success("验证码输入正确");
        }




        /// <summary>
        /// 激活并登陆
        /// </summary>
        /// <param name="request">获取信息</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult ActivationLogin()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());

            string account = jobj.GetStringValue("account");
            // string sendcode = jobj.GetStringValue("sendcode");
            string password = jobj.GetStringValue("password");
            //if (string.IsNullOrWhiteSpace(sendcode))
            //{
            //    return ApiResult.Failed("验证码不能为空");
            //}
            //else
            //{

            //    object cacheCode = Cache.App.MsgUserRedisCache.GetUserCode(Cache.CacheKey.MsgStudent_Login_Key + account, Common.Enum.ApiRequestFromEnum.AppStudent);
            //    if (cacheCode == null)
            //    {
            //        return ApiResult.Failed("验证码已失效,请重新获取");
            //    }
            //    else
            //    {
            //        if (!cacheCode.ToString().Equals(sendcode))
            //        {
            //            return ApiResult.Failed("验证码不正确，请填写正确的验证码");
            //        }
            //    }
            //}
            var model = accountModule.GetStudentExt(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = Common.Enum.User.AccountTypeEnum.Student
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed(message: "用户不存在", new { Error = -1 });
            }
            else
            {
                //if (password != "Viitto!@#123")
                //{
                //    password = Common.DES.Encrypt(password);
                //    if (model.Password != password)
                //    {
                //        return ApiResult.Failed("密码错误", new { Error = 0 });
                //    }
                //}
                if (model.Status == Common.Enum.DateStateEnum.Delete)
                {
                    return ApiResult.Failed(message: $"此账号【{ account }】已禁用", new { Error = 2 });
                }
                //更新用户的密码
                bool ss = accountModule.SetResetPwdAndAtatus(new RB_Account_ViewModel { ActivationStatus = 1, AccountId = model.AccountId, AccountType = model.AccountType, Group_Id = model.Group_Id }, password = Common.DES.Encrypt(password));

                //生成教育token
                EduUserInfoToken eduUserInfo = new EduUserInfoToken()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.AppStudent,
                    uid = model.Id.ToString()
                };
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();
                string token = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_User_Key, eduUserInfo);
                AppStudentInfo obj = new AppStudentInfo
                {
                    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,
                    ActivationStatus = model.ActivationStatus,
                    GroupLogo = model.GroupLogo,
                    UserIcon = model.UserIcon,
                    ApiRequestFromEnum = Common.Enum.ApiRequestFromEnum.AppStudent,
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    }
                };
                Cache.User.AppStudentReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success("", new { obj, model.ActivationStatus });
            }


        }



        /// <summary>
        /// 用户状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetAccountOpenid()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());
            string openid = jobj.GetStringValue("Openid");
            var model = accountModule.GetStudentExt(new RB_Account_ViewModel()
            {
                OpenId = openid.Trim(),
                AccountType = Common.Enum.User.AccountTypeEnum.Student
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("该账号不存在", new { resultCode = (int)ResultCode.AccountBind });
            }
            else if (model.Status == Common.Enum.DateStateEnum.Delete)
            {
                return ApiResult.Failed(message: $"此账号【{ model.Account }】已禁用", new { Error = 2 });
            }
            else if (model.ActivationStatus == 0)
            {
                return ApiResult.Failed(message: "该账号未激活", new { resultCode = (int)ResultCode.AccountNotActivation });
            }
            else
            {
                //生成教育token
                EduUserInfoToken eduUserInfo = new EduUserInfoToken()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.AppStudent,
                    uid = model.Id.ToString()
                };
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();
                string token = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_User_Key, eduUserInfo);
                AppStudentInfo obj = new AppStudentInfo
                {
                    Id = model.Id,
                    AccountType = model.AccountType,
                    Group_Id = model.Group_Id,
                    GroupName = model.GroupName,
                    School_Id = model.School_Id,
                    AccountId = model.AccountId,
                    AccountName = model.AccountName,
                    SchoolName = model.SchoolName,
                    Token = token,
                    GroupLogo = model.GroupLogo,
                    UserIcon = model.UserIcon,
                    ApiRequestFromEnum = Common.Enum.ApiRequestFromEnum.AppStudent,
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    }
                };
                Cache.User.AppStudentReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success("", new { obj, model.ActivationStatus });
            }
        }



        /// <summary>
        /// 激活并登陆
        /// </summary>
        /// <param name="request">获取信息</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult ActivationLoginByOpenid()
        {
            JObject jobj = JObject.Parse(RequestParm.Msg.ToString());

            string account = jobj.GetStringValue("account");
            string sendcode = jobj.GetStringValue("sendcode");
            string openid = jobj.GetStringValue("openid");
            string password = jobj.GetStringValue("password");
            if (string.IsNullOrWhiteSpace(sendcode))
            {
                return ApiResult.Failed("验证码不能为空");
            }
            else
            {

                object cacheCode = Cache.App.MsgUserRedisCache.GetUserCode(Cache.CacheKey.MsgStudent_Login_Key + account, Common.Enum.ApiRequestFromEnum.AppStudent);
                if (cacheCode == null)
                {
                    return ApiResult.Failed("验证码已失效,请重新获取");
                }
                else
                {
                    if (!cacheCode.ToString().Equals(sendcode))
                    {
                        return ApiResult.Failed("验证码不正确，请填写正确的验证码");
                    }
                }
            }
            Cache.App.MsgUserRedisCache.SetSendCode(Cache.CacheKey.MsgStudent_Login_Key + account, sendcode, 1);
            var model = accountModule.GetStudentExt(new RB_Account_ViewModel()
            {
                Account = account.Trim(),
                AccountType = Common.Enum.User.AccountTypeEnum.Student
            })?.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed(message: "用户不存在", new { Error = -1 });
            }
            else
            {
                var modelWeiXin = accountModule.GetStudentExt(new RB_Account_ViewModel()
                {
                    OpenId = openid.Trim(),
                    AccountType = Common.Enum.User.AccountTypeEnum.Student
                })?.FirstOrDefault();
                if (modelWeiXin.Account != account)
                {
                    return ApiResult.Failed(message: "微信号已绑定其他账户", new { Error = 3 });
                }
                if (model.Status == Common.Enum.DateStateEnum.Delete)
                {
                    return ApiResult.Failed(message: $"此账号【{ account }】已禁用", new { Error = 2 });
                }

                //更新用户的密码
                bool ss = accountModule.SetResetPwdAndAtatus(new RB_Account_ViewModel { OpenId = openid, ActivationStatus = 1, AccountId = model.AccountId, AccountType = model.AccountType, Group_Id = model.Group_Id }, password = Common.DES.Encrypt(password));

                //生成教育token
                EduUserInfoToken eduUserInfo = new EduUserInfoToken()
                {
                    requestFrom = Common.Enum.ApiRequestFromEnum.AppStudent,
                    uid = model.Id.ToString()
                };
                //上传配置
                var uploadConfig = publicModule.GetFileStoreList(new Model.Public.RB_File_Store() { Group_Id = model.Group_Id, IsDefault = 1 })?.FirstOrDefault();
                string token = WebApiTokenHelper.CreateToken(Common.GlobalKey.JWT_User_Key, eduUserInfo);
                AppStudentInfo obj = new AppStudentInfo
                {
                    Id = model.Id,
                    AccountType = model.AccountType,
                    Group_Id = model.Group_Id,
                    GroupName = model.GroupName,
                    AccountId = model.AccountId,
                    School_Id = model.School_Id,
                    AccountName = model.AccountName,
                    SchoolName = model.SchoolName,
                    Token = token,
                    ActivationStatus = model.ActivationStatus,
                    GroupLogo = model.GroupLogo,
                    UserIcon = model.UserIcon,
                    ApiRequestFromEnum = Common.Enum.ApiRequestFromEnum.AppStudent,
                    UploadConfig = new
                    {
                        uploadConfig?.Bucket,
                        uploadConfig?.StoreType,
                        uploadConfig?.Region,
                        uploadConfig?.CustomDomain,
                        uploadConfig?.SecretKey,
                        uploadConfig?.SecretId,
                        uploadConfig?.UploadDomain
                    }
                };
                Cache.User.AppStudentReidsCache.UserInfoSet(Cache.CacheKey.User_Login_Key + model.Id, obj, Common.Config.JwtExpirTime);
                return ApiResult.Success("", new { obj, model.ActivationStatus });
            }
        }


        #region 兴趣爱好的基础信息
        /// <summary>
        /// 兴趣爱好信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetInterestList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(InterestEnum));

            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 日语基础掌握信息情况
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetJapanbaseInfoEnumList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(JapanbaseInfoEnum));

            return ApiResult.Success(data: list);
        }
        #endregion 
    }
}
