using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Interface;
using OpenAuth.App.Response;
using OpenAuth.App.SSO;
using OpenAuth.Repository.Domain;
using Infrastructure.Helpers;
using SqlSugar;
using Infrastructure.Extensions;
using Infrastructure.Utilities;

namespace OpenAuth.WebApi.Controllers
{
    /// <inheritdoc />
    /// <summary>
    /// 登录及与登录信息获取相关的接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[ApiExplorerSettings(GroupName = "登录验证_Check")]
    public class CheckController : ControllerBase
    {
        private readonly IAuth _authUtil;
        private AuthStrategyContext _authStrategyContext;


        public CheckController(IAuth authUtil)
        {
            _authUtil = authUtil;
            _authStrategyContext = _authUtil.GetCurrentUser();
        }

        #region 当前登录用户资源

        #region 用户信息
        /// <summary>
        /// 获取登录用户资料
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Response<UserView> GetUserProfile()
        {
            var resp = new Response<UserView>();
            try
            {
                resp.Result = _authStrategyContext.User.MapTo<UserView>();
                if (_authStrategyContext.Orgs != null)
                {
                    //var orgLevel = _authStrategyContext.Orgs.Min(a => a.Level);
                    //resp.Result.OrgMaxLevel = orgLevel.ToString();
                }
            }
            catch (Exception e)
            {
                resp.Code = 500;
                resp.Message = e.Message;
            }

            return resp;
        }
        #endregion

        #region 角色
        /// <summary>
        /// 获取登录用户的所有可访问的角色
        /// </summary>
        [HttpGet]
        public Response<List<SysRole>> GetRoles()
        {
            var result = new Response<List<SysRole>>();
            try
            {
                result.Result = _authStrategyContext.Roles;
            }
            catch (CommonException ex)
            {
                if (ex.Code == Define.INVALID_TOKEN)
                {
                    result.Code = ex.Code;
                    result.Message = ex.Message;
                }
                else
                {
                    result.Code = 500;
                    result.Message = ex.InnerException != null
                        ? "OpenAuth.WebAPI数据库访问失败:" + ex.InnerException.Message
                        : "OpenAuth.WebAPI数据库访问失败:" + ex.Message;
                }

            }

            return result;
        }
        #endregion

        #region 部门
        /// <summary>
        /// 获取登录用户的所有可访问的组织信息
        /// </summary>
        [HttpGet]
        public Response<List<SysOrg>> GetOrgs()
        {
            var result = new Response<List<SysOrg>>();
            try
            {
                result.Result = _authStrategyContext.Orgs;
            }
            catch (CommonException ex)
            {
                if (ex.Code == Define.INVALID_TOKEN)
                {
                    result.Code = ex.Code;
                    result.Message = ex.Message;
                }
                else
                {
                    result.Code = 500;
                    result.Message = ex.InnerException != null
                        ? "OpenAuth.WebAPI数据库访问失败:" + ex.InnerException.Message
                        : "OpenAuth.WebAPI数据库访问失败:" + ex.Message;
                }

            }

            return result;
        }
        #endregion

        #region 菜单
        /// <summary>
        /// 获取登录用户的所有可访问的模块及菜单，以列表形式返回结果
        /// </summary>
        [HttpGet]
        public Response<List<ModuleView>> GetModules()
        {
            var result = new Response<List<ModuleView>>();
            try
            {
                result.Result = _authStrategyContext.Modules;
            }
            catch (CommonException ex)
            {
                if (ex.Code == Define.INVALID_TOKEN)
                {
                    result.Code = ex.Code;
                    result.Message = ex.Message;
                }
                else
                {
                    result.Code = 500;
                    result.Message = ex.InnerException != null
                        ? "OpenAuth.WebAPI数据库访问失败:" + ex.InnerException.Message
                        : "OpenAuth.WebAPI数据库访问失败:" + ex.Message;
                }
            }
            return result;
        }

