yanjinhui
2025-04-03 5d6ba8e6b477a0ed540e1c3267c2618939a5356b
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
using WIDESEAWCS_Core.Authorization;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.BaseServices;
using WIDESEAWCS_Core.Const;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_Core.HttpContextUser;
using WIDESEAWCS_ISystemServices;
using WIDESEAWCS_Model;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_ISystemRepository;
using WIDESEAWCS_Core.BaseRepository;
using System.Net;
using WIDESEAWCS_Core.Caches;
using WIDESEA_ISerialPortRepository;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using ICacheService = WIDESEAWCS_Core.Caches.ICacheService;
using Microsoft.AspNetCore.Builder;
using WIDESEAWCS_DTO.SerialPort;
using WIDESEAWCS_DTO.Telescopic;
using WIDESEAWCS_Common;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System.Security.Policy;
 
namespace WIDESEAWCS_SystemServices
{
    public class Sys_UserService : ServiceBase<Sys_User, ISys_UserRepository>, ISys_UserService
    {
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly ICacheService _cacheService;
        private readonly ISys_MenuService _menuService;
        private readonly ISys_RoleRepository _RoleRepository;
        private readonly ILoginHistoryRepository _loginHistoryRepository;
        private readonly IPutakeRepository _putakeRepository;
        private readonly IFaceRecognitionRepository _faceRecognitionRepository;
 
 
 
        public Sys_UserService(IFaceRecognitionRepository faceRecognitionRepository, ISys_UserRepository repository, IUnitOfWorkManage unitOfWorkManage,
            ICacheService cacheService, ISys_MenuService menuService, ISys_RoleRepository roleRepository, ILoginHistoryRepository loginHistoryRepository, IPutakeRepository putakeRepository) : base(repository)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _cacheService = cacheService;
            _menuService = menuService;
            _RoleRepository = roleRepository;
            _RoleRepository = roleRepository;
            _loginHistoryRepository = loginHistoryRepository;
            _putakeRepository = putakeRepository;
            _faceRecognitionRepository = faceRecognitionRepository;
 
        }
 
        //#region 原本登入
        //public WebResponseContent Login(LoginInfo loginInfo)
        //{
        //    WebResponseContent content = new WebResponseContent();
        //    try
        //    {
        //        // BaseDal.QueryFirst(x => x.UserName == loginInfo.UserName);
 
        //        string msg = string.Empty;
 
        //        #region 临时使用
        //        try
        //        {
        //            loginInfo.Password = loginInfo.Password.EncryptDES(AppSecret.User);
        //        }
        //        catch
        //        {
 
        //        }
        //        #endregion
        //        if (!string.IsNullOrEmpty(loginInfo.path))
        //        {
        //            var gruoid = _faceRecognitionRepository.QueryData().Select(x => x.GroupID).FirstOrDefault();
        //            if (gruoid == null)
        //            {
        //                return new WebResponseContent { Status = false, Message = "没找到该组" };
 
        //            }
        //            var faceResult = BaiDuFaceHelper.FaceSearch(loginInfo.path, gruoid);
 
        //            if (faceResult != null && faceResult.error_code == 0)
        //            {
        //                // 获取最高匹配度的用户
        //                var bestMatch = faceResult.result.user_list.OrderByDescending(u => u.score).FirstOrDefault();//拿第一个最高的
 
        //                if (bestMatch != null && double.TryParse(bestMatch.score, out double score) && score > 80) // 设定80分为可信度阈值
        //                {
        //                    //return new WebResponseContent {Status=true,Data = true,Message="识别登入成功" };
 
        //                }
        //            }
 
        //            return WebResponseContent.Instance.Error("人脸识别失败,请重试");
        //        }
 
        //        UserInfo user = BaseDal.GetUserInfo(loginInfo.UserName, loginInfo.Password);
 
 
        //        var disbled = BaseDal.QueryFirst(x => x.UserName == loginInfo.UserName);//根据这个用户名来查看用户
        //        if (user != null)
        //        {
        //            object obj = _menuService.GetMenuActionList(user.RoleId);
        //            if (obj is not IEnumerable<object> list)
        //            {
        //                return WebResponseContent.Instance.Error("无登录权限");
        //            }
        //            if (!list.Any())
        //            {
        //                return WebResponseContent.Instance.Error("无登录权限");
        //            }
        //            if (disbled.Enable != 1)
        //            {
        //                return WebResponseContent.Instance.Error("你的账号已被禁用,请联系管理员");
        //            }
 
