using Attribute;
using Base;
using Common;
using Dto;
using Extensions;
using Feign;
using Infrastructure;
using IPTools.Core;
using Model;
using Model.Base;
using Repository;
using Service;
using System.Collections;
using Vo;
namespace Services
{
///
/// 系统用户
///
[AppService(ServiceType = typeof(ISysUserService), ServiceLifetime = LifeTime.Transient)]
public class SysUserService : BaseService, ISysUserService
{
private readonly ISysRoleService RoleService;
private readonly ISysPostService PostService;
private readonly ISysUserRoleService UserRoleService;
private readonly ISysUserPostService UserPostService;
public SysUserService(
ISysRoleService sysRoleService,
ISysPostService sysPostService,
ISysUserRoleService userRoleService,
ISysUserPostService userPostService)
{
RoleService = sysRoleService;
PostService = sysPostService;
UserRoleService = userRoleService;
UserPostService = userPostService;
}
///
/// 根据条件分页查询用户列表
///
///
public PagedInfo SelectUserList(SysUserQueryDto user, PagerInfo pager)
{
var exp = Expressionable.Create();
exp.AndIF(!string.IsNullOrEmpty(user.username), u => u.username.Contains(user.username));
exp.AndIF(!string.IsNullOrEmpty(value: user.nickname), u => u.username.Contains(user.nickname));
exp.AndIF(!string.IsNullOrEmpty(user.name), u => u.username.Contains(user.name));
exp.AndIF(!string.IsNullOrEmpty(user.phone), u => u.username.Contains(user.phone));
exp.And(u => u.DelFlag == "0");
var query = Queryable()
.Where(exp.ToExpression())
.OrderByDescending(m => m.userId);
PagedInfo result = query.ToPage(pager);
foreach(SysUser sub in result.Records)
{
List userRoles = UserRoleService.GetList(m => m.UserId == sub.userId).Select(m => m.RoleId).ToList();
sub.RoleList = RoleService.GetList(m => userRoles.Contains(m.roleId));
List userPost = UserPostService.GetList(m => m.UserId == sub.userId).Select(m => m.PostId).ToList();
sub.PostList = PostService.GetList(m => userPost.Contains(m.postId));
}
return result;
}
///
/// 通过用户ID查询用户
///
///
///
public SysUser SelectUserById(long userId)
{
var user = Queryable().Filter(null, true).WithCache(60 * 5)
.Where(f => f.userId == userId).First();
// if (user != null && user.UserId > 0)
// {
// user.Roles = RoleService.SelectUserRoleListByUserId(userId);
// user.RoleIds = user.Roles.Select(x => x.RoleId).ToArray();
// }
return user;
}
///
/// 校验用户名称是否唯一
///
///
///
public string CheckUserNameUnique(string userName)
{
int count = Count(it => it.username == userName);
if (count > 0)
{
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}
///
/// 新增保存用户信息
///
///
///
public SysUser InsertUser(SysUser sysUser)
{
sysUser.CreateTime = DateTime.Now;
sysUser.UpdateTime = DateTime.Now;
var result = UseTran(() =>
{
sysUser.userId = Insertable(sysUser).ExecuteReturnIdentity();
//新增用户角色信息
UserRoleService.InsertUserRole(sysUser);
//新增用户岗位信息
UserPostService.InsertUserPost(sysUser);
});
if (!result.IsSuccess)
{
throw new Exception("提交数据异常," + result.ErrorMessage, result.ErrorException);
}
return sysUser;
}
///
/// 修改用户信息
///
///
///
public int UpdateUser(SysUser user)
{
var roleIds = RoleService.SelectUserRoles(user.userId);
var diffArr = roleIds.Where(c => !((IList)user.RoleIds).Contains(c)).ToArray();
var diffArr2 = user.RoleIds.Where(c => !((IList)roleIds).Contains(c)).ToArray();
bool result = UseTran2(() =>
{
if (diffArr.Length > 0 || diffArr2.Length > 0)
{
//删除用户与角色关联
UserRoleService.DeleteUserRoleByUserId((int)user.userId);
//新增用户与角色关联
UserRoleService.InsertUserRole(user);
}
// 删除用户与岗位关联
UserPostService.Delete(user.userId);
// 新增用户与岗位管理
UserPostService.InsertUserPost(user);
ChangeUser(user);
});
return result ? 1 : 0;
}
public int ChangeUser(SysUser user)
{
user.UpdateTime = DateTime.Now;
return Update(user, true);
}
///
/// 重置密码
///
///
///
///
public int ResetPwd(long userid, string password)
{
return Update(new SysUser() { userId = userid, password = password }, it => new { it.password }, f => f.userId == userid);
}
///
/// 修改用户状态
///
///
///
public int ChangeUserStatus(SysUser user)
{
CheckUserAllowed(user);
return Update(user, it => new { it.DelFlag }, f => f.userId == user.userId);
}
///
/// 删除用户
///
///
///
public int DeleteUser(long userid)
{
CheckUserAllowed(new SysUser() { userId = userid });
//删除用户与角色关联
UserRoleService.DeleteUserRoleByUserId((int)userid);
// 删除用户与岗位关联
UserPostService.Delete(userid);
return Update(new SysUser() { userId = userid, DelFlag = "2" }, it => new { it.DelFlag }, f => f.userId == userid);
}
///
/// 修改用户头像
///
///
///
public int UpdatePhoto(SysUser user)
{
return Update(user, it => new { it.avatar }, f => f.userId == user.userId); ;
}
///
/// 注册用户
///
///
///
public SysUser Register(RegisterDto dto)
{
if (!Tools.PasswordStrength(dto.Password))
{
throw new CustomException("密码强度不符合要求");
}
if (!Tools.CheckUserName(dto.Username))
{
throw new CustomException("用户名不符合要求");
}
//密码md5
string password = Function.MD532(dto.Password);
var ip_info = IpTool.Search(dto.UserIP);
SysUser user = new()
{
CreateTime = DateTime.Now,
username = dto.Username,
nickname = dto.Username,
password = password,
deptId = 0,
};
if (UserConstants.NOT_UNIQUE.Equals(CheckUserNameUnique(dto.Username)))
{
throw new CustomException($"保存用户{dto.Username}失败,注册账号已存在");
}
user.userId = Insertable(user).ExecuteReturnIdentity();
return user;
}
///
/// 校验角色是否允许操作
///
///
public void CheckUserAllowed(SysUser user)
{
if (user.IsAdmin())
{
throw new CustomException("不允许操作超级管理员角色");
}
}
///
/// 校验用户是否有数据权限
///
///
///
public void CheckUserDataScope(long userid, long loginUserId)
{
if (!SysUser.IsAdmin(loginUserId))
{
SysUser user = new SysUser() { userId = userid };
//TODO 判断用户是否有数据权限
}
}
///
/// 导入数据
///
///
///
public (string, object, object) ImportUsers(List users)
{
users.ForEach(x =>
{
x.CreateTime = DateTime.Now;
x.DelFlag = "0";
x.password = "E10ADC3949BA59ABBE56E057F20F883E";
});
var x = Context.Storageable(users)
.SplitInsert(it => !it.Any())
.SplitIgnore(it => it.Item.username == GlobalConstant.AdminRole)
.SplitError(x => x.Item.username.IsEmpty(), "用户名不能为空")
.SplitError(x => !Tools.CheckUserName(x.Item.username), "用户名不符合规范")
.WhereColumns(it => it.username)//如果不是主键可以这样实现(多字段it=>new{it.x1,it.x2})
.ToStorage();
var result = x.AsInsertable.ExecuteCommand();//插入可插入部分;
string msg = string.Format(" 插入{0} 更新{1} 错误数据{2} 不计算数据{3} 删除数据{4} 总共{5}",
x.InsertList.Count,
x.UpdateList.Count,
x.ErrorList.Count,
x.IgnoreList.Count,
x.DeleteList.Count,
x.TotalList.Count);
//输出统计
Console.WriteLine(msg);
//输出错误信息
foreach (var item in x.ErrorList)
{
Console.WriteLine("userName为" + item.Item.username + " : " + item.StorageMessage);
}
foreach (var item in x.IgnoreList)
{
Console.WriteLine("userName为" + item.Item.username + " : " + item.StorageMessage);
}
return (msg, x.ErrorList, x.IgnoreList);
}
///
/// 登录
///
/// 登录实体
///
public SysUser Login(LoginBodyDto user)
{
return GetFirst(it => it.username == user.username && it.password.ToLower() == user.password.ToLower());
}
///
/// 修改登录信息
///
///
///
///
public void UpdateLoginInfo(string userIP, long userId)
{
}
public PagedInfo TestList(SysDeptFeign SysDept)
{
//开始拼装查询条件
var predicate = Expressionable.Create();
var response = Queryable()
.Where(predicate.ToExpression())
.OrderByDescending(m => m.userId)
.Includes(m => m.deptJoin)
// .CrossQuery(typeof(Users), "tel")
// .Includes(m => m.user)
.ToPage(new PagerInfo());
return response;
}
}
}