yanjinhui
2025-03-19 1067a1298d2d12c217dd94997b6820d879ae5400
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
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;
 
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;
 
        public Sys_UserService(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;
        }
 
        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
 
                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;
        }
 
        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};
            }
 
        }
    }
}