        //            string token = JwtHelper.IssueJwt(new TokenModelJwt()
        //            {
        //                UserId = user.UserId,
        //                RoleId = user.RoleId,
        //                UserName = user.UserName,
        //                TenantId = user.TenantId,
        //            });
        //            //登入历史记录
        //            var loghis = new Dt_LoginHistory
        //            {
        //                Account = user.UserName,
        //                TrurName = user.UserTrueName,
        //                CreateDate = DateTime.Now
 
        //            };
 
 
        //            _cacheService.AddOrUpdate(user.UserId.ToString(), token);
        //            _loginHistoryRepository.AddData(loghis);
 
        //            content = WebResponseContent.Instance.OK(data: new { token, userName = user.UserTrueName, img = user.HeadImageUrl, ID = user.UserId, RoleId = user.RoleId });
        //        }
        //        else
        //        {
        //            content = WebResponseContent.Instance.Error("账号或密码错误");
        //        }
 
        //    }
 
        //    catch (Exception ex)
        //    {
        //        content = WebResponseContent.Instance.Error(ex.Message);
        //    }
 
        //    return content;
        //}
        //#endregion
 
 
        /// <summary>
        /// 人脸识别登入接口
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <returns></returns>
        public WebResponseContent Login(LoginInfo loginInfo)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                //string msg = string.Empty;
 
                #region 临时使用
                try
                {
                    loginInfo.Password = loginInfo.Password.EncryptDES(AppSecret.User);
                }
                catch
                {
                }
                #endregion
 
                // 先获取用户信息
                UserInfo user = null;
                if (!string.IsNullOrEmpty(loginInfo.path))
                {
                    // 人脸识别登录
                    var groupId = _faceRecognitionRepository.QueryData().Select(x => x.GroupID).FirstOrDefault();
                    if (groupId == null)
                    {
                        return WebResponseContent.Instance.Error("没找到该人脸识别分组");
                    }
 
                    var faceResult = BaiDuFaceHelper.FaceSearch(loginInfo.path, groupId);
                    if (faceResult != null && faceResult.error_code == 0)
                    {
                        var bestMatch = faceResult.result.user_list.OrderByDescending(u => u.score).FirstOrDefault();
                        string usercount = bestMatch.user_id;
                        if (bestMatch != null && double.TryParse(bestMatch.score, out double score) && score > 80)
                        {
                            //用识别到的 user_id 来获取用户信息
                            var faceuser = BaseDal.QueryData(x => x.UserName == usercount).FirstOrDefault(); // 获取匹配的第一个用户
                            if (faceuser != null)
                            {
                                // 手动将 Sys_User 映射到 UserInfo
                                user = new UserInfo
                                {
                                    UserId = faceuser.User_Id,
                                    UserName = faceuser.UserName,
                                    UserTrueName = faceuser.UserTrueName,
                                    HeadImageUrl = faceuser.HeadImageUrl,
                                    RoleId = faceuser.Role_Id,
                                    TenantId = faceuser.TenantId,
                                };
                            }
                        }
 
                        if (user == null)
                        {
                            return WebResponseContent.Instance.Error("人脸识别失败,请重试");
                        }
                        loginInfo.UserName = user.UserName;
                    }
                }
                else
                {
                    // 密码登录
                    user = BaseDal.GetUserInfo(loginInfo.UserName, loginInfo.Password);
                }
 
