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

namespace YBEE.EQM.Application;

/// <summary>
/// 系统用户服务
/// </summary>
public class SysUserService(IRepository<SysUser> userRep, IOptions<AuthOptions> options) : ISysUserService, ITransient
{
    private readonly AuthOptions _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)))
        if ((await userRep.DetachedEntities.AsQueryable().ToListAsync()).Any(t => t.Id == CurrentSysUserInfo.SysUserId && PBKDF2Encryption.Compare(oldPwd, t.Password)))
        {
            var user = await userRep.FirstOrDefaultAsync(t => t.Id == CurrentSysUserInfo.SysUserId);
            //user.Password = AESEncryption.Encrypt(newPwd, _authOptions.AesPassword);
            user.Password = PBKDF2Encryption.Encrypt(newPwd);
            await user.UpdateIncludeNowAsync(["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;
    }

    ///// <summary>
    ///// 更换密码加密方式
    ///// </summary>
    ///// <returns></returns>
    //public async Task UpdatePassword()
    //{
    //    var items = await userRep.Where(t => t.Id > 1).ToListAsync();
    //    foreach (var item in items)
    //    {
    //        string pwd = AESEncryption.Decrypt(item.Password, _authOptions.AesPassword);
    //        item.Password = PBKDF2Encryption.Encrypt(pwd);
    //        await item.UpdateIncludeAsync(["Password"]);
    //    }
    //}

    #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
}