SysRoleService.cs 10.7 KB
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 Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;


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

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

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

                string cascadeId = ".0.";
                if (orgId != null)
                {
                    var org = loginUser.Orgs.SingleOrDefault(u => u.Id == orgId);
                    cascadeId = org.CascadeId;
                }
                //获取部门、下属的多级子部门ID
                var ids = loginUser.Orgs.Where(t => t.CascadeId.StartsWith(cascadeId)).Select(t => t.Id).ToList();
                //根据多级部门ID找到对应的多个角色ID
                var roleIds = Context.Queryable<sys_relevance>()
                                     .Where(u => u.relKey == Define.ROLEORG && ids.Contains(u.secondId.Value))
                                     .Select(u => u.firstId.Value)
                                     .ToList();
                //角色ID去重
                roleIds = roleIds.Distinct().ToList();
                //找出角色和部门的关联
                var relevances = Context.Queryable<SysRelevance>()
                                        .Where(u => u.RelKey == Define.ROLEORG && roleIds.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();
                //根据角色ID找到多个角色
                int count = 0;
                var roles = Context.Queryable<SysRole>()
                                   .Where(t => roleIds.Contains(t.Id))
                                   .OrderBy(t => t.Name)
                                   .ToOffsetPage(pageRequest.page, pageRequest.limit, ref count);

                var roleViews = new List<SysRoleView>();
                foreach (var role in roles)
                {
                    //查询角色的所有组织ID
                    var roleDeptIds = relevances.Where(t => t.FirstId == role.Id).Select(t => t.SecondId).ToList();
                    //根据组织ID查询所有组织信息
                    var orgs = depts.Where(t => roleDeptIds.Contains(t.Id)).ToList();

                    SysRoleView uv = role;
                    uv.Organizations = string.Join(",", orgs.Select(u => u.Name).ToList());
                    uv.OrganizationIds = string.Join(",", orgs.Select(u => u.Id).ToList());
                    roleViews.Add(uv);
                }

                response.Count = count;
                response.Result = roleViews;

                return response;
            });
        }

        public dynamic Ins(SysRoleView obj)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                if (string.IsNullOrEmpty(obj.OrganizationIds))
                {
                    throw new Exception("请为角色分配机构");
                }
                if (Context.Queryable<SysRole>().Any(u => u.Name == obj.Name))
                {
                    throw new Exception("角色已存在");
                }
                SysRole role = obj;
                role.CreateBy = sysWebUser?.Account;
                role.CreateTime = DateTime.Now;

                int[] orgIds = Array.ConvertAll(obj.OrganizationIds.Split(','), int.Parse);

                //角色和组织的关联
                List<SysRelevance> list = new List<SysRelevance>();
                foreach (var item in orgIds)
                {
                    var sysRelevance = new SysRelevance
                    {
                        RelKey = Define.ROLEORG,
                        SecondId = item,
                        CreateBy = sysWebUser?.Account,
                        CreateTime = DateTime.Now
                    };
                    list.Add(sysRelevance);
                }

                //在事务中处理
                var result = Context.Ado.UseTran(() =>
                {
                    //插入角色到数据库
                    role.Id = Context.Insertable(role).ExecuteReturnIdentity();
                    //role.Id插入后才会产生,才能赋值
                    list.ForEach(t => t.FirstId = role.Id);
                    //删除角色对应的所有组织
                    Context.Deleteable<SysRelevance>(t => t.FirstId == role.Id && t.RelKey == Define.ROLEORG).ExecuteCommand();
                    //新增角色对应的所有组织
                    Context.Insertable(list).ExecuteCommand();
                });

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

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public dynamic Upd(SysRoleView obj)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                if (string.IsNullOrEmpty(obj.OrganizationIds))
                {
                    throw new Exception("请为角色分配机构");
                }

                SysRole role = obj;
                role.UpdateBy = sysWebUser?.Account;
                role.UpdateTime = DateTime.Now;

                ClearRedis(new int[] { role.Id });

                int[] orgIds = Array.ConvertAll(obj.OrganizationIds.Split(','), int.Parse);
                //角色和组织的关联
                List<SysRelevance> list = new List<SysRelevance>();
                foreach (var item in orgIds)
                {
                    var sysRelevance = new SysRelevance
                    {
                        RelKey = Define.ROLEORG,
                        FirstId = role.Id,
                        SecondId = item,
                        CreateBy = sysWebUser?.Account,
                        CreateTime = DateTime.Now
                    };
                    list.Add(sysRelevance);
                }
                //在事务中处理
                var result = Context.Ado.UseTran(() =>
                {
                    //更新角色信息
                    Context.Updateable(role).UpdateColumns(t => new { t.Name, t.UpdateBy, t.Status, t.UpdateTime }).ExecuteCommand();
                    //删除角色对应的所有组织
                    Context.Deleteable<SysRelevance>(t => t.FirstId == role.Id && t.RelKey == Define.ROLEORG).ExecuteCommand();
                    //新增角色对应的所有组织
                    Context.Insertable(list).ExecuteCommand();
                });

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

                return response;
            });
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids">角色删除id</param>
        /// <returns></returns>
        [HttpPost]
        public dynamic DelById(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                if (ids.Length == 0)
                {
                    return response.ResponseError("请选择角色!");
                }
                ClearRedis(ids);
                //删除角色组织
                Context.Deleteable<SysRelevance>(t => t.RelKey == Define.ROLEORG && ids.Contains(t.FirstId.Value)).AddQueue();
                //删除角色模块
                Context.Deleteable<SysRelevance>(t => t.RelKey == Define.ROLEMODULE && ids.Contains(t.FirstId.Value)).AddQueue();
                //删除角色菜单
                Context.Deleteable<SysRelevance>(t => t.RelKey == Define.ROLEELEMENT && ids.Contains(t.FirstId.Value)).AddQueue();
                //删除用户角色
                Context.Deleteable<SysRelevance>(t => t.RelKey == Define.USERROLE && ids.Contains(t.SecondId.Value)).AddQueue();
                //删除角色
                Context.Deleteable<SysRole>(t => ids.Contains(t.Id)).AddQueue();

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

        /// <summary>
        /// 清除角色对应的用户的授权redis缓存
        /// </summary>
        /// <param name="roleIds">角色id数组</param>
        private void ClearRedis(int[] roleIds)
        {
            //根据角色找到对应的用户id
            var userIdList = Context.Queryable<SysRelevance>()
                                     .Where(t => t.RelKey == Define.USERROLE && roleIds.Contains(t.SecondId.Value))
                                     .Select(t => t.FirstId).ToList();
            if (userIdList.Count > 0)
            {
                //根据用户id找到用户账号
                var accountList = Context.Queryable<SysUser>()
                                         .Where(t => userIdList.Contains(t.Id))
                                         .Select(t => t.Account).ToList();
                var cl = new RedisBase();
                foreach (var item in accountList)
                {
                    if (cl.redisClient.Exists(item))
                    {
                        cl.redisClient.Del(item);
                    }
                }
            }
        }


    }
}