                    // 如果找到用户
                    if (user != null)
                    {
                   
                        var disbled = BaseDal.QueryFirst(x => x.UserName == loginInfo.UserName);
                        if (disbled.Enable != 1)
                        {
                            return WebResponseContent.Instance.Error("你的账号已被禁用,请联系管理员");
                        }
 
                        // 获取角色权限
                        object obj = _menuService.GetMenuActionList(user.RoleId);
                        if (obj is not IEnumerable<object> list || !list.Any())
                        {
                            return WebResponseContent.Instance.Error("无登录权限");
                        }
 
                        // 生成 JWT Token
                        string token = JwtHelper.IssueJwt(new TokenModelJwt()
                        {
                            UserId = user.UserId,
                            RoleId = user.RoleId,
                            UserName = user.UserName,
                            TenantId = user.TenantId,
                        });
 
                        // 记录登录历史
                        var loghis = new Dt_LoginHistory
                        {
                            Account = user.UserName,
                            TrurName = user.UserTrueName,
                            CreateDate = DateTime.Now
                        };
 
                        // 保存用户登录信息
                        _cacheService.AddOrUpdate(user.UserId.ToString(), token);
                        _loginHistoryRepository.AddData(loghis);
 
                        // 返回响应
                        content = WebResponseContent.Instance.OK(data: new
                        {
                            token,
                            userName = user.UserTrueName,
                            img = user.HeadImageUrl,
                            ID = user.UserId,
                            RoleId = user.RoleId
                        });
                    }
                    else
                    {
                        content = WebResponseContent.Instance.Error("账号或密码错误");
                    }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
 
