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 { // 保存单个员工记录 public bool Save(ErpStaff unit) { if (unit == null) throw new ArgumentNullException(nameof(unit)); var entity = GetMesStaff(unit); //var mesStaffPositionLink = GetMesStaffPositionLink(unit); List 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 }, // new List { entity }, mesStaffPositionLink) // ? 1 // : 0; return InsertUser(db, entity) ? 1 : 0; case "3": // return DeleteStaff(db, new List { sysUser }, // new List { entity }) // ? 1 // : 0; return DeleteStaff(db, entity) ? 1 : 0; default: throw new ArgumentException($"不支持的类型: {unit.Type}"); } }) > 0; } /// /// 生成新的ID,确保不重复 /// private decimal GenerateNewId() { // 处理空表的情况,从1开始 var maxId = Db.Queryable().Max(x => (decimal?)x.Id) ?? 0; var newId = maxId + 1; // 双重检查,确保生成的ID不存在 while (Db.Queryable().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().Where(s => s.Id == originalId).ExecuteCommand(); db.Deleteable().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() .Where(s => s.Id == entity.Id) .ExecuteCommand(); db.Deleteable() .Where(s => s.StaffId == entity.Id.ToString()) .ExecuteCommand(); return executeCommand > 0; } // 保存多个员工记录 public bool SaveList(List 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 sysUsers, List entities, List positionLinks) { if (!sysUsers.Any() || !entities.Any()) { Console.WriteLine("警告: SysUser或MesStaff列表为空,跳过插入操作"); return false; } try { // 1. 批量插入 SysUser(仅新增) var newSysUsers = sysUsers .Where(u => !db.Queryable().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().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() .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 sysUsers, List entities, List positionLinks) { return InsertOrUpdateBatch(db, sysUsers, entities, positionLinks); } // 批量更新员工状态 private bool UpdateStaffStatusBatch(SqlSugarScope db, List staffList, string status) { if (!staffList.Any()) { Console.WriteLine("警告: 员工列表为空,跳过状态更新"); return false; } var ids = staffList.Select(s => s.Id).ToList(); var updateCount = db.Updateable() .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 sysUsers, List 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() .Where(u => userAccounts.Contains(u.Account)).ExecuteCommand(); // 2. 删除 MesStaff var staffIds = entities.Select(e => e.Id).ToList(); var staffDeleteCount = db.Deleteable() .Where(s => staffIds.Contains(s.Id)).ExecuteCommand(); // 3. 删除岗位关联 :使用Any方法(推荐) db.Deleteable() .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() .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 sysUsers, List 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() .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 GetMesStaffPositionLink(ErpStaff staff) { if (staff == null) return new List(); try { var staffDetails = new List(); 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; } } }