using BPA.SAAS.Manage.Application.Auth.Dtos;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Org;
using Mapster;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.Auth
{
    public class AuthService : IAuthService, IDynamicApiController
    {
        private readonly ISqlSugarClient _db;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public AuthService(ISqlSugarClient db, IHttpContextAccessor httpContextAccessor)
        {
            _db = db;
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 用户名密码登录
        /// </summary>
        /// <param name="LoginType">1平台用户登录,0加盟商登录</param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/auth/login")]
        [AllowAnonymous]
        public async Task<LoginOutInfo> Login(LoginInput input)
        {

            // 获取加密后的密码
            var encryptPasswod = MD5Encryption.Encrypt(input.Password).ToLower();
            // 判断用户名和密码是否正确 忽略全局过滤器
            var user = await _db.Queryable<BPA_Users>().Where(u => u.Account.Equals(input.Account)
            && u.Password.Equals(encryptPasswod)
            && u.IsDeleted == 0
           ).FirstAsync();
            _ = user ?? throw Oops.Oh("用户名或密码不正确");
            //获取权限
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "Id", ConditionalType = ConditionalType.Equal, FieldValue = user.GroupId });
            conModels.Add(new ConditionalModel() { FieldName = "Status", ConditionalType = ConditionalType.Equal, FieldValue = CommonStatus.ENABLE.ToString() });
            conModels.Add(new ConditionalModel() { FieldName = "IsDeleted", ConditionalType = ConditionalType.Equal, FieldValue ="0" });
            //if (user.AdminType != 1)
            //{
            //    conModels.Add(new ConditionalModel() { FieldName = "Type", ConditionalType = ConditionalType.Equal, FieldValue = input.Type.ToString() });
            //}
            var company = _db.Queryable<BPA_Company>().Where(conModels).First();
          
            string CLAINM_SUPERADMIN = "Customer";
            if (user.AdminType == 1)
            {
                CLAINM_SUPERADMIN = "1";
            }
            _ = company ?? throw Oops.Oh("企业被锁定,请联系管理员");
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
            {
                { ClaimConst.CLAINM_USERID, user.Id },
                { ClaimConst.LoginType, 0},
                { ClaimConst.CLAINM_ACCOUNT,  user.Account },
                { ClaimConst.CLAINM_NAME,  user.Name },
                { ClaimConst.CLAINM_SUPERADMIN, CLAINM_SUPERADMIN },
                { ClaimConst.GroupId,  user.GroupId},
                { ClaimConst.OrgId,user.SysOrgId},
                //{ ClaimConst.SupplyPlatformId,company?.SupplyPlatformId}
            }, 1440);

            // 设置Swagger自动登录
            // _httpContextAccessor.SigninToSwagger(accessToken);

            // 生成刷新Token令牌
            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 1445);

            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
            // 设置刷新Token令牌
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;
            LoginOutInfo loginOutInfo = new LoginOutInfo()
            {
                userID = user.Id,
                token = accessToken
            };
            return loginOutInfo;

        }
        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/auth/getLoginUser")]
        [AllowAnonymous]
        public async Task<LoginOutput> GetLoginUserAsync()
        {
            string userid = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var user = await _db.Queryable<BPA_Users>().Where(u => u.Id == userid).FirstAsync();
            if (user != null)
            {
                var reslut = user.Adapt<LoginOutput>();
                return reslut;
            }
            else
            {
                throw Oops.Oh($"用户不存在");
            }

        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/auth/logout")]
        public async Task LogoutAsync()
        {
            // _httpContextAccessor.SignoutToSwagger();
            await Task.CompletedTask;
        }


        #region 添加平台授权

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/authorization/pageauthorization")]
        public async Task<PageUtil> PageAuthorization(PageInputBase input)
        {
            RefAsync<int> total = 0;
            var res = await _db.Queryable<BPA_PlatformAuthorization>()
                .OrderBy(x => x.CreateAt, OrderByType.Desc)
                .Select(x => new PlatformAuthorizationDto()
                {
                    Id = x.Id.SelectAll(),
                })
                .ToPageListAsync(input.Current, input.PageSize, total);
            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = res
            };
            return util;
        }

        /// <summary>
        /// 添加授权码
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/authorization/addauthorization")]
        public async Task<bool> AddAuthorization(CreateOrUpDatePlatformAuthorizationDto input)
        {
            var data = _db.Queryable<BPA_PlatformAuthorization>().ToList();
            if (data.Count > 0)
            {
                throw Oops.Oh("授权码已存在");
            }

            var res = await _db.Insertable(new BPA_PlatformAuthorization()
            {
                Key = Guid.NewGuid().ToString(),
                PeriodValidity = input.PeriodValidity,
                UpdateAt=DateTime.Now,

            }).CallEntityMethod(t => t.Create()).ExecuteCommandAsync();

            return res > 0;
        }

        /// <summary>
        /// 修改授权码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("/api/authorization/updateauthorization")]
        public async Task<bool> UpdateAuthorization(string id)
        {
            var data = await _db.Queryable<BPA_PlatformAuthorization>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }
            data.Key = Guid.NewGuid().ToString();
            data.UpdateAt = DateTime.Now;
            //data.PeriodValidity = input.PeriodValidity;

            return await _db.Updateable(data).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 修改授权码授权时间
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("/api/authorization/updateauthtime")]
        public async Task<bool> UpdateAuthTime(CreateOrUpDatePlatformAuthorizationDto input)
        {
            var data = await _db.Queryable<BPA_PlatformAuthorization>().FirstAsync(x => x.Id == input.Id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }
            data.PeriodValidity = input.PeriodValidity;
            data.UpdateAt = DateTime.Now;

            return await _db.Updateable(data).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 删除授权码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("/api/authorization/delauthorization")]
        public async Task<bool> DelAuthorization(string id)
        {
            var data = await _db.Queryable<BPA_PlatformAuthorization>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                throw Oops.Oh("授权信息不存在");
            }

            return await _db.Deleteable(data).ExecuteCommandHasChangeAsync();
        }


        /// <summary>
        /// 获取加盟商信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("/api/authorization/GetCompanyByIdNew")]
        [AllowAnonymous]
        public async Task<BPA_Company> GetCompanyById(string id)
        {
            var data = await _db.Queryable<BPA_Company>().FirstAsync(x => x.Id == id);

            return data;
        }

        #endregion
    }
}
