using Furion.DatabaseAccessor.Extensions;
using Microsoft.Extensions.Options;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 系统用户服务
/// </summary>
public class SysUserService : ISysUserService, ITransient
{
    private readonly IRepository<SysUser> _userRep;
    private readonly AuthOptions _authOptions;

    public SysUserService(IRepository<SysUser> userRep, IOptions<AuthOptions> options)
    {
        _userRep = userRep;
        _authOptions = options.Value;
    }

    /// <summary>
    /// 获取所有用户列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<SysUserLiteOutput>> GetAllList()
    {
        var items = await _userRep.DetachedEntities.Where(u => u.Status == CommonStatus.ENABLE)
                                                    .ProjectToType<SysUserLiteOutput>()
                                                    .ToListAsync();
        return items;
    }
    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task ChangePassword(ChangeSysUserPasswordInput input)
    {
        string oldPwd = RSAEncryption.Decrypt(input.OldPassword, _authOptions.RsaPrivateKey);
        string newPwd = RSAEncryption.Decrypt(input.NewPassword, _authOptions.RsaPrivateKey);
        if (newPwd.Length < 6 || newPwd.Length > 32)
        {
            throw Oops.Oh(ErrorCode.E1006);
        }

        if ((await _userRep.DetachedEntities.AsQueryable().ToListAsync()).Any(t => t.Id == CurrentSysUserInfo.SysUserId && AESEncryption.Decrypt(t.Password, _authOptions.AesPassword).Equals(oldPwd)))
        {
            var user = await _userRep.FirstOrDefaultAsync(t => t.Id == CurrentSysUserInfo.SysUserId);
            user.Password = AESEncryption.Encrypt(newPwd, _authOptions.AesPassword);
            await user.UpdateIncludeNowAsync(new[] { "Password" });
        }
        else
        {
            throw Oops.Oh(ErrorCode.E1005);
        }
    }
    /// <summary>
    /// 查询简要用户列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<PageResult<SysUserSimpleOutput>> QueryUserSimplePageList(SysUserPageInput input)
    {
        var query = GetQueryBase(input);
        var ret = await query.OrderBy(t => t.Name).ProjectToType<SysUserSimpleOutput>().ToADPagedListAsync(input.PageIndex, input.PageSize);
        return ret;
    }

    #region 私有方法
    private IQueryable<SysUser> GetQueryBase(SysUserPageInput input)
    {
        var name = !string.IsNullOrEmpty(input.Name?.Trim());
        var mobile = !string.IsNullOrEmpty(input.Mobile?.Trim());
        var account = !string.IsNullOrEmpty(input.Account?.Trim());
        var email = !string.IsNullOrEmpty(input.Email?.Trim());
        var searchValue = !string.IsNullOrEmpty(input.SearchValue?.Trim());

        var query = _userRep.DetachedEntities.Where(t => t.IsDeleted == false)
                                             .Where((searchValue, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%") || EF.Functions.Like(u.Account, $"%{input.SearchValue.Trim()}%")))
                                             .Where(name, u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%"))
                                             .Where(mobile, u => EF.Functions.Like(u.Mobile, $"%{input.Mobile.Trim()}%"))
                                             .Where(account, u => EF.Functions.Like(u.Account, $"%{input.Account.Trim()}%"))
                                             .Where(email, u => EF.Functions.Like(u.Email, $"%{input.Email.Trim()}%"))
                                             .Where(input.SysOrgId.HasValue, t => t.SysOrgId == input.SysOrgId);
        return query;
    }
    #endregion
}