            return content;
        }
 
       
 
 
        public override WebResponseContent UpdateData(SaveModel saveModel)
        {
            UpdateIgnoreColOnExecute = x =>
            {
                return new List<string>
                {
                    nameof(Sys_User.UserPwd),
                    nameof(Sys_User.TenantId)
                };
            };
            return base.UpdateData(saveModel);
        }
 
        public override WebResponseContent AddData(SaveModel saveModel)
        {
            string pwd = "123456";
            string uesrName = saveModel.MainData[nameof(Sys_User.UserName).FirstLetterToLower()].ToString();
            saveModel.MainData[nameof(Sys_User.UserPwd).FirstLetterToLower()] = pwd.EncryptDES(AppSecret.User);
 
            WebResponseContent content = base.AddData(saveModel);
            if (content.Status)
            {
                return WebResponseContent.Instance.OK($"用户新建成功.帐号{uesrName}密码{pwd}");
            }
            else
            {
                return content;
            }
        }
 
        /// <summary>
        /// 个人中心获取当前用户信息
        /// </summary>
        /// <returns></returns>
        public WebResponseContent GetCurrentUserInfo()
        {
            var data = BaseDal.QueryFirst(x => x.User_Id == App.User.UserId, s => new
            {
                s.UserName,
                s.UserTrueName,
                s.Address,
                s.PhoneNo,
                s.Email,
                s.Remark,
                s.Gender,
                s.RoleName,
                s.HeadImageUrl,
                s.CreateDate
            });
            return WebResponseContent.Instance.OK(null, data);
        }
 
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public WebResponseContent ModifyPwd(string oldPwd, string newPwd)
        {
            WebResponseContent content = WebResponseContent.Instance;
            oldPwd = oldPwd?.Trim();
            newPwd = newPwd?.Trim();
            string message = "";
            try
            {
                if (string.IsNullOrEmpty(oldPwd)) return WebResponseContent.Instance.Error("旧密码不能为空");
                if (string.IsNullOrEmpty(newPwd)) return WebResponseContent.Instance.Error("新密码不能为空");
                if (newPwd.Length < 6) return WebResponseContent.Instance.Error("密码不能少于6位");
 
                int userId = App.User.UserId;
 
                string userCurrentPwd = BaseDal.QueryFirst(x => x.User_Id == userId, s => s.UserPwd);
 
                string _oldPwd = oldPwd.EncryptDES(AppSecret.User);
                if (_oldPwd != userCurrentPwd) return WebResponseContent.Instance.Error("旧密码不正确");
 
                string _newPwd = newPwd.EncryptDES(AppSecret.User);
                if (userCurrentPwd == _newPwd) return WebResponseContent.Instance.Error("新密码不能与旧密码相同");
 
 
                BaseDal.UpdateData(new Sys_User
                {
                    User_Id = userId,
                    UserPwd = _newPwd,
                    LastModifyPwdDate = DateTime.Now
                }, new List<string>
                {
                    nameof(Sys_User.LastModifyPwdDate),
                    nameof(Sys_User.UserPwd)
                });
                //content = WebResponseContent.Instance.OK("密码修改成功");
                content = WebResponseContent.Instance.OK("密码修改成功", userId);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                content = WebResponseContent.Instance.Error("服务器了点问题,请稍后再试");
            }
            return content;
 
        }
 
        public WebResponseContent GetUerType()
        {
            try
            {
                var role = _RoleRepository.QueryData();
                var user = BaseDal.QueryData();
 
                var result = user.Join(
                    role,
                    u => u.Role_Id,
                    r => r.RoleId,
                    (u, r) => new
                    {
                        u.User_Id,
                        u.UserName,
                        r.RoleId,
                        u.RoleName,
                        u.UserTrueName,
                    }).ToList();
 
                return new WebResponseContent { Status = true, Data = result };
            }
            catch (Exception ex)
            {
 
 
                return new WebResponseContent { Status = false, Message = "失败" + ex };
            }
        }
 
 
        public WebResponseContent PermissionView(int userId, string group)
        {
            try
            {
                // 1. 获取用户信息
                var user = BaseDal.QueryData(x => x.User_Id == userId).FirstOrDefault();
                var allTasks = _putakeRepository.QueryData();
 
                if (user == null)
                {
                    return new WebResponseContent { Status = false, Message = "用户不存在" };
                }
 
                string roleName = user.RoleName;
 
                // 2. 判断是否是超级管理员
                if (roleName.Contains("超级管理员"))
                {
                    // 超级管理员仍然要筛选指定 group
                    var adminTasks = allTasks.Where(x => x.Grouptype == group).ToList();
                    return new WebResponseContent { Status = true, Data = adminTasks, Message = "获取成功" };
                }
 
                // 3. 确定普通用户角色匹配的任务类型
                List<string> allowedGroups = new List<string>();
 
                if (roleName.Contains("地沟")) allowedGroups.Add("地沟");//如果添加进数组中
                if (roleName.Contains("电气")) allowedGroups.Add("电气");
                if (roleName.Contains("机械")) allowedGroups.Add("机械");
 
                if (allowedGroups.Count == 0)
                {
                    return new WebResponseContent { Status = false, Message = "您无权限查看任务" };
                }
 
                // 4. 普通用户只能看自己权限范围内的任务
                if (!allowedGroups.Contains(group))
                {
                    return new WebResponseContent { Status = false, Message = "您无权限查看该任务类别" };
                }
 
                var tasks = allTasks.Where(t => t.Grouptype == group).ToList();
 
                return new WebResponseContent { Status = true, Data = tasks, Message = "获取成功" };
            }
            catch (Exception ex)
            {
                return new WebResponseContent { Status = false, Message = "错误: " + ex.Message };
            }
        }
 
 
        /// <summary>
        /// 图片文件名
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public WebResponseContent SaveFiles(IFormCollection files)
        {
            if (files == null || files.Files.Count == 0)
                return new WebResponseContent { Status = false, Message = "请上传文件" };
 
            // 1. 确保存储目录存在
            string baseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "image");
            if (!Directory.Exists(baseDirectory))
                Directory.CreateDirectory(baseDirectory);
 
            try
            {
                var file = files.Files[0]; // 只处理第一个文件
                string fileName = file.FileName; // 直接使用前端的文件名
 
                string fullFilePath = Path.Combine(baseDirectory, fileName);
 
                // 2. 保存文件(如果存在,则覆盖)
                using (var stream = new FileStream(fullFilePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
 
                // 3. 返回文件名
                return new WebResponseContent { Status = true, Message = "文件上传成功", Data = fileName };
            }
            catch (Exception ex)
            {
                return new WebResponseContent { Status = false, Message = "上传文件失败:" + ex.Message };
            }
        }
 
        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="oldPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public WebResponseContent UpdatePwd(int id, string oldPwd, string newPwd)
        {
            WebResponseContent content = new WebResponseContent();
            oldPwd = oldPwd?.Trim();
            newPwd = newPwd?.Trim();
 
            try
            {
                if (string.IsNullOrEmpty(oldPwd)) return content.Error("旧密码不能为空");
                if (string.IsNullOrEmpty(newPwd)) return content.Error("新密码不能为空");
                if (newPwd.Length < 6) return content.Error("密码不能少于6位");
 
                // 获取用户当前密码
                string userCurrentPwd = BaseDal.QueryFirst(x => x.User_Id == id, s => s.UserPwd) ?? "";
 
                if (string.IsNullOrEmpty(userCurrentPwd)) return content.Error("用户不存在或密码未设置");
 
                //// 进行密码加密对比
                //string _oldPwd = oldPwd.EncryptDES(AppSecret.User);
                //if (_oldPwd != userCurrentPwd) return content.Error("旧密码不正确");
 
                // 生成新密码加密值
                string _newPwd = newPwd.EncryptDES(AppSecret.User);
                if (userCurrentPwd == _newPwd) return content.Error("新密码不能与旧密码相同");
 
                // 更新密码
                bool isUpdated = BaseDal.UpdateData(new Sys_User
                {
                    User_Id = id,
                    UserPwd = _newPwd,
                    LastModifyPwdDate = DateTime.Now
                }, new List<string>
        {
            nameof(Sys_User.LastModifyPwdDate),
            nameof(Sys_User.UserPwd)
        });
 
                if (!isUpdated)
                {
                    return content.Error("密码修改失败,请稍后重试");
                }
 
                return content.OK("密码修改成功", id);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"修改密码异常: {ex.Message}");
                return content.Error($"服务器错误: {ex.Message}");
            }
        }
 
        public WebResponseContent Upuserbase(UserDTO userDTO)
        {
            try
            {
                var user = BaseDal.QueryData(x => x.User_Id == userDTO.id).FirstOrDefault();
                if (user == null)
                {
                    return new WebResponseContent { Status = false, Message = "没找到该用户" };
                }
                user.UserTrueName = userDTO.usertruename;
                user.PhoneNo = userDTO.phone;
                user.HeadImageUrl = userDTO.files;
                BaseDal.UpdateData(user); // 确保更新到数据库
                return new WebResponseContent { Status = true, Data = user };
            }
            catch (Exception ex)
            {
 
                return new WebResponseContent { Status = false, Message = "失败:" + ex };
            }
 
        }
 
 
        /// <summary>
        /// 查看用户信息和人脸识别表
        /// </summary>
        /// <param name="paginationDTO"></param>
        /// <returns></returns>
        public WebResponseContent GetUserFace(PaginationDTO paginationDTO)
        {
            try
            {
                int totalCount = 0;
                var sys = Db.Queryable<Sys_User>();
                var face = _faceRecognitionRepository.Db.Queryable<Dt_FaceRecognition>();
 
                if (face == null)
                {
                    return new WebResponseContent { Status = false, Message = "数据为空" };
                }
 
                var query = sys.LeftJoin<Dt_FaceRecognition>((a, b) => a.Log_id == b.GroupID);
                if (!string.IsNullOrEmpty(paginationDTO.searchKeyword))
                {
                    query = query.Where((a, b) =>
                        a.UserName.Contains(paginationDTO.searchKeyword) ||
                        a.UserTrueName.Contains(paginationDTO.searchKeyword) ||
                        a.PhoneNo.Contains(paginationDTO.searchKeyword) ||
                        a.RoleName.Contains(paginationDTO.searchKeyword) ||
                        a.Role_Id.ToString().Contains(paginationDTO.searchKeyword)
                    );
                }
                if (paginationDTO.startDate.HasValue && paginationDTO.endDate.HasValue)
                {
                    query = query.Where((a, b) => a.CreateDate >= paginationDTO.startDate && a.CreateDate <= paginationDTO.endDate);
                }
 
                var result = query.Select((a, b) => new
                {
 
                    
                    a.Log_id,
                    a.User_Id,
                    a.UserName,
                    a.UserTrueName,
                    a.UserPwd,
                    a.PhoneNo,
                    a.Role_Id,
                    a.RoleName,
                    a.HeadImageUrl,
                    a.Enable,
                    a.CreateDate,
                    a.Face_token,
                    b.GroupID,
                }).ToPageList(paginationDTO.pageIndex, paginationDTO.pageSize, ref totalCount);
                return new WebResponseContent
                {
                    Status = true,
                    Data = new
                    {
                        TotalCount = totalCount,//总数
                        PageIndex = paginationDTO.pageIndex,//页数
                        PaseSize = paginationDTO.pageSize,//一页多少数据
                        Items = result//返回字段
                    }
 
                };
 
            }
            catch (Exception)
            {
 
                throw;
            }
        }
 
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="addUserDTO"></param>
        /// <returns></returns>
        public WebResponseContent AdduserData(AddUserDTO addUserDTO)
        {
            try
            {
                if (addUserDTO == null)
                {
                    return new WebResponseContent { Status = false, Message = "请求数据为空,可能是 JSON 解析失败" };
                }
 
                var list = BaseDal.QueryData(a => a.UserName == addUserDTO.username).FirstOrDefault();
                if (list != null)
                {
                    return new WebResponseContent { Status = false, Message = "账号重复,请重新录入" };
                }
                var face = _faceRecognitionRepository.QueryData().Select(x => x.GroupID).FirstOrDefault(); ;
                var baiduResult = BaiDuFaceHelper.AddUser(new BDUserInfo
                {
                    ImgPath = addUserDTO.path,
                    user_id = addUserDTO.username,
                    group_id = face // 这里应该填百度人脸库分组
                   // group_id = baiduResult.result.log_id
                });
 
 
                // 判断百度返回是否成功
                if (baiduResult == null || baiduResult.error_code != 0)
                {
                    return new WebResponseContent { Status = false, Data = "人脸注册失败:" + baiduResult.error_msg };
                  
 
                }
 
                // 创建用户数据
                var sys = new Sys_User
                {
                    UserName = addUserDTO.username,
                    UserTrueName=addUserDTO.usertruename,
                    HeadImageUrl=addUserDTO.path,
                    Log_id = baiduResult.log_id,
                    Face_token = baiduResult.result.face_token,
                    PhoneNo = addUserDTO.phoneno,
                    Role_Id = addUserDTO.roleid,
                    RoleName = addUserDTO.rolename,
                    Enable = addUserDTO.enable,
                    UserPwd= "j79rYYvCz4vdhcboB1Ausg==",
                    CreateDate=DateTime.Now
                };
                BaseDal.AddData(sys);
                return new WebResponseContent { Status = true, Data = sys };
            }
            catch (Exception ex)
            {
 
                return new WebResponseContent { Status = false, Message = "失败" + ex };
            }
 
        }
 
 
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="addUserDTO"></param>
        /// <returns></returns>
        public WebResponseContent UpuserData(AddUserDTO addUserDTO)
        {
            try
            {
                // 1. 查询用户
                var sys = BaseDal.QueryData(x => x.User_Id == addUserDTO.id).FirstOrDefault();
                if (sys == null)
                {
                    return new WebResponseContent { Status = false, Message = "没找到该用户" };
                }
 
                // 2. 查询人脸库分组 ID
                var faceGroupID = _faceRecognitionRepository.QueryData().Select(x => x.GroupID).FirstOrDefault();
 
                // 3. 判断是否需要更新人脸信息
                string faceToken = null;
                if (!string.IsNullOrEmpty(addUserDTO.path)) // 只有传了新图片,才更新人脸信息
                {
                    var baiduResult = BaiDuFaceHelper.AddUser(new BDUserInfo
                    {
                        ImgPath = addUserDTO.path,
                        user_id = addUserDTO.username,
                        group_id = faceGroupID // 这里应该填百度人脸库分组
                    });
 
                    // 4. 判断百度 API 是否成功
                    if (baiduResult == null || baiduResult.error_code != 0)
                    {
                        return new WebResponseContent { Status = false, Message = "该图片也存在,不要重复上传:" + baiduResult.error_msg };
                    }
 
                    // 5. 只有当上传了新图片并成功时,才更新这些字段
                    faceToken = baiduResult.result.face_token;
                    sys.Log_id = baiduResult.log_id;
                    sys.HeadImageUrl = addUserDTO.path;
                }
 
                // 6. 更新用户其他信息
                sys.UserName = addUserDTO.username;
                sys.UserTrueName = addUserDTO.usertruename;
                sys.Face_token = faceToken ?? sys.Face_token; // 只有当 faceToken 有值时才更新,否则保持原值
                sys.PhoneNo = addUserDTO.phoneno;
                sys.Role_Id = addUserDTO.roleid;
                sys.RoleName = addUserDTO.rolename;
                sys.Enable = addUserDTO.enable;
 
                // 7. 更新数据库
                BaseDal.UpdateData(sys);
 
                return new WebResponseContent { Status = true, Data = sys };
            }
            catch (Exception ex)
            {
                return new WebResponseContent { Status = false, Message = "失败:" + ex.Message };
            }
        }
 
 
 
 
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="deleteUserDTO"></param>
        /// <returns></returns>
        public WebResponseContent DeleteUserData(string account)
        {
            try
            {
 
                // 2. 查询人脸库分组 ID
                var faceGroupID = _faceRecognitionRepository.QueryData().Select(x => x.GroupID).FirstOrDefault();
 
                WIDESEAWCS_Common.DeleteUserImg deleteUserImg = new WIDESEAWCS_Common.DeleteUserImg();
                deleteUserImg.group_id = faceGroupID;
                deleteUserImg.user_id = account;
 
                string apiResult = BaiDuFaceHelper.DeleteUser(deleteUserImg);//只要给token和log_id
 
                // 2. 解析返回结果,判断删除是否成功
                dynamic resultObj = JsonConvert.DeserializeObject(apiResult);
                if (resultObj.error_code == 0)
                {
                   // 百度删除成功后,删除数据库中的用户
                    var user = BaseDal.QueryData(x=>x.UserName== account);
                    if (user != null)
                    {
                        BaseDal.DeleteData(user);
                    }
                    return WebResponseContent.Instance.OK("用户删除成功");
                }
                else
                {
                    return WebResponseContent.Instance.Error("百度 API 删除失败:" + resultObj.error_msg);
                }
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error("删除用户失败:" + ex.Message);
            }
        }
 
 
        public WebResponseContent SaveFaceFiles(IFormCollection files)
        {
            if (files == null || files.Files.Count == 0)
                return new WebResponseContent { Status = false, Message = "请上传文件" };
 
            // 1. 确保存储目录存在
            string baseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "UploadfaceImage");
            if (!Directory.Exists(baseDirectory))
                Directory.CreateDirectory(baseDirectory);
 
            try
            {
                var file = files.Files[0]; // 只处理第一个文件
                string fileName = file.FileName; // 直接使用前端的文件名
 
                string fullFilePath = Path.Combine(baseDirectory, fileName);
 
                // 2. 保存文件(如果存在,则覆盖)
                using (var stream = new FileStream(fullFilePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
 
                // 3. 返回文件名
                return new WebResponseContent { Status = true, Message = "文件上传成功", Data = fileName };
            }
            catch (Exception ex)
            {
                return new WebResponseContent { Status = false, Message = "上传文件失败:" + ex.Message };
            }
        }
 
 
        /// <summary>
        /// 删除数据库中没有使用的图片
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public WebResponseContent CleanUnusedImages()
        {
            try
            {
                // 获取文件的完整路径
                string pathimage = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "image");
 
                // 如果文件夹不存在,返回错误信息
                if (!Directory.Exists(pathimage))
                {
                    return new WebResponseContent { Status = false, Message = "图片文件夹不存在" };
                }
 
                // **使用 HashSet 提高查找效率**
                var userImageSet = BaseDal.QueryData(x => !string.IsNullOrEmpty(x.HeadImageUrl))
                                          .Select(x => x.HeadImageUrl)
                                          .ToHashSet(); // **提升查询速度**
 
                // 获取文件夹中的所有图片文件(文件名)
                var imageFiles = Directory.GetFiles(pathimage)
                                          .Select(Path.GetFileName)
                                          .ToList();
 
                int deletedCount = 0;
                foreach (var file in imageFiles)
                {
                    // **HashSet 查询 O(1)**
                    if (!userImageSet.Contains(file))
                    {
                        string filePath = Path.Combine(pathimage, file);
                        try
                        {
                            File.Delete(filePath);
                            deletedCount++;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"无法删除文件 {file}: {ex.Message}");
                        }
                    }
                }
 
                return new WebResponseContent { Status = true, Message = $"清理完成,删除了 {deletedCount} 张未使用的图片" };
            }
            catch (Exception ex)
            {
                return new WebResponseContent { Status = false, Message = $"清理失败: {ex.Message}" };
            }
        }
 
    }
}