SysDeptService.cs 8.61 KB
using Hh.Mes.Common.log;
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.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Hh.Mes.Service.WebService.Base
{
    public class SysDeptService : RepositorySqlSugar<SysDept>
    {
        public SysDeptService(IAuth auth, IDistributedCache cache) : base(auth, cache)
        {

        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="sysDept">部门实体</param>
        /// <returns>部门ID</returns>
        /// <exception cref="System.Exception">未能找到该组织的父节点信息</exception>
        public dynamic Ins(SysDept sysDept)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response<int>();
                //填充分支ID、父节点名称
                ChangeModuleCascade(sysDept);
                sysDept.CreateBy = sysWebUser?.Account;
                sysDept.CreateTime = DateTime.Now;
                //新增操作
                var row = Context.Insertable(sysDept).ExecuteCommand();
                if (row <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }

                ClearOnlineUserRedis();

                response.Result = sysDept.Id;
                return response;
            });
        }

        public dynamic Upd(SysDept sysDept)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                ChangeModuleCascade(sysDept);

                //获取旧的的CascadeId
                var cascadeId = Context.Queryable<SysDept>().First(o => o.Id == sysDept.Id).CascadeId;
                //根据CascadeId查询子部门
                var sysDeptList = Context.Queryable<SysDept>()
                                         .Where(u => u.CascadeId.StartsWith(cascadeId) && u.Id != sysDept.Id)
                                         .OrderBy(u => u.CascadeId)
                                         .ToList();
                //更新操作
                Context.Updateable(sysDept).AddQueue();

                //更新子部门的CascadeId
                foreach (var item in sysDeptList)
                {
                    ChangeModuleCascade(item);
                    //更新操作
                    Context.Insertable(sysDept).AddQueue();
                }
                if (ExecuteQueues(Context) <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearOnlineUserRedis();
                response.Result = sysDept.Id;
                return response;
            });
        }

        /// <summary>
        /// 删除指定ID的部门及其所有子部门
        /// </summary>
        public dynamic DelByIds(int[] ids)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                if (ids.Length == 0)
                {
                    return response.ResponseError("请选择部门!");
                }
                string[] relkeyList = new string[] { Define.ROLEORG, Define.USERORG };
                var exist = Context.Queryable<SysRelevance>().Any(t => relkeyList.Contains(t.RelKey) && ids.Contains(t.SecondId.Value));
                if (exist)
                {
                    return response.ResponseError("部门还有角色或是人员,不能删除,请先删除部门的角色和人员!");
                }
                var cascadeIds = Context.Queryable<SysDept>().Where(t => ids.Contains(t.Id)).Select(t => t.CascadeId).ToList();
                foreach (var cascadeId in cascadeIds)
                {
                    Context.Deleteable<SysDept>().Where(t => t.CascadeId.StartsWith(cascadeId)).AddQueue();
                }
                if (ExecuteQueues(Context) <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearOnlineUserRedis();
                return response;
            });
        }

        /// <summary>
        /// 加载特定用户的角色
        /// TODO:这里会加载用户及用户角色的所有角色,“为用户分配角色”功能会给人一种混乱的感觉,但可以接受
        /// </summary>
        /// <param name="userId">The user unique identifier.</param>
        public dynamic LoadForUser(int userId)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                //用户角色
                var userRoleIds = Context.Queryable<sys_relevance>()
                                         .Where(u => u.firstId == userId && u.relKey == Define.USERROLE)
                                         .Select(u => u.secondId)
                                         .ToList();

                //用户角色与自己分配到的角色ID
                var moduleIds = Context.Queryable<sys_relevance>()
                                       .Where(t => t.firstId == userId && t.relKey == Define.USERORG ||
                                                    t.relKey == Define.ROLEORG && userRoleIds.Contains(t.firstId))
                                       .Select(t => t.secondId).ToList();

                if (moduleIds.Count == 0) return new List<SysDept>();
                var SysDeptList = Context.Queryable<SysDept>().Where(t => moduleIds.Contains(t.Id)).ToList();

                response.Result = SysDeptList;
                response.Count = SysDeptList.Count;
                return SysDeptList;
            });
        }

        /// <summary>
        /// 加载特定角色的角色
        /// </summary>
        /// <param name="roleId">角色ID</param>
        public dynamic LoadForRole(int roleId)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var moduleIds = Context.Queryable<sys_relevance>()
                                       .Where(t => t.firstId == roleId && t.relKey == Define.ROLEORG)
                                       .Select(t => t.secondId)
                                       .ToList();
                if (moduleIds.Count == 0)
                {
                    return new List<SysDept>();
                }
                var SysDeptList = Context.Queryable<SysDept>().Where(t => moduleIds.Contains(t.Id)).ToList();

                response.Result = SysDeptList;
                response.Count = SysDeptList.Count;
                return SysDeptList;
            });
        }


        /// <summary>
        /// 填充部门实体的节点(生成类似XXX.XXX.X.XX)、父节点名
        /// </summary>
        /// <param name="sysDept">部门</param>
        public void ChangeModuleCascade(SysDept sysDept)
        {
            int currentCascadeId = 1;
            //当前结点的级联节点最后一位,也就是平级的所有部门
            var query = Context.Queryable<SysDept>().Where(t => t.Id != sysDept.Id);
            //因为这里个SqlSugar的bug,如果传入的参数为null,那么生成的sql不是 xx is null 而是xx = '',所以要这么写
            if (sysDept.ParentId == null)
            {
                query.Where(t => t.ParentId == null);
            }
            else
            {
                query.Where(t => t.ParentId == sysDept.ParentId);
            }
            var sameLevels = query.ToList();
            foreach (var obj in sameLevels)
            {
                int objCascadeId = int.Parse(obj.CascadeId.TrimEnd('.').Split('.').Last());
                if (currentCascadeId <= objCascadeId) currentCascadeId = objCascadeId + 1;
            }

            if (sysDept.ParentId != null)
            {
                var parentOrg = Context.Queryable<SysDept>().First(t => t.Id == sysDept.ParentId);
                if (parentOrg != null)
                {
                    sysDept.CascadeId = parentOrg.CascadeId + currentCascadeId + ".";
                    sysDept.ParentName = parentOrg.Name;
                }
                else
                {
                    throw new Exception("未能找到该组织的父节点信息");
                }
            }
            else
            {
                sysDept.CascadeId = ".0." + currentCascadeId + ".";
                sysDept.ParentName = "根节点";
            }
        }

    }
}