helongyang
16 小时以前 dc06f58d8ed537555fd529551180f43a0586ec3f
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
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_DTO.System;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.HttpContextUser;
using WIDESEA_ISystemRepository;
using WIDESEA_ISystemService;
using WIDESEA_Model.Models;
using WIDESEA_Model.Models.System;
using WIDESEA_SystemRepository;
using WIDESEA_Core.Helper;
using WIDESEA_Core.HostedService;
 
namespace WIDESEA_SystemService
{
    public class Sys_RoleService : ServiceBase<Sys_Role, ISys_RoleRepository>, ISys_RoleService
    {
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly ISys_MenuRepository _MenuRepository;
        private readonly ISys_MenuService _MenuService;
        private readonly ISys_RoleAuthRepository _RoleAuthRepository;
 
        public ISys_RoleRepository Repository => BaseDal;
 
        public Sys_RoleService(ISys_RoleRepository BaseDal, ISys_MenuRepository MenuRepository, ISys_MenuService MenuService, ISys_RoleAuthRepository roleAuthRepository, IUnitOfWorkManage unitOfWorkManage) : base(BaseDal)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _MenuRepository = MenuRepository;
            _MenuService = MenuService;
            _RoleAuthRepository = roleAuthRepository;
        }
 
        public override WebResponseContent AddData(SaveModel saveModel)
        {
            string authorityScope = saveModel.MainData["authorityScope"].ToString() ?? "";
            Sys_Role role = saveModel.MainData.DicToModel<Sys_Role>();
            if (BaseDal.QueryFirst(x => x.RoleName == role.RoleName) != null)
            {
                return WebResponseContent.Instance.Error($"角色名重复");
            }
            List<Dt_Warehouse> warehouses = BaseDal.Db.Queryable<Dt_Warehouse>().Where(x => true).ToList();
            List<Sys_RoleDataPermission> roleDataPermissions = new List<Sys_RoleDataPermission>();
            if (!string.IsNullOrEmpty(authorityScope))
            {
                string[] scopes = authorityScope.Split(',');
                foreach (string scope in scopes)
                {
                    Dt_Warehouse? warehouse = warehouses.FirstOrDefault(x => x.WarehouseId == Convert.ToInt32(scope));
                    if (warehouse != null)
                    {
                        roleDataPermissions.Add(new Sys_RoleDataPermission
                        {
                            WarehouseId = warehouse.WarehouseId,
                            WarehouseName = warehouse.WarehouseName,
                            RoleName = role.RoleName
                        });
                    }
                }
            }
 
            int roleId = BaseDal.AddData(role);
            if (roleDataPermissions.Count > 0)
            {
                roleDataPermissions.ForEach(x => { x.RoleId = roleId; });
                BaseDal.Db.Insertable(roleDataPermissions).ExecuteCommand();
            }
 
            PermissionDataHostService.UserRoles = PermissionDataHostService.GetUserRoles(Db);
 
            return WebResponseContent.Instance.OK();
        }
 
        public override WebResponseContent UpdateData(SaveModel saveModel)
        {
            string authorityScope = saveModel.MainData["authorityScope"].ToString() ?? "";
            Sys_Role role = saveModel.MainData.DicToModel<Sys_Role>();
            if (BaseDal.QueryFirst(x => x.RoleId == role.RoleId) == null)
            {
                return WebResponseContent.Instance.Error($"未找到该数据");
            }
            List<Dt_Warehouse> warehouses = BaseDal.Db.Queryable<Dt_Warehouse>().Where(x => true).ToList();
 
            List<Sys_RoleDataPermission> oldDatas = BaseDal.Db.Queryable<Sys_RoleDataPermission>().Where(x => x.RoleId == role.RoleId).ToList();
            List<Sys_RoleDataPermission> roleDataPermissions = new List<Sys_RoleDataPermission>();
            if (!string.IsNullOrEmpty(authorityScope))
            {
                string[] scopes = authorityScope.Split(',');
                foreach (string scope in scopes)
                {
                    Sys_RoleDataPermission? oldData = oldDatas.FirstOrDefault(x => x.WarehouseId == Convert.ToInt32(scope));
                    if (oldData == null)
                    {
                        Dt_Warehouse? warehouse = warehouses.FirstOrDefault(x => x.WarehouseId == Convert.ToInt32(scope));
                        if (warehouse != null)
                        {
                            roleDataPermissions.Add(new Sys_RoleDataPermission
                            {
                                WarehouseId = warehouse.WarehouseId,
                                WarehouseName = warehouse.WarehouseName,
                                RoleName = role.RoleName
                            });
                        }
                    }
                    else
                    {
                        oldDatas.Remove(oldData);
                    }
                }
            }
 
            roleDataPermissions.ForEach(x => { x.RoleId = role.RoleId; });
            BaseDal.Db.Insertable(roleDataPermissions).ExecuteCommand();
            BaseDal.Db.Deleteable(oldDatas).ExecuteCommand();
 
            PermissionDataHostService.UserRoles = PermissionDataHostService.GetUserRoles(Db);
 
            return WebResponseContent.Instance.OK();
        }
 