        /// <summary>
        /// 获取登录用户的所有可访问的模块及菜单，以树状结构返回
        /// <param name="typeid">菜单类型</param>
        /// </summary>
        [HttpGet]
        public Response<IEnumerable<TreeItem<ModuleView>>> GetModulesTree(string typeid)
        {
            var result = new Response<IEnumerable<TreeItem<ModuleView>>>();
            try
            {
                result.Result = _authStrategyContext.Modules.WhereIF(!string.IsNullOrEmpty(typeid), a => a.ModuleTypeId == typeid).OrderBy(a => a.SortNo).GenerateTree(u => u.Id, u => u.ParentId, "0");
            }
            catch (CommonException ex)
            {
                if (ex.Code == Define.INVALID_TOKEN)
                {
                    result.Code = ex.Code;
                    result.Message = ex.Message;
                }
                else
                {
                    result.Code = 500;
                    result.Message = ex.InnerException != null
                        ? "OpenAuth.WebAPI数据库访问失败:" + ex.InnerException.Message
                        : "OpenAuth.WebAPI数据库访问失败:" + ex.Message;
                }

            }

            return result;
        }
        #endregion

        #endregion

        #region 登录
        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="request">登录参数</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Response<LoginResult> Login(PassportLoginRequest request)
        {
            //var aaaa = Md5Helper.Encrypt(DESEncrypt.Encrypt(Md5Helper.Hash("x9p$E$Bxc$v1kViqZTJ1%#0sORIhf*^3"), "390cbc0b25469cc5").ToLower(), 32).ToLower();
            return _authUtil.Login(request.AppKey, request.Account, request.Password);
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <param name="token"></param>
        /// <param name="requestid">备用参数.</param>
        [HttpPost]
        public Response<bool> Logout()
        {
            var resp = new Response<bool>();
            try
            {
                resp.Result = _authUtil.Logout();
            }
            catch (Exception e)
            {
                resp.Result = false;
                resp.Message = e.Message;
            }

            return resp;
        }
        #endregion

        #region 未启用/后台使用

        #region 检验token是否有效
        /// <summary>
        /// 检验token是否有效
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="requestid">备用参数.</param>
        [HttpGet]
        [ApiExplorerSettings(IgnoreApi = true)]
        public Response<bool> GetStatus()
        {
            var result = new Response<bool>();
            try
            {
                result.Result = _authUtil.CheckLogin();
            }
            catch (Exception ex)
            {
                result.Code = Define.INVALID_TOKEN;
                result.Message = ex.Message;
            }

            return result;
        }
        /// <summary>
        /// 图片验证token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Validate()
        {
            if (_authUtil.CheckLogin())
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
        #endregion

        #region 根据token获取用户名称
        /// <summary>
        /// 根据token获取用户名称
        /// </summary>
        [HttpGet]
        [ApiExplorerSettings(IgnoreApi = true)]
        public Response<string> GetUserName()
        {
            var result = new Response<string>();
            try
            {
                result.Result = _authStrategyContext.User.Account;
            }
            catch (CommonException ex)
            {
                if (ex.Code == Define.INVALID_TOKEN)
                {
                    result.Code = ex.Code;
                    result.Message = ex.Message;
                }
                else
                {
                    result.Code = 500;
                    result.Message = ex.InnerException != null
                        ? ex.InnerException.Message : ex.Message;
                }

            }

            return result;
        }
        #endregion

        #region 加载机构的全部下级机构
        /// <summary>
        /// 加载机构的全部下级机构
        /// </summary>
        /// <param name="orgId">机构ID</param>
        /// <returns></returns>
        [HttpGet]
        [ApiExplorerSettings(IgnoreApi = true)]
        public TableData GetSubOrgs(long orgId)
        {
            string cascadeId = ".0.";
            if (orgId != 0)
            {
                var org = _authStrategyContext.Orgs.SingleOrDefault(u => u.Id == orgId);
                if (org == null)
                {
                    return new TableData
                    {
                        msg = "未找到指定的节点",
                        code = 500,
                    };
                }
                cascadeId = org.CascadeId;
            }

            var query = _authStrategyContext.Orgs
                .Where(u => u.CascadeId.Contains(cascadeId))
                .OrderBy(u => u.CascadeId);

            return new TableData
            {
                data = query.ToList(),
                count = query.Count(),
            };
        }
        #endregion

        #endregion
    }
}