schangxiang@126.com
2025-09-17 e8e8a06fc68a6a645ce32be2cc9c3aaa67a97d68
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
using iWareCommon.Common.Entity;
using iWareCommon.Common.EnumType;
using iWareCommon.Common.Service;
using iWareCommon.Utils;
using iWareDataCore.ORM;
using iWareDataCore.Properties;
using iWareDataCore.RBAC.Dao;
using iWareDataCore.RBAC.Entity;
using iWareDataCore.RBAC.EnumType;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace iWareDataCore.RBAC.Service
{
   public class UserService : CommonService<UserEntity, RBACUser, DbModelCore>
    {
 
        private static object Lock = new object();
 
        private UserService() : base(UserDao.GetInstance()) { }
 
        private static UserService Instance = null;
 
        /// <summary>
        /// 获取单例的方法
        /// </summary>
        /// <returns>用户服务的单例实体</returns>
        public static UserService GetInstance()
        {
 
            if (Instance == null)
            {
                lock (Lock)
                {
                    if (Instance == null)
                    {
                        Instance = new UserService();
                    }
                }
            }
            return Instance;
        }
 
        /// <summary>
        /// 批量修改用户状态
        /// </summary>
        /// <param name="ids">需要修改的用户id列表</param>
        /// <param name="status">状态:1为启用,0为锁定</param>
        /// <param name="msg">异常错误消息</param>
        /// <returns>修改的用户数量</returns>
        public int ChangeStatus(List<int> ids, int status, out string msg)
        {
            msg = "";
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var ones = dbModel.RBACUsers.Where(x => ids.Contains(x.id)).ToList();
 
                    foreach (var one in ones)
                    {
                        one.status = status;
                    }
 
                    dbModel.SaveChanges();
                    return ones.Count;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ChangeStatus", ex.Message);
                    return -1;
                }
            }
        }
 
 
        /// <summary>
        /// 用户自己修改用户密码
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="oldPassword">原密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="msg">异常错误消息</param>
        /// <returns>修改用户的Id,发生错误是返回-1</returns>
        public int ChangePassword(int id, string oldPassword, string newPassword, out string msg)
        {
            msg = "";
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var oPass = MD5Helper.ParseMd5(oldPassword);
 
                    var users = dbModel.RBACUsers.Where(x => x.id == id && x.password == oPass).ToList();
 
                    if (users.Count <= 0)
                    {
                        msg = "您输入的原始密码错误!";
                        return -1;
                    }
 
                    users[0].password = MD5Helper.ParseMd5(newPassword);
                    dbModel.SaveChanges();
                    return id;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ChangePassword", ex.Message);
                    return -1;
                }
            }
        }
 
        /// <summary>
        /// 将密码重置为111111
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="msg">异常错误消息</param>
        /// <returns>修改用户的Id,发生错误是返回-1</returns>
        public int ResetPassword(int id, out string msg)
        {
            msg = "";
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var users = dbModel.RBACUsers.Where(x => x.id == id).ToList();
 
                    if (users.Count <= 0)
                    {
                        msg = "未找到指定用户!";
                        return -1;
                    }
 
                    users[0].password = MD5Helper.ParseMd5(Resources.InitPassword);
                    dbModel.SaveChanges();
                    return id;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ResetPassword", ex.Message);
                    return -1;
                }
            }
        }
 
        public override List<UserEntity> QueryByParam(QueryParam param, out string msg)
        {
            msg = "";
 
            using (var dbModel = new DbModelCore())
            {
                var users = UserDao.GetInstance().QueryByParam(param, dbModel);
                var roles = RoleDao.GetInstance().QueryByParam(new QueryParam(), dbModel);
                //以角色Id为键,角色实体为值的字典
                var roleDictionary = new Dictionary<int, RoleEntity>();
 
                foreach (var role in roles)
                {
                    roleDictionary.Add(role.Id, role);
                }
 
                //以用户id为键,角色id列表为值的字典
                var userIdRoleIdsDictionary = new Dictionary<int, List<int>>();
 
                foreach (var user in users)
                {
                    userIdRoleIdsDictionary.Add(user.Id, new List<int>());
                }
 
                var roleUsers = RoleUserDao.GetInstance().QueryByParam(new QueryParam(), dbModel);
 
                foreach (var one in roleUsers)
                {
                    if (userIdRoleIdsDictionary.ContainsKey(one.UserId))
                    {
                        userIdRoleIdsDictionary[one.UserId].Add(one.RoleId);
                    }
                }
 
                foreach (var user in users)
                {
                    foreach (var roleId in userIdRoleIdsDictionary[user.Id])
                    {
                        user.Roles.Add(roleDictionary[roleId]);
                        user.DisplayRoleNames += roleDictionary[roleId].RoleName + ",";
                    }
 
                    if (user.DisplayRoleNames.EndsWith(","))
                    {
                        user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1);
                    }
                }
                return users;
            }
        }
 
        public override List<UserEntity> QueryByParam(QueryParam param, out string msg, out int totalNum, out int currentPage)
        {
            msg = "";
            totalNum = 0;
            currentPage = 1;
            using (var dbModel = new DbModelCore())
            {
                var users = UserDao.GetInstance().QueryByParam(param, dbModel, out totalNum, out currentPage);
                var roles = RoleDao.GetInstance().QueryByParam(new QueryParam(), dbModel);
                //以角色Id为键,角色实体为值的字典
                var roleDictionary = new Dictionary<int, RoleEntity>();
 
                foreach (var role in roles)
                {
                    roleDictionary.Add(role.Id, role);
                }
 
                //以用户id为键,角色id列表为值的字典
                var userIdRoleIdsDictionary = new Dictionary<int, List<int>>();
 
                foreach (var user in users)
                {
                    userIdRoleIdsDictionary.Add(user.Id, new List<int>());
                }
 
                var roleUsers = RoleUserDao.GetInstance().QueryByParam(new QueryParam(), dbModel);
 
                foreach (var one in roleUsers)
                {
                    if (userIdRoleIdsDictionary.ContainsKey(one.UserId))
                    {
                        userIdRoleIdsDictionary[one.UserId].Add(one.RoleId);
                    }
                }
 
                foreach (var user in users)
                {
                    foreach (var roleId in userIdRoleIdsDictionary[user.Id])
                    {
                        user.Roles.Add(roleDictionary[roleId]);
                        user.DisplayRoleNames += roleDictionary[roleId].RoleName + ",";
                    }
 
                    if (user.DisplayRoleNames.EndsWith(","))
                    {
                        user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1);
                    }
                }
                return users;
            }
 
        }
 
        public override int Delete(int id, out string msg)
        {
            Delete(new List<int> { id }, out msg);
            return string.IsNullOrEmpty(msg) ? id : -1;
        }
 
        public override int Delete(List<int> ids, out string msg)
        {
            msg = "";
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var roleUsers = dbModel.RBACRoleUsers.Where(x => ids.Contains(x.userid)).ToList();
                    roleUsers.ForEach(x => dbModel.RBACRoleUsers.Remove(x));
 
 
                    var ones = dbModel.RBACUsers.Where(x => ids.Contains(x.id)).ToList();
                    ones.ForEach(x => x.label = (int)ELabelStatus.已删除);
 
                    dbModel.SaveChanges();
                    return ones.Count;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "DeleteBatch", ex.Message);
                    return 0;
                }
            }
        }
 
        public override int Save(UserEntity user, out string msg)
        {
            msg = "";
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var one = user.ToOrm();
                    if (string.IsNullOrEmpty(one.password))
                    {
                        one.password = MD5Helper.ParseMd5(Resources.InitPassword);
                    }
                    else 
                    {
                        one.password = MD5Helper.ParseMd5(one.password);
                    }
 
                    if (user.Roles != null)
                    {
                        foreach (var role in user.Roles)
                        {
                            one.RBACRoleUsers.Add(new RBACRoleUser
                            {
                                roleid = role.Id
                            });
                        }
                    }
                    dbModel.RBACUsers.Add(one);
                    dbModel.SaveChanges();
                    return one.id;
                }
                catch (DbEntityValidationException ex)
                {
                    var errs = ex.EntityValidationErrors.SelectMany(validationResult => validationResult.ValidationErrors).Select(m => m.ErrorMessage);
                    msg = string.Join(", ", errs);
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Save", msg);
                    return -1;
                }
 
 
                catch (Exception ex)
                {
                    msg = ex.HResult == (int)EDbError.记录已存在 ? EDbError.记录已存在.ToString() : ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Save", msg);
                    return -1;
                }
            }
        }
 
        public override int Update(UserEntity user, out string msg)
        {
            msg = "";
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var one = dbModel.RBACUsers.First(x => x.id == user.Id);
 
                    EntityPropHelper<UserEntity, RBACUser>.CopyProp(user, one, UserEntity.GetColumnMap());
 
 
                    var ones = dbModel.RBACRoleUsers.Where(x => x.userid == user.Id).ToList();
 
                    foreach (var ur in ones)
                    {
                        dbModel.RBACRoleUsers.Remove(ur);
                    }
 
 
                    if (user.Roles != null)
                    {
                        foreach (var role in user.Roles)
                        {
                            one.RBACRoleUsers.Add(new RBACRoleUser
                            {
 
                                roleid = role.Id
                            });
                        }
                    }
 
 
                    dbModel.SaveChanges();
                    return one.id;
                }
 
                catch (DbEntityValidationException ex)
                {
                    var errs = ex.EntityValidationErrors.SelectMany(validationResult => validationResult.ValidationErrors).Select(m => m.ErrorMessage);
                    msg = string.Join(", ", errs);
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Save", msg);
                    return -1;
                }
 
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Update", ex.Message);
                    return -1;
                }
            }
        }
 
 
        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="msg">异常错误信息</param>
        /// <returns>登录成功后的用户信息,登录失败时返回null</returns>
        public UserEntity Login(string username, string password, out string msg)
        {
            msg = "";
 
            if (string.IsNullOrEmpty(username))
            {
                msg = "用户名不能为空";
                return null;
            }
 
            if (string.IsNullOrEmpty(password))
            {
                msg = "密码不能为空";
                return null;
            }
 
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var pass = MD5Helper.ParseMd5(password);
 
                    var users = dbModel.RBACUsers.Where(x => x.username == username && x.password == pass && x.status == (int)EStatus.启用 && x.label == (int)ELabelStatus.未删除).ToList();
 
                    if (users.Count <= 0)
                    {
                        msg = "用户名或密码错误!";
                        return null;
                    }
 
                    var user = new UserEntity(users[0]);
 
                    //拼装用户角色
                    var roleUsers = dbModel.RBACRoleUsers.Where(x => x.userid == user.Id).ToList();
 
                    var roleIds = new List<int>();
 
                    foreach (var one in roleUsers)
                    {
                        roleIds.Add(one.roleid);
                    }
 
                    var roles = dbModel.RBACRoles.Where(x => roleIds.Contains(x.id)).ToList();
 
                    foreach (var role in roles)
                    {
                        user.Roles.Add(new RoleEntity(role));
                    }
 
                    //拼装用户菜单
                    var roleContents = dbModel.RBACRoleContents.Where(x => roleIds.Contains(x.roleid)).ToList();
 
                    var contentIds = new List<int>();
 
                    var valueDictionary = new Dictionary<int, int>();
 
                    foreach (var roleContent in roleContents)
                    {
                        if (!contentIds.Contains(roleContent.contentid))
                        {
                            contentIds.Add(roleContent.contentid);
                            valueDictionary.Add(roleContent.contentid, roleContent.value);
                        }
                        else
                        {
                            if (valueDictionary[roleContent.contentid] < roleContent.value)
                            {
                                valueDictionary[roleContent.contentid] = roleContent.value;
                            }
                        }
                    }
 
                    var contents = dbModel.RBACContents.Where(x => contentIds.Contains(x.id)).OrderBy(x => x.contentindex).ToList();
 
                    var planContents = new List<ContentValueEntity>();
 
                    foreach (var content in contents)
                    {
                        planContents.Add(new ContentValueEntity(content, valueDictionary[content.id]));
                    }
 
                    var childrenDictionary = TreeHelper<ContentValueEntity>.GetChildrenDictionary(planContents);
 
                    var userContents = childrenDictionary.ContainsKey(-1) ? childrenDictionary[-1] : new List<ContentValueEntity>();
 
                    foreach (var content in userContents)
                    {
                        if (((int)EContentType.用于BS端的菜单).Equals(content.Type))
                        {
                            user.Contents.Add(content);
                        }
                        else if (((int)EContentType.用于CS端的菜单).Equals(content.Type))
                        {
                            user.CsContents.Add(content);
                        }
                    }
 
 
 
                    if (user.Roles.Count > 0)
                    {
                        for (var i = 0; i < user.Roles.Count; i++)
                        {
                            user.DisplayRoleNames += user.Roles[i].RoleName + ",";
                        }
                        if (user.DisplayRoleNames.EndsWith(","))
                        {
                            user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1);
                        }
                    }
 
                    return user;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Login", ex.Message);
                    return null;
                }
            }
        }
 
        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="msg">异常错误信息</param>
        /// <returns>登录成功后的用户信息,登录失败时返回null</returns>
        public UserEntity Login(string username, string password, string cellName, out string msg)
        {
            msg = "";
 
            if (string.IsNullOrEmpty(username))
            {
                msg = "用户名不能为空";
                return null;
            }
 
            if (string.IsNullOrEmpty(password))
            {
                msg = "密码不能为空";
                return null;
            }
 
            using (var dbModel = new DbModelCore())
            {
                try
                {
                    var pass = MD5Helper.ParseMd5(password);
 
                    var users = dbModel.RBACUsers.Where(x => x.username == username && x.password == pass && x.status == (int)EStatus.启用 && x.label == (int)ELabelStatus.未删除).ToList();
 
                    if (users.Count <= 0)
                    {
                        msg = "用户名或密码错误!";
                        return null;
                    }
 
                    var user = new UserEntity(users[0]);
                    var roleIds = new List<int>();
 
                    var roles = dbModel.RBACRoles.Where(x => x.rolename == cellName).ToList();
 
                    foreach (var role in roles)
                    {
                        roleIds.Add(role.id);
                        user.Roles.Add(new RoleEntity(role));
                    }
 
                    //拼装用户菜单
                    var roleContents = dbModel.RBACRoleContents.Where(x => roleIds.Contains(x.roleid)).ToList();
 
                    var contentIds = new List<int>();
 
                    var valueDictionary = new Dictionary<int, int>();
 
                    foreach (var roleContent in roleContents)
                    {
                        if (!contentIds.Contains(roleContent.contentid))
                        {
                            contentIds.Add(roleContent.contentid);
                            valueDictionary.Add(roleContent.contentid, roleContent.value);
                        }
                        else
                        {
                            if (valueDictionary[roleContent.contentid] < roleContent.value)
                            {
                                valueDictionary[roleContent.contentid] = roleContent.value;
                            }
                        }
                    }
 
                    var contents = dbModel.RBACContents.Where(x => contentIds.Contains(x.id)).OrderBy(x => x.contentindex).ToList();
 
                    var planContents = new List<ContentValueEntity>();
 
                    foreach (var content in contents)
                    {
                        planContents.Add(new ContentValueEntity(content, valueDictionary[content.id]));
                    }
 
                    var childrenDictionary = TreeHelper<ContentValueEntity>.GetChildrenDictionary(planContents);
 
                    var userContents = childrenDictionary.ContainsKey(-1) ? childrenDictionary[-1] : new List<ContentValueEntity>();
 
                    foreach (var content in userContents)
                    {
                        if (((int)EContentType.用于BS端的菜单).Equals(content.Type))
                        {
                            user.Contents.Add(content);
                        }
                        else if (((int)EContentType.用于CS端的菜单).Equals(content.Type))
                        {
                            user.CsContents.Add(content);
                        }
                    }
 
 
 
                    if (user.Roles.Count > 0)
                    {
                        for (var i = 0; i < user.Roles.Count; i++)
                        {
                            user.DisplayRoleNames += user.Roles[i].RoleName + ",";
                        }
                        if (user.DisplayRoleNames.EndsWith(","))
                        {
                            user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1);
                        }
                    }
 
                    return user;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Login", ex.Message);
                    return null;
                }
            }
        }
 
    }
}