        public List<int> GetAllChildrenRoleId(int roleId)
        {
            return GetAllChildren(roleId).Select(x => x.Id).ToList();
        }
 
        public List<RoleNodes> GetAllChildren(int roleId)
        {
            if (roleId <= 0) return new List<RoleNodes>() { };
            var roles = GetAllRoleId();
            if (App.User.IsRoleIdSuperAdmin(roleId)) return roles;
 
            var list = GetChildren(roles, roleId);
            return list;
        }
 
        public List<RoleNodes> GetAllRoleId()
        {
            List<RoleNodes> roles = BaseDal.QueryData().Select(s => new RoleNodes() { Id = s.RoleId, ParentId = s.ParentId, RoleName = s.RoleName }).ToList();
 
            return roles;
        }
 
        /// <summary>
        /// 获取所有子节点
        /// </summary>
        /// <param name="roleId"></param>
        private List<RoleNodes> GetChildren(List<RoleNodes> roles, int roleId)
        {
            List<RoleNodes> rolesChildren = roles.Where(x => x.Id == roleId).Distinct().ToList();
 
            for (int i = 0; i < rolesChildren.Count; i++)
            {
                RoleNodes node = rolesChildren[i];
                var children = roles.Where(x => x.ParentId == node.Id && !rolesChildren.Any(c => c.Id == x.Id)).Distinct().ToList();
                rolesChildren.AddRange(children);
            }
            return rolesChildren;
        }
 
        /// <summary>
        /// 编辑权限时获取当前用户下的所有角色与当前用户的菜单权限
        /// </summary>
        /// <returns></returns>
        public WebResponseContent GetCurrentTreePermission()
        {
            WebResponseContent content = GetCurrentUserTreePermission();
            int roleId = App.User.RoleId;
            return WebResponseContent.Instance.OK(null, new
            {
                tree = content.Data,
                roles = GetAllChildren(roleId)
            });
        }
 
        /// <summary>
        /// 编辑权限时,获取当前用户的所有菜单权限
        /// </summary>
        /// <returns></returns>
        public WebResponseContent GetCurrentUserTreePermission()
        {
            return GetUserTreePermission(App.User.RoleId);
        }
 
        /// <summary>
        /// 编辑权限时,获取指定角色的所有菜单权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public WebResponseContent GetUserTreePermission(int roleId)
        {
            if (!App.User.IsRoleIdSuperAdmin(roleId) && App.User.RoleId != roleId)
            {
                if (!(GetAllChildren(App.User.RoleId)).Exists(x => x.Id == roleId))
                {
                    return WebResponseContent.Instance.Error("没有权限获取此角色的权限信息");
                }
            }
            //获取用户权限
            List<Permissions> permissions = _MenuRepository.GetPermissions(roleId);
            //权限用户权限查询所有的菜单信息
            List<MenuDTO> menus = _MenuService.GetUserMenuList(roleId);
            //获取当前用户权限如:(Add,Search)对应的显示文本信息如:Add:添加,Search:查询
            var data = menus.Select(x => new
            {
                Id = x.MenuId,
                Pid = x.ParentId,
                Text = x.MenuName,
                IsApp = x.MenuType == 1,
                Actions = _MenuService.GetActions(x.MenuId, x.Actions, permissions, roleId)
            });
            return WebResponseContent.Instance.OK(null, data);
        }
        public WebResponseContent GetCurrentTreePermissionPDA()
        {
            WebResponseContent content = GetCurrentUserTreePermissionPDA();
            int roleId = App.User.RoleId;
            return WebResponseContent.Instance.OK(null, new
            {
                tree = content.Data,
                roles = GetAllChildren(roleId)
            });
        }
 
