using System;
using Infrastructure;
using Infrastructure.Cache;
using Infrastructure.Helpers;
using Infrastructure.Utilities;
using Microsoft.Extensions.Configuration;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.SSO
{
    public class LoginParse
    {
        //这个地方使用IRepository<User> 而不使用UserManagerApp是防止循环依赖
        public ISimpleClient<SysUser> _app;
        private ICacheContext _cacheContext;
        private IConfiguration configuration;


        public LoginParse(ICacheContext cacheContext, ISimpleClient<SysUser> userApp, IConfiguration configuration)
        {
            _cacheContext = cacheContext;
            _app = userApp;
            this.configuration = configuration;
        }

        public Response<LoginResult> Do(PassportLoginRequest model)
        {
            var result = new Response<LoginResult>();
            try
            {
                model.Trim();
                //todo:如果需要判定应用，可以取消该注释
                // var appInfo = _appInfoService.GetByAppKey(model.AppKey);
                // if (appInfo == null)
                // {
                //     throw  new Exception("应用不存在");
                // }
                //获取用户信息
                SysUser userInfo = null;
                if (model.Account == Define.SYSTEM_USERNAME)
                {
                    userInfo = new SysUser
                    {
                        Id = -1,
                        Account = Define.SYSTEM_USERNAME,
                        Name = "超级管理员",
                        Password = Md5Helper.Encrypt(DESEncrypt.Encrypt(Md5Helper.Hash(configuration.GetSection("AppSetting:SYSTEM_USERPWD").Value), Define.SYSTEM_SECRETKEY).ToLower(), 32).ToLower(),
                        //Password = Define.SYSTEM_USERPWD,
                        Secretkey = Define.SYSTEM_SECRETKEY
                    };
                }
                else
                {
                    userInfo = _app.GetFirst(u => u.Account == model.Account);
                }

                if (userInfo == null)
                {
                    throw new Exception("用户不存在");
                }

                string dbPwd = Md5Helper.Encrypt(DESEncrypt.Encrypt(model.Password, userInfo.Secretkey).ToLower(), 32).ToLower();
                if (userInfo.Password != dbPwd)
                {
                    throw new Exception("密码错误");
                }

                if (userInfo.Status != 0)
                {
                    throw new Exception("账号状态异常，可能已停用");
                }

                var currentSession = new UserAuthSession
                {
                    UserId = userInfo.Id.ToString(),
                    Account = model.Account,
                    Name = userInfo.Name,
                    Token = Guid.NewGuid().ToString().GetHashCode().ToString("x"),
                    AppKey = model.AppKey,
                    CreateTime = DateTime.Now
                    //    , IpAddress = HttpContext.Current.Request.UserHostAddress
                };

                //创建Session
                _cacheContext.Set(currentSession.Token, currentSession, DateTime.Now.AddDays(10));

                result.Code = 200;
                result.Result = new LoginResult
                {
                    Token = currentSession.Token
                };

            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }
    }
}