kyy
6 天以前 f476ec010c22cd4e3c6a119eea035cbf4594bfbb
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
namespace MES.Service.service.BasicData;
 
using MES.Service.DB;
using MES.Service.Dto.webApi;
using MES.Service.Modes;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
 
public class MesStaffManager : Repository<MesStaff>
{
    // 保存单个员工记录
    public bool Save(ErpStaff unit)
    {
        if (unit == null) throw new ArgumentNullException(nameof(unit));
 
        var entity = GetMesStaff(unit);
        //var mesStaffPositionLink = GetMesStaffPositionLink(unit);
        List<MesStaffPositionLink> mesStaffPositionLink = null;
 
        return UseTransaction(db =>
        {
            switch (unit.Type)
            {
                case "0": return UpdateStaffStatus(db, entity.Id, "A") ? 1 : 0;
                case "1": return UpdateStaffStatus(db, entity.Id, "B") ? 1 : 0;
                case "2":
                case "4":
                    // return InsertOrUpdateStaff(db,
                    //     new List<SysUser> { sysUser },
                    //     new List<MesStaff> { entity }, mesStaffPositionLink)
                    //     ? 1
                    //     : 0;
                    return InsertUser(db, entity) ? 1 : 0;
                case "3":
                    // return DeleteStaff(db, new List<SysUser> { sysUser },
                    //     new List<MesStaff> { entity })
                    //     ? 1
                    //     : 0;
                    return DeleteStaff(db, entity) ? 1 : 0;
                default: throw new ArgumentException($"不支持的类型: {unit.Type}");
            }
        }) > 0;
    }
 
    /// <summary>
    /// 生成新的ID,确保不重复
    /// </summary>
    private decimal GenerateNewId()
    {
        // 处理空表的情况,从1开始
        var maxId = Db.Queryable<MesStaff>().Max(x => (decimal?)x.Id) ?? 0;
        var newId = maxId + 1;
        
        // 双重检查,确保生成的ID不存在
        while (Db.Queryable<MesStaff>().Where(x => x.Id == newId).Any())
        {
            newId++;
        }
        
        return newId;
    }
 
    private bool InsertUser(SqlSugarScope db, MesStaff entity)
    {
        if (entity.Id == 0)
        {
            // 新增情况:生成新ID并插入
            var newId = GenerateNewId();
            entity.Id = newId;
            
            var sysUser = GetUser(entity);
            var staffInsertId = db.Insertable(entity).ExecuteReturnIdentity();
            
            if (staffInsertId > 0)
            {
                sysUser.StaffId = staffInsertId.ToString();
                return db.Insertable(sysUser).ExecuteCommand() > 0;
            }
            return false;
        }
        else
        {
            // 更新情况:删除后重新插入,保持原有ID
            var originalId = entity.Id;
            
            // 先删除原记录(如果存在)
            db.Deleteable<MesStaff>().Where(s => s.Id == originalId).ExecuteCommand();
            db.Deleteable<SysUser>().Where(s => s.StaffId == originalId.ToString()).ExecuteCommand();
            
            // 重新插入,保持原有ID
            entity.Id = originalId;
            var sysUser = GetUser(entity);
            
            var staffInsert = db.Insertable(entity).ExecuteCommand();
            if (staffInsert > 0)
            {
                return db.Insertable(sysUser).ExecuteCommand() > 0;
            }
            return false;
        }
    }
 
    private bool DeleteStaff(SqlSugarScope db, MesStaff entity)
    {
        var executeCommand = db.Deleteable<MesStaff>()
            .Where(s => s.Id == entity.Id)
            .ExecuteCommand();
 
        db.Deleteable<SysUser>()
            .Where(s => s.StaffId == entity.Id.ToString())
            .ExecuteCommand();
 
        return executeCommand > 0;
    }
 
    // 保存多个员工记录
    public bool SaveList(List<ErpStaff> departments)
    {
        if (departments == null || !departments.Any())
        {
            Console.WriteLine("警告: 传入的员工列表为空");
            return false;
        }
 
        // 逐条处理,全部成功才返回true(事务内批量处理更优,此处保持原有逻辑)
        var result = departments.Select(Save).ToList();
        return result.All(b => b);
    }
 
    // 插入或更新员工(批量版本)
    private bool InsertOrUpdateBatch(SqlSugarScope db, List<SysUser> sysUsers,
        List<MesStaff> entities, List<MesStaffPositionLink> positionLinks)
    {
        if (!sysUsers.Any() || !entities.Any())
        {
            Console.WriteLine("警告: SysUser或MesStaff列表为空,跳过插入操作");
            return false;
        }
 
        try
        {
            // 1. 批量插入 SysUser(仅新增)
            var newSysUsers = sysUsers
                .Where(u =>
                    !db.Queryable<SysUser>().Any(e => e.StaffId == u.StaffId))
                .ToList();
 
            if (newSysUsers.Any())
            {
                Console.WriteLine($"准备插入 {newSysUsers.Count} 个新SysUser");
                var insertCount = db.Insertable(newSysUsers).ExecuteCommand();
 
                if (insertCount != newSysUsers.Count)
                {
                    throw new InvalidOperationException(
                        $"SysUser插入失败,期望插入 {newSysUsers.Count} 条,实际插入 {insertCount} 条");
                }
 
                Console.WriteLine($"成功插入 {insertCount} 个SysUser");
            }
 
            // 2. 批量删除并插入 MesStaff
            var staffIds = entities.Select(e => e.Id).ToList();
            db.Deleteable<MesStaff>().Where(s => staffIds.Contains(s.Id))
                .ExecuteCommand();
 
            var staffInsertCount = db.Insertable(entities).IgnoreColumns(true)
                .ExecuteCommand();
            if (staffInsertCount != entities.Count)
            {
                throw new InvalidOperationException(
                    $"MesStaff插入失败,期望插入 {entities.Count} 条,实际插入 {staffInsertCount} 条");
            }
 
            // 3. 处理岗位关联(如果有)
            if (positionLinks != null && positionLinks.Any())
            {
                var positionStaffIds = positionLinks.Select(p => p.StaffId)
                    .Distinct().ToList();
                db.Deleteable<MesStaffPositionLink>()
                    .Where(p => positionStaffIds.Contains(p.StaffId))
                    .ExecuteCommand();
 
                var positionInsertCount = db.Insertable(positionLinks)
                    .PageSize(500).IgnoreColumnsNull().ExecuteCommand();
                if (positionInsertCount != positionLinks.Count)
                {
                    throw new InvalidOperationException(
                        $"MesStaffPositionLink插入失败,期望插入 {positionLinks.Count} 条,实际插入 {positionInsertCount} 条");
                }
            }
 
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"批量插入/更新失败: {ex.Message}");
            Console.WriteLine($"SQL: {db.Ado.SqlExecutionTime}");
 
            // 记录完整的错误堆栈
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
 
            // 记录失败的数据
            if (sysUsers != null && sysUsers.Any())
            {
                Console.WriteLine(
                    $"失败的SysUser数据: {string.Join(", ", sysUsers.Select(u => u.Account))}");
            }
 
            throw;
        }
    }
 
    // 插入或更新员工(兼容旧版本,调用批量方法)
    private bool InsertOrUpdateStaff(SqlSugarScope db, List<SysUser> sysUsers,
        List<MesStaff> entities, List<MesStaffPositionLink> positionLinks)
    {
        return InsertOrUpdateBatch(db, sysUsers, entities, positionLinks);
    }
 
    // 批量更新员工状态
    private bool UpdateStaffStatusBatch(SqlSugarScope db,
        List<MesStaff> staffList, string status)
    {
        if (!staffList.Any())
        {
            Console.WriteLine("警告: 员工列表为空,跳过状态更新");
            return false;
        }
 
        var ids = staffList.Select(s => s.Id).ToList();
        var updateCount = db.Updateable<MesStaff>()
            .SetColumns(s => s.FforbidStatus == status)
            .Where(s => ids.Contains(s.Id))
            .ExecuteCommand();
 
        if (updateCount <= 0)
        {
            throw new InvalidOperationException(
                $"更新员工状态失败,状态: {status},影响行数: {updateCount}");
        }
 
        Console.WriteLine($"成功更新 {updateCount} 个员工状态为 {status}");
        return true;
    }
 
    // 批量删除员工
    private bool DeleteStaffBatch(SqlSugarScope db, List<SysUser> sysUsers,
        List<MesStaff> entities)
    {
        if (!sysUsers.Any() || !entities.Any())
        {
            Console.WriteLine("警告: SysUser或MesStaff列表为空,跳过删除操作");
            return false;
        }
 
        try
        {
            // 1. 删除 SysUser
            var userAccounts = sysUsers.Select(u => u.Account).ToList();
            var userDeleteCount = db.Deleteable<SysUser>()
                .Where(u => userAccounts.Contains(u.Account)).ExecuteCommand();
 
            // 2. 删除 MesStaff
            var staffIds = entities.Select(e => e.Id).ToList();
            var staffDeleteCount = db.Deleteable<MesStaff>()
                .Where(s => staffIds.Contains(s.Id)).ExecuteCommand();
 
            // 3. 删除岗位关联 :使用Any方法(推荐)
            db.Deleteable<MesStaffPositionLink>()
                .Where(p => staffIds.Any(id => id == p.StaffId))
                .ExecuteCommand();
 
            Console.WriteLine(
                $"成功删除 {userDeleteCount} 个SysUser和 {staffDeleteCount} 个MesStaff");
            return userDeleteCount > 0 && staffDeleteCount > 0;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"批量删除失败: {ex.Message}");
            Console.WriteLine($"SQL: {db.Ado.SqlExecutionTime}");
            throw;
        }
    }
 
    // 更新员工状态
    private bool UpdateStaffStatus(SqlSugarScope db, decimal? staffId,
        string status)
    {
        var result = db.Updateable<MesStaff>()
            .SetColumns(s => s.FforbidStatus == status)
            .Where(s => s.Id == staffId)
            .ExecuteCommand();
 
        if (result <= 0)
        {
            throw new InvalidOperationException(
                $"更新员工状态失败,员工ID: {staffId},状态: {status}");
        }
 
        return true;
    }
 
    // 删除员工(调用批量方法)
    private bool DeleteStaff(SqlSugarScope db, List<SysUser> sysUsers,
        List<MesStaff> entities)
    {
        return DeleteStaffBatch(db, sysUsers, entities);
    }
 
    // 将 ErpStaff 对象转换为 MesStaff 对象
    private MesStaff GetMesStaff(ErpStaff staff)
    {
        if (staff == null) throw new ArgumentNullException(nameof(staff));
 
        try
        {
            var entity = new MesStaff
            {
                Guid = Guid.NewGuid(),
                StaffNo = staff.FStaffNumber,
                StaffName = staff.FName,
                DepartmentName = staff.FPostDept,
                PositionCode = staff.FPostId,
                PhoneNumber = staff.FMobile,
                Remark = staff.FDescription,
                FforbidStatus = staff.FForbidStatus,
                FSubsidiary = string.IsNullOrEmpty(staff.FUseOrgId)
                    ? "1"
                    : staff.FUseOrgId,
                Fumbrella = string.IsNullOrEmpty(staff.FCreateOrgId)
                    ? "1"
                    : staff.FCreateOrgId,
                CreateDate = DateTime.Now,
                LastupdateDate = DateTime.Now,
                Type = staff.Type
            };
 
            if (!string.IsNullOrEmpty(staff.FStaffStartDate))
            {
                entity.StartDate = DateTime.ParseExact(staff.FStaffStartDate,
                    "yyyy-MM-dd HH:mm:ss", null);
            }
 
            // 查找是否已存在相同员工编码的记录
            var existingStaff = Db.Queryable<MesStaff>()
                .Where(s => s.StaffNo == entity.StaffNo)
                .First();
 
            if (existingStaff != null)
            {
                // 如果存在,使用现有的ID,后续将删除后重新插入
                entity.Id = existingStaff.Id;
            }
            else
            {
                // 如果不存在,设为0,InsertUser方法将生成新ID
                entity.Id = 0;
            }
 
            return entity;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"转换ErpStaff到MesStaff失败: {ex.Message}");
            Console.WriteLine(
                $"输入数据: {staff.Id}, {staff.FStaffNumber}, {staff.FName}");
            throw;
        }
    }
 
    // 将 ErpStaff 对象转换为 SysUser 对象
    private SysUser GetUser(MesStaff entity)
    {
        if (entity == null) throw new ArgumentNullException(nameof(entity));
 
        try
        {
            return new SysUser
            {
                StaffId = entity.Id.ToString(), // 确保Sid与员工ID一致
                IsStatus = true,
                Account = entity.StaffNo,
                UserName = entity.StaffName,
                Password = "E1ADC3949BA59ABBE56E057F2F883E", // 初始密码
                DepartNo = entity.DepartmentName,
                CreateTime = DateTime.Now
            };
        }
        catch (Exception ex)
        {
            throw new NotImplementedException(ex.Message);
        }
    }
 
    // 获取员工岗位关联列表
    private List<MesStaffPositionLink> GetMesStaffPositionLink(ErpStaff staff)
    {
        if (staff == null) return new List<MesStaffPositionLink>();
 
        try
        {
            var staffDetails = new List<MesStaffPositionLink>();
 
            if (staff.ErpStaffDetails != null &&
                staff.ErpStaffDetails.Count > 0)
            {
                staffDetails = staff.ErpStaffDetails.Select(staffDetail =>
                    new MesStaffPositionLink
                    {
                        StaffId = Convert.ToDecimal(staff.Id),
                        PositionId =
                            string.IsNullOrEmpty(
                                staffDetail.fPostId?.ToString())
                                ? null
                                : Convert.ToDecimal(staffDetail.fPostId),
                        FPostDeptId =
                            string.IsNullOrEmpty(staffDetail.fPostDeptid
                                ?.ToString())
                                ? null
                                : Convert.ToDecimal(staffDetail.fPostDeptid),
                        FStaffStartDate =
                            string.IsNullOrEmpty(staffDetail.fStaffStartDate
                                ?.ToString())
                                ? null
                                : DateTime.ParseExact(
                                    staffDetail.fStaffStartDate,
                                    "yyyy-MM-dd HH:mm:ss", null)
                    }).ToList();
            }
 
            return staffDetails;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"转换岗位关联数据失败: {ex.Message}");
            Console.WriteLine($"员工ID: {staff.Id}");
            throw;
        }
    }
}