SysModuleService.cs 20.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
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.POJO.ViewModel;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.SystemAuth;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Hh.Mes.Service.WebService.Base
{
    /// <summary>
    /// 模块服务
    /// </summary>
    public class SysModuleService : RepositorySqlSugar<SysModule>
    {
        public readonly List<CheckBoxItem> DefaultBtns;
        public SysModuleService(IAuth auth) : base(auth)
        {
            DefaultBtns = new List<CheckBoxItem>
            {
                new CheckBoxItem
                {
                    Text="新增",
                    Value="btnAdd",
                    BtnClass="layui-btn-mini",
                    Icon="&#xe654;",
                    Sort=10
                },
                new CheckBoxItem
                {
                    Text="复制新增",
                    Value="btnCopyAdd",
                    BtnClass="layui-btn-mini",
                    Icon="&#xe630;",
                    Sort=20
                },
                new CheckBoxItem
                {
                    Text="编辑",
                    Value="btnEdit",
                    BtnClass="layui-btn-warm",
                    Icon="&#xe642;",
                    Sort=30
                },
                new CheckBoxItem
                {
                    Text="删除",
                    Value="btnDelete",
                    BtnClass="layui-btn-danger",
                    Icon="&#xe640;",
                    Sort =40
                },
                new CheckBoxItem
                {
                    Text="打印",
                    Value="btnPrint",
                    BtnClass="layui-btn-mini",
                    Icon="&#xe66d;",
                    Sort=50
                },
                new CheckBoxItem
                {
                    Text="导出",
                    Value="btnExport",
                    BtnClass="layui-btn-mini",
                    Icon="&#xe601;",
                    Sort=60
                },
                new CheckBoxItem
                {
                    Text="上传附件",
                    Value="btnUpload",
                    BtnClass="layui-btn-primary",
                    Icon="&#xe681;",
                    Sort=70
                },
            };
        }
        #region 模块操作

        /// <summary>
        /// 增加一个模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic Ins(SysModule model, string user = "")
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response<SysModule>();
                //填充分支ID、父节点名称
                ChangeModuleCascade(model);
                //处理模块标识,判断不能为空,不能重复
                string msg = HandleModuleCode(model);
                if (msg != "")
                {
                    return response.ResponseError(msg);
                }
                var result = Context.Insertable(model).ExecuteReturnIdentity();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }

                if (!string.IsNullOrWhiteSpace(user))
                {
                    ClearCurrentUserRedis(user);
                }

                model.Id = result;
                response.Result = model;
                response.Message = "业务数据操作成功,请刷新首页或者退出登入后再登入!";
                return response;
            });
        }

        /// <summary>
        /// 修改一个模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic Upd(SysModule model)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                //填充分支ID、父节点名称
                ChangeModuleCascade(model, "update");
                //处理模块标识,判断不能为空,不能重复
                string msg = HandleModuleCode(model,false);
                if (msg != "")
                {
                    response.Message = msg;
                    return response;
                }
                var result = Context.Updateable(model).ExecuteCommand();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearOnlineUserRedis();
                response.Result = model;
                response.Message = "业务数据操作成功,请刷新首页或者退出登入后再登入!";
                return response;
            });
        }

        /// <summary>
        /// 删除多个模块
        /// </summary>
        /// <param name="ids"></param>
        public dynamic DelById(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                List<int> moduleIdList = new List<int>();
                //因为可能选中的是父级的模块,那么删除的时候,就要把子模块全部删除,所以要找出所有子模块
                var cascadeIds = Context.Queryable<SysModule>().Where(t => ids.Contains(t.Id)).Select(t => t.CascadeId).ToList();
                foreach (var cascadeId in cascadeIds)
                {
                    var tempModuleIds = Context.Queryable<SysModule>().Where(t => t.CascadeId.StartsWith(cascadeId)).Select(t => t.Id).ToList();
                    moduleIdList.AddRange(tempModuleIds);
                }
                moduleIdList = moduleIdList.Distinct().ToList();

                //删除菜单
                Context.Deleteable<SysModuleElement>(t => moduleIdList.Contains(t.ModuleId.Value)).AddQueue();
                //删除模块
                Context.Deleteable<SysModule>(t => moduleIdList.Contains(t.Id)).AddQueue();
                if (ExecuteQueues(Context) <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearOnlineUserRedis();
                response.Message = "业务数据操作成功,请刷新首页或者退出登入后再登入!";
                return response;
            });
        }
        #endregion

        #region 菜单操作

        /// <summary>
        /// 增加一个菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic AddMenu(SysModuleElement model, string user)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                model.Class = model.Class ?? "";
                model.Icon = model.Icon ?? "";
                model.CreateBy = sysWebUser?.Account;
                model.CreateTime = DateTime.Now;
                model.UpdateBy = sysWebUser?.Account;
                model.UpdateTime = DateTime.Now;
                var result = Context.Insertable(model).ExecuteCommand();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearCurrentUserRedis(user);
                return response;
            });
        }

        /// <summary>
        /// 增加一组菜单
        /// </summary>
        /// <param name="modelList"></param>
        /// <returns></returns>
        public dynamic AddMenu(List<SysModuleElement> modelList, string user)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                foreach (var model in modelList)
                {
                    model.Class = model.Class ?? "";
                    model.Icon = model.Icon ?? "";
                    model.UpdateBy = sysWebUser?.Account;
                    model.UpdateTime = DateTime.Now;
                    model.CreateBy = sysWebUser?.Account;
                    model.CreateTime = DateTime.Now;
                }
                var result = Context.Insertable(modelList).ExecuteCommand();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearCurrentUserRedis(user);
                return response;
            });
        }

        /// <summary>
        /// 修改一个菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic UpdateMenu(SysModuleElement model)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                model.Class = model.Class ?? "";
                model.Icon = model.Icon ?? "";
                model.UpdateBy = sysWebUser?.Account;
                model.UpdateTime = DateTime.Now;
                var result = Context.Updateable(model).ExecuteCommand();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearOnlineUserRedis();
                return response;
            });
        }

        /// <summary>
        /// 删除多个菜单
        /// </summary>
        /// <param name="ids"></param>
        public dynamic DelMenu(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var result = Context.Deleteable<SysModuleElement>(t => ids.Contains(t.Id)).ExecuteCommand();
                if (result <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                ClearOnlineUserRedis();
                return response;
            });
        }
        #endregion

        #region 加载 用户、角色对应的模块、菜单

        /// <summary>
        /// 加载特定用户的模块
        /// TODO:这里会加载用户及用户角色的所有模块,“为用户分配模块”功能会给人一种混乱的感觉,但可以接受
        /// </summary>
        /// <param name="userId">The user unique identifier.</param>
        public dynamic LoadForUser(int userId)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                //取出用户对应的所有角色
                var roleIds = Context.Queryable<SysRelevance>()
                                     .Where(t => t.RelKey == Define.USERROLE && t.FirstId == userId)
                                     .Select(t => t.SecondId)
                                     .ToList();
                //取出 用户对应的模块、用户的角色对应的模块
                var moduleIds = Context.Queryable<SysRelevance>()
                                       .Where(t => t.RelKey == Define.USERMODULE && t.FirstId == userId ||
                                                   t.RelKey == Define.ROLEMODULE && roleIds.Contains(t.FirstId.Value))
                                       .Select(t => t.SecondId)
                                       .ToList();
                //去重
                moduleIds = moduleIds.Distinct().ToList();
                //根据模块ID找出模块
                var result = Context.Queryable<SysModule>()
                                    .Where(t => moduleIds.Contains(t.Id))
                                    .OrderBy(t => t.SortNo)
                                    .ToList();
                return result;
            });

        }

        /// <summary>
        /// 根据某用户ID获取可访问某模块的菜单项
        /// </summary>
        /// <param name="moduleId">模块id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public dynamic LoadMenusForUser(int moduleId, int userId)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                //取出用户对应的所有角色
                var roleIds = Context.Queryable<SysRelevance>()
                                     .Where(t => t.RelKey == Define.USERROLE && t.FirstId == userId)
                                     .Select(t => t.SecondId)
                                     .ToList();
                //取出 用户对应的菜单、用户角色对应的菜单
                var elementIds = Context.Queryable<SysRelevance>()
                                        .Where(t => t.RelKey == Define.USERELEMENT && t.FirstId == userId ||
                                                    t.RelKey == Define.ROLEELEMENT && roleIds.Contains(t.FirstId.Value))
                                        .Select(t => t.SecondId)
                                        .ToList();
                //根据模块ID找出菜单
                var result = Context.Queryable<SysModuleElement>()
                                    .Where(t => elementIds.Contains(t.Id) && t.ModuleId == moduleId)
                                    .ToList();
                return result;
            });
        }

        /// <summary>
        /// 加载特定角色的模块
        /// </summary>
        /// <param name="roleId">The role unique identifier.</param>
        public dynamic LoadForRole(int roleId)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                //取出角色对应的所有模块
                var elementIds = Context.Queryable<SysRelevance>()
                                        .Where(t => t.RelKey == Define.ROLEMODULE && t.FirstId == roleId)
                                        .Select(t => t.SecondId)
                                        .ToList();
                //根据模块ID找出模块
                var result = Context.Queryable<SysModule>()
                                         .Where(t => elementIds.Contains(t.Id))
                                         .OrderBy(u => u.SortNo)
                                         .ToList();
                return result;
            });
        }

        /// <summary>
        /// 加载特定角色的菜单
        /// </summary>
        /// <param name="moduleId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public dynamic LoadMenusForRole(int moduleId, int roleId)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                //取出角色对应的所有菜单
                var elementIds = Context.Queryable<SysRelevance>()
                                        .Where(t => t.RelKey == Define.ROLEELEMENT && t.FirstId == roleId)
                                        .Select(t => t.SecondId)
                                        .ToList();
                //根据模块ID找出菜单
                var result = Context.Queryable<SysModuleElement>()
                                         .Where(t => elementIds.Contains(t.Id) && t.ModuleId == moduleId)
                                         .ToList();
                return result;
            });
        }
        #endregion

        /// <summary>
        /// 填充模块实体的节点(生成类似XXX.XXX.X.XX)、父节点名
        /// 新增、复制新增读取所有节点CascadeId最后一个值要加1,编辑不变
        /// </summary>
        /// <param name="sysModule">模块实体</param>
        /// <param name="flag">操作标识,默认值为 "add"</param>
        public void ChangeModuleCascade(SysModule sysModule, string flag = "add")
        {
            int currentCascadeId = 1;

            if (flag != "update")
            {
                var query = Context.Queryable<SysModule>();
                // 查询同级模块
                if (sysModule.ParentId == null)
                {
                    query.Where(t => t.ParentId == null);
                }
                else
                {
                    query.Where(t => t.ParentId == sysModule.ParentId);
                }
                var sameLevels = query.ToList();
                // 计算当前级联 ID
                foreach (var obj in sameLevels)
                {
                    int objCascadeId = int.Parse(obj.CascadeId.TrimEnd('.').Split('.').Last());
                    currentCascadeId = Math.Max(currentCascadeId, objCascadeId + 1);
                }
            }
            // 设置父节点信息和级联 ID
            if (sysModule.ParentId != null)
            {
                var parentOrg = Context.Queryable<SysModule>().First(t => t.Id == sysModule.ParentId);
                if (parentOrg == null)
                {
                    throw new Exception("未能找到该组织的父节点信息");
                }
                if (flag != "update") sysModule.CascadeId = $"{parentOrg.CascadeId}{currentCascadeId}.";
                sysModule.ParentName = parentOrg.Name;
            }
            else
            {
                if (flag != "update") sysModule.CascadeId = $".0.{currentCascadeId}.";
                sysModule.ParentName = "根节点";
            }

            // 设置创建或更新时间
            if (flag == "add")
            {
                sysModule.CreateTime = DateTime.Now;
                sysModule.CreateBy = sysWebUser?.Account;
            }
            else
            {
                sysModule.UpdateTime = DateTime.Now;
                sysModule.UpdateBy = sysWebUser?.Account;
            }
        }

        public void SaveChanageCommonBtn(int moduleId, List<string> area1, List<string> area2, List<string> area3, List<SysModuleView> modulesView)
        {
            var defaultBtnDoms = DefaultBtns.Select(x => x.Value).ToList();
            var module = modulesView.SingleOrDefault(u => u.Id == moduleId)?.Elements.Where(x => defaultBtnDoms.Contains(x.DomId)).ToList();
            var newData = new Dictionary<int, List<string>>
                {
                    { 1, area1 },
                    { 2, area2 },
                    { 3, area3 }
                };
            foreach (var item in newData)
            {
                var deleteArea = module.Where(x => !item.Value.Contains(x.DomId) && x.AreaMenus == item.Key.ToString()).Select(x => x.Id).ToList();
                DelMenu(deleteArea.ConvertAll(x => Convert.ToInt32(x)).ToArray());
                var addArea1DomIds = item.Value.Where(x => !module.Where(m => m.AreaMenus == item.Key.ToString()).Select(y => y.DomId).Contains(x)).ToList();
                var addArea1Btns = ConvertMenuBtnModel(DefaultBtns.Where(x => addArea1DomIds.Contains(x.Value)).ToList(), item.Key.ToString(), moduleId);
                AddMenu(addArea1Btns, base.sysWebUser.Account);
            }
        }

        private List<SysModuleElement> ConvertMenuBtnModel(List<CheckBoxItem> items, string area, int moduleId)
        {
            int.TryParse(area, out int areaNum);
            if (areaNum <= 0)
            {
                areaNum = 1;
            }
            var elements = items.Select(x => new SysModuleElement
            {
                AreaMenus = area,
                Name = x.Text,
                Icon = x.Icon,
                Class = x.BtnClass,
                DomId = x.Value,
                ModuleId = moduleId,
                Remark = x.Text,
                Sort = areaNum * 10 + x.Sort,
            }).ToList();
            return elements;
        }

        private string HandleModuleCode(SysModule model,bool isNew=true)
        {
            string msg = "";
            int idCount = model.CascadeId.Count(i => i == '.');
            if (string.IsNullOrEmpty(model.Code) && idCount > 3)
            {
                msg = "模块标识不能为空";
                return msg;
            }
            var existingModule = Context.Queryable<SysModule>()
                                        .Where(x => x.Code == model.Code || x.Name == model.Name)
                                        .ToList();

            // 新增逻辑
            if (isNew) // 假设你有一个标识是否为新增操作的变量
            {
                if (existingModule.Any())
                {
                    msg = "模块标识或者模块名称不能重复,请重新输入!";
                }
            }
            else // 编辑逻辑
            {
                // 检查是否存在相同的 Code 或 Name,但排除当前编辑的记录
                var isHave = existingModule.Any(x => (x.Code == model.Code || x.Name == model.Name) && x.CascadeId != model.CascadeId);

                if (isHave)
                {
                    msg = "编辑菜单模块不能跟其它模块标识或者模块名称重复,请重新输入!";
                }
            }
            return msg;
        }
    }
}