        /// <summary>
        /// 编辑权限时,获取当前用户的所有菜单权限
        /// </summary>
        /// <returns></returns>
        public WebResponseContent GetCurrentUserTreePermissionPDA()
        {
            return GetUserTreePermissionPDA(App.User.RoleId);
        }
        public WebResponseContent GetUserTreePermissionPDA(int roleId)
        {
            if (!App.User.IsRoleIdSuperAdmin(roleId) && App.User.RoleId != roleId)
            {
                if (!(GetAllChildren(App.User.RoleId)).Exists(x => x.Id == roleId))
                {
                    return WebResponseContent.Instance.Error("没有权限获取此角色的权限信息");
                }
            }
            //获取用户权限
            List<Permissions> permissions = _MenuRepository.GetPermissions(roleId);
            //权限用户权限查询所有的菜单信息
            List<MenuDTO> menus = _MenuService.GetUserMenuListPDA(roleId);
 
            //获取当前用户权限如:(Add,Search)对应的显示文本信息如:Add:添加,Search:查询
            var data = menus.Where(x => x.MenuType == 1).Select(x => new
            {
                Id = x.MenuId,
                Pid = x.ParentId,
                Text = x.MenuName,
                IsApp = x.MenuType == 1,
                Actions = _MenuService.GetActions(x.MenuId, x.Actions, permissions, roleId)
            });
            return WebResponseContent.Instance.OK(null, data);
        }
 
        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="userPermissions"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public WebResponseContent SavePermission(List<UserPermissionDTO> userPermissions, int roleId)
        {
            WebResponseContent content = new WebResponseContent();
            string message = "";
            try
            {
                if (!GetAllChildren(App.User.RoleId).Exists(x => x.Id == roleId))
                    return WebResponseContent.Instance.Error("没有权限修改此角色的权限信息");
                //当前用户的权限
                List<Permissions> permissions = _MenuRepository.GetPermissions(App.User.RoleId);
 
                List<int> menuIds = _MenuRepository.QueryData(x => x.MenuId, x => x.MenuType == 1);
 
                List<int> originalMeunIds = new List<int>();
                //被分配角色的权限
                List<Sys_RoleAuth> roleAuths = _RoleAuthRepository.QueryData(x => x.RoleId == roleId && menuIds.Contains(x.MenuId));
                List<Sys_RoleAuth> updateAuths = new List<Sys_RoleAuth>();
                foreach (UserPermissionDTO x in userPermissions)
                {
                    Permissions per = permissions.FirstOrDefault(p => p.MenuId == x.Id);
                    //不能分配超过当前用户的权限
                    if (per == null) continue;
                    //per.UserAuthArr.Contains(a.Value)校验权限范围
                    string[] arr = x.Actions == null || x.Actions.Count == 0
                      ? new string[0]
                      : x.Actions.Where(a => per.UserAuthArr.Contains(a.Value))
                      .Select(s => s.Value).ToArray();
 
                    //如果当前权限没有分配过,设置Auth_Id默认为0,表示新增的权限
                    var auth = roleAuths.Where(r => r.MenuId == x.Id).Select(s => new { s.AuthId, s.AuthValue, s.MenuId }).FirstOrDefault();
                    string newAuthValue = string.Join(",", arr);
                    //权限没有发生变化则不处理
                    if (auth == null || auth.AuthValue != newAuthValue)
                    {
                        updateAuths.Add(new Sys_RoleAuth()
                        {
                            RoleId = roleId,
                            MenuId = x.Id,
                            AuthValue = string.Join(",", arr),
                            AuthId = auth == null ? 0 : auth.AuthId,
                            ModifyDate = DateTime.Now,
                            Modifier = App.User.UserName,
                            CreateDate = DateTime.Now,
                            Creater = App.User.UserName
                        });
                    }
                    else
                    {
                        originalMeunIds.Add(auth.MenuId);
                    }
 
                }
                //更新权限
                _RoleAuthRepository.UpdateData(updateAuths);
                //新增的权限
                _RoleAuthRepository.AddData(updateAuths);
 
                //获取权限取消的权限
                int[] authIds = roleAuths.Where(x => userPermissions.Select(u => u.Id)
                 .ToList().Contains(x.MenuId) || originalMeunIds.Contains(x.MenuId))
                .Select(s => s.AuthId)
                .ToArray();
                List<Sys_RoleAuth> delAuths = roleAuths.Where(x => x.AuthValue != "" && !authIds.Contains(x.AuthId)).ToList();
                delAuths.ForEach(x =>
                {
                    x.AuthValue = "";
                });
                //将取消的权限设置为""
                _RoleAuthRepository.DeleteData(delAuths);
 
                int addCount = updateAuths.Where(x => x.AuthId <= 0).Count();
                int updateCount = updateAuths.Where(x => x.AuthId > 0).Count();
 
                string _version = DateTime.Now.ToString("yyyyMMddHHMMssfff");
 
 
                content.OK($"保存成功:新增加配菜单权限{addCount}条,更新菜单{updateCount}条,删除权限{delAuths.Count}条");
            }
            catch (Exception ex)
            {
                message = "异常信息:" + ex.Message + ex.StackTrace + ",";
            }
 
            return content;
        }
 
        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="userPermissions"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public WebResponseContent SavePermissionPDA(List<UserPermissionDTO> userPermissions, int roleId)
        {
            WebResponseContent content = new WebResponseContent();
            string message = "";
            try
            {
                if (!GetAllChildren(App.User.RoleId).Exists(x => x.Id == roleId))
                    return WebResponseContent.Instance.Error("没有权限修改此角色的权限信息");
                //当前用户的权限
                List<Permissions> permissions = _MenuRepository.GetPermissions(App.User.RoleId);
 
                List<int> originalMeunIds = new List<int>();
 
                List<int> menuIds = _MenuRepository.QueryData(x => x.MenuId, x => x.MenuType == 1);
 
                //被分配角色的权限
                List<Sys_RoleAuth> roleAuths = _RoleAuthRepository.QueryData(x => x.RoleId == roleId && menuIds.Contains(x.MenuId));
                List<Sys_RoleAuth> updateAuths = new List<Sys_RoleAuth>();
                foreach (UserPermissionDTO x in userPermissions)
                {
                    Permissions per = permissions.FirstOrDefault(p => p.MenuId == x.Id);
                    //不能分配超过当前用户的权限
                    if (per == null) continue;
                    //per.UserAuthArr.Contains(a.Value)校验权限范围
                    string[] arr = x.Actions == null || x.Actions.Count == 0
                      ? new string[0]
                      : x.Actions.Where(a => per.UserAuthArr.Contains(a.Value))
                      .Select(s => s.Value).ToArray();
 
                    //如果当前权限没有分配过,设置Auth_Id默认为0,表示新增的权限
                    var auth = roleAuths.Where(r => r.MenuId == x.Id).Select(s => new { s.AuthId, s.AuthValue, s.MenuId }).FirstOrDefault();
                    string newAuthValue = string.Join(",", arr);
                    //权限没有发生变化则不处理
                    if (auth == null || auth.AuthValue != newAuthValue)
                    {
                        updateAuths.Add(new Sys_RoleAuth()
                        {
                            RoleId = roleId,
                            MenuId = x.Id,
                            AuthValue = string.Join(",", arr),
                            AuthId = auth == null ? 0 : auth.AuthId,
                            ModifyDate = DateTime.Now,
                            Modifier = App.User.UserName,
                            CreateDate = DateTime.Now,
                            Creater = App.User.UserName
                        });
                    }
                    else
                    {
                        originalMeunIds.Add(auth.MenuId);
                    }
 
                }
                //更新权限
                _RoleAuthRepository.UpdateData(updateAuths);
                //新增的权限
                _RoleAuthRepository.AddData(updateAuths);
 
                //获取权限取消的权限
                int[] authIds = roleAuths.Where(x => userPermissions.Select(u => u.Id)
                 .ToList().Contains(x.MenuId) || originalMeunIds.Contains(x.MenuId))
                .Select(s => s.AuthId)
                .ToArray();
                List<Sys_RoleAuth> delAuths = roleAuths.Where(x => x.AuthValue != "" && !authIds.Contains(x.AuthId)).ToList();
                delAuths.ForEach(x =>
                {
                    x.AuthValue = "";
                });
                //将取消的权限设置为""
                _RoleAuthRepository.DeleteData(delAuths);
 
                int addCount = updateAuths.Where(x => x.AuthId <= 0).Count();
                int updateCount = updateAuths.Where(x => x.AuthId > 0).Count();
 
                string _version = DateTime.Now.ToString("yyyyMMddHHMMssfff");
 
 
                content.OK($"保存成功:新增加配菜单权限{addCount}条,更新菜单{updateCount}条,删除权限{delAuths.Count}条");
            }
            catch (Exception ex)
            {
                message = "异常信息:" + ex.Message + ex.StackTrace + ",";
            }
 
            return content;
        }
    }
}