SysUserService.cs 15 KB
using Hh.Mes.Common;
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Redis;
using Hh.Mes.Common.Request;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.SystemAuth;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Hh.Mes.Service.WebService.Base
{
    /// <summary>
    /// 关联服务(用户角色、角色权限、用户权限、用户部门等等)
    /// </summary>
    public class SysUserService : RepositorySqlSugar<SysUser>
    {
        private IAuth authUtil;
        private SysRelevanceService sysRelevanceService;

        public SysUserService(IAuth authUtil, SysRelevanceService sysRelevanceService) : base()
        {
            this.authUtil = authUtil;
            this.sysRelevanceService = sysRelevanceService;
        }

        /// <summary>
        /// 拼接where条件
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="Name"></param>
        /// <param name="Idcard"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public Expression<Func<SysUser, bool>> LinqWhere(List<int> userIds, string Name, string Idcard)
        {
            try
            {
                var exp = Expressionable.Create<SysUser>();
                exp.And(t => userIds.Contains(t.Id) && t.Account != "System");
                if (!string.IsNullOrWhiteSpace(Name)) exp.And(t => t.Name.Contains(Name));
                if (!string.IsNullOrWhiteSpace(Idcard)) exp.And(t => t.Idcard.Contains(Idcard));
                return exp.ToExpression();//拼接表达式
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        /// <summary>
        /// 加载当前登录用户可访问的一个部门及子部门全部用户
        /// </summary>
        public dynamic Load(PageReq request, int? orgId, string Name, string Idcard)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var loginUser = authUtil.GetCurrentUser();

                //根据部门ID获取分支ID
                string cascadeId = ".0.";
                if (orgId != null)
                {
                    var org = loginUser.Orgs.SingleOrDefault(u => u.Id == orgId.Value);
                    cascadeId = org.CascadeId;
                }
                //根据分支ID找出下属的部门ID
                var ids = loginUser.Orgs.Where(u => u.CascadeId.StartsWith(cascadeId)).Select(u => u.Id).ToArray();
                //根据所有的部门ID,找出对应的用户ID
                var userIds = Context.Queryable<SysRelevance>()
                                     .Where(u => u.RelKey == Define.USERORG && ids.Contains(u.SecondId.Value))
                                     .Select(u => u.FirstId.Value)
                                     .ToList();
                //用户ID去重
                userIds = userIds.Distinct().ToList();
                //找出用户和部门的关联
                var relevances = Context.Queryable<SysRelevance>()
                                        .Where(u => u.RelKey == Define.USERORG && userIds.Contains(u.FirstId.Value))
                                        .ToList();
                var deptIds = relevances.Select(t => t.SecondId).Distinct().ToList();
                //根据用户ID,找出对应的部门ID
                var depts = Context.Queryable<SysDept>().Where(u => deptIds.Contains(u.Id)).ToList();

                //动态拼接表达式
                var expression = LinqWhere(userIds, Name, Idcard);
                var records = 0;
                var users = Context.Queryable<SysUser>()
                                   .Where(expression)
                                   .OrderBy(u => u.Name)
                                   .ToOffsetPage(request.page, request.limit, ref records);              

                var userViews = new List<SysUserView>();
                foreach (var user in users)
                {
                    //查询用户的所有组织ID
                    var userDeptIds = relevances.Where(t => t.FirstId == user.Id).Select(t => t.SecondId).ToList();
                    //根据组织ID查询所有组织信息
                    var orgs = depts.Where(t => userDeptIds.Contains(t.Id)).ToList();

                    SysUserView uv = user;
                    uv.Organizations = string.Join(",", orgs.Select(u => u.Name).ToList());
                    uv.OrganizationIds = string.Join(",", orgs.Select(u => u.Id).ToList());
                    uv.FaceID = user.FaceID;
                    uv.Idcard = user.Idcard;
                    uv.FacePicture = user.FacePicture;
                    uv.PhoneNumber = user.PhoneNumber;
                    uv.PassWord = null;
                    userViews.Add(uv);
                }

                response.Count = records;
                response.Result = userViews;

                return response;
            });
        }

        public dynamic Ins(SysUserView view)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();

                if (string.IsNullOrEmpty(view.OrganizationIds))
                {
                    throw new Exception("请为用户分配机构");
                }
                if (Context.Queryable<SysUser>().Any(u => u.Account == view.Account))
                {
                    throw new Exception("账号已存在");
                }
                if (Context.Queryable<SysUser>().Any(u => u.Name == view.Name))
                {
                    throw new Exception("用户名已存在");
                }
                SysUser user = view;
                user.Password = Encryption.Encrypt(user.Password); //密码加密
                user.CreateBy = sysWebUser?.Account;
                user.CreateTime = DateTime.Now;

                int[] orgIds = Array.ConvertAll(view.OrganizationIds.Split(','), int.Parse);
                //用户和组织的关联
                List<SysRelevance> list = new List<SysRelevance>();
                foreach (var item in orgIds)
                {
                    var sysRelevance = new SysRelevance
                    {
                        RelKey = Define.USERORG,
                        SecondId = item,
                        CreateBy = sysWebUser?.Account,
                        CreateTime = DateTime.Now
                    };
                    list.Add(sysRelevance);
                }
                var result = Context.Ado.UseTran(() =>
                {
                    //插入用户到数据库
                    user.Id = Context.Insertable(user).ExecuteReturnIdentity();
                    //user.Id插入后才会产生,才能赋值
                    list.ForEach(t => t.FirstId = user.Id);
                    //删除用户对应的所有组织
                    Context.Deleteable<SysRelevance>(t => t.FirstId == user.Id && t.RelKey == Define.USERORG).ExecuteCommand();
                    //新增用户对应的所有组织
                    Context.Insertable(list).ExecuteCommand();
                });

                if (result.IsSuccess == false) 
                {
                    return response.ResponseError(result.ErrorMessage);
                }

                //要把保存后的ID存入view
                view.Id = user.Id;
                return response;
            });
        }

        public dynamic Upd(SysUserView view)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();

                if (string.IsNullOrEmpty(view.OrganizationIds))
                {
                    throw new Exception("请为用户分配机构");
                }

                SysUser user = view;
                user.UpdateBy = sysWebUser?.Account;
                user.UpdateTime = DateTime.Now;

                int[] orgIds = Array.ConvertAll(view.OrganizationIds.Split(','), int.Parse);
                //用户和组织的关联
                List<SysRelevance> list = new List<SysRelevance>();
                foreach (var item in orgIds)
                {
                    var sysRelevance = new SysRelevance
                    {
                        RelKey = Define.USERORG,
                        FirstId = user.Id,
                        SecondId = item,
                        CreateBy = sysWebUser?.Account,
                        CreateTime = DateTime.Now
                    };
                    list.Add(sysRelevance);
                }

                var result = Context.Ado.UseTran(() =>
                {
                    //更新用户信息
                    Context.Updateable(user).UpdateColumns(t => new { t.Account, t.Name, t.Sex, t.PhoneNumber, t.Status, t.UpdateBy, t.UpdateTime }).ExecuteCommand();
                    //删除用户对应的所有组织
                    Context.Deleteable<SysRelevance>(t => t.FirstId == user.Id && t.RelKey == Define.USERORG).ExecuteCommand();
                    //新增用户对应的所有组织
                    Context.Insertable(list).ExecuteCommand();
                });

                if (result.IsSuccess == false)
                {
                    return response.ResponseError(result.ErrorMessage);
                }

                //清空用户的redis授权缓存,这样用的时候就会自动从数据库更新一次
                var cl = new RedisBase();
                if (cl.redisClient.Exists(view.Account))
                {
                    cl.redisClient.Del(view.Account);
                }

                return response;
            });
        }

        public dynamic DeleteById(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var relkeyList = new string[] { Define.USERROLE, Define.USERORG, Define.USERELEMENT, Define.USERMODULE };

                //清空被删除用户的Redis缓存
                var userOnlineList = Context.Queryable<sys_user_online>().Where(t => ids.Contains(t.id)).ToList();
                var cl = new RedisBase();
                foreach (var item in userOnlineList)
                {
                    if (cl.redisClient.Exists(item.account))
                    {
                        cl.redisClient.Del(item.account);
                    }
                    if (cl.redisClient.Exists(item.token))
                    {
                        cl.redisClient.Del(item.token);
                    }
                }

                Context.Deleteable<SysRelevance>().Where(t => ids.Contains(t.FirstId.Value) && relkeyList.Contains(t.RelKey)).AddQueue();
                Context.Deleteable<SysUser>().In(ids).AddQueue();

                if (ExecuteQueues(Context) <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }

                return response;
            });
        }

        /// <summary>
        /// 修改个人密码
        /// </summary>
        /// <param name="OldPassword"></param>
        /// <param name="Password"></param>
        /// <param name="CurrentUser"></param>
        /// <exception cref="Exception"></exception>
        public dynamic ChangeUserPassword(string OldPassword, string Password, SysUser CurrentUser)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();

                SysUser user = CurrentUser;

                if (user.Password.Equals(Encryption.Encrypt(OldPassword)))
                {
                    if (OldPassword == Password)
                    {
                        throw new Exception("新密码不应与旧密码相同");
                    }
                    else
                    {
                        user.Password = Encryption.Encrypt(Password);
                        var result = Context.Updateable(user)
                                            .UpdateColumns(t => t.Password)
                                            .ExecuteCommand();
                        if (result <= 0)
                        {
                            return response.ResponseError(SystemVariable.dataActionError);
                        }
                    }
                }
                else
                {
                    throw new Exception("旧密码不正确");
                }

                return response;
            });
        }

        /// <summary>
        /// 重设用户密码
        /// </summary>
        /// <param name="currentUser"></param>
        public dynamic ResetPassword(SysUser currentUser)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                currentUser.Password = ConfigRead.GetInstance.GetAppsetConnection().ResetPwd ;
                if (string.IsNullOrEmpty(currentUser.Password)) return response.ResponseError("配置文件属性【ResetPwd】不存在或者值为空,请核实!");
                var result = Context.Updateable(currentUser)
                                    .UpdateColumns(t => t.Password)
                                    .ExecuteCommand();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                return response;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public SysUser GetByAccount(string account)
        {
            return Context.Queryable<SysUser>().First(t => t.Account == account);
        }

        /// <summary>
        /// 创建绑定登录方式
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string CreateBinding(string user, string userImage, string jobCard)
        {
            return "";
        }


        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadUserListByTeamCode(string teamCode)
        {
            var result = new Response();
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine($@" SELECT t1.*
                                          FROM sys_user t1 
                                          inner join  base_team_user_rel t2 on t1.id=t2.userId
                                          where t2.teamCode=@teamCode ");

            
            var dt = base.Context.Ado.GetDataTable(stringBuilder.ToString(), new List<SugarParameter>(){
                new SugarParameter("@teamCode",teamCode)
            });
            result.Result = dt;
            result.Count = dt.Rows.Count;
            return result;
        }

    }
}