快乐的昕的电脑
9 天以前 f311876e3a1341c4051e0d8eb45032fd35407f3c
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
using MES.Service.DB;
using MES.Service.Dto.webApi;
using MES.Service.Modes;
using SqlSugar;
 
namespace MES.Service.service.BasicData;
/// <summary>
/// 员工信息
/// </summary>
public class MesStaffManager : Repository<MesStaff>
{
    // Save 方法用于保存单个员工记录,根据类型执行不同的操作
    public bool Save(ErpStaff unit)
    {
        var entity = GetMesStaff(unit); // 将 ErpStaff 转换为 MesStaff
        var sysUser = GetUser(unit); // 获取 SysUser 实例
 
        return UseTransaction(db =>
        {
            switch (unit.Type)
            {
                case "0":
                    if (UpdateStaffStatus(db, entity.Id, "A")) // 启用员工
                        return 1;
                    break;
                case "1":
                    if (UpdateStaffStatus(db, entity.Id, "B")) // 禁用员工
                        return 1;
                    break;
                case "2":
                case "4":
                    if (InsertOrUpdateStaff(db, sysUser, entity)) // 插入或更新员工
                        return 1;
                    break;
                case "3":
                    if (DeleteStaff(db, sysUser, entity.Id)) // 删除员工
                        return 1;
                    break;
                default:
                    throw new ArgumentNullException(
                        $"type没有{unit.Type}这个类型的参数");
            }
 
            throw new NotImplementedException("操作失败");
        }) > 0;
    }
 
    // 更新员工状态的方法
    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)
            return true;
 
        throw new NotImplementedException(status == "A" ? "启用失败" : "禁用失败");
    }
 
    /// <summary>
    /// 同步物料信息new_0/4
    /// </summary>
    /// <param name="db"></param>
    /// <param name="entity"></param>
    /// <returns></returns>
    private bool InsertOrUpdateStaff(SqlSugarScope db, SysUser sysUser, MesStaff entity)
    {
        // 先确保用户账号存在
        var exists = db.Queryable<SysUser>().Any(u => u.Account == sysUser.Account);
        if (!exists)
        {
            var insertUser = db.Insertable(sysUser).ExecuteCommand();
            if (insertUser <= 0) return false;
        }
 
        if (entity.Id == 0)
        {
            // 新增情况:生成新ID并插入
            var newId = GenerateNewId();
            entity.Id = newId;
            return db.Insertable(entity).ExecuteCommand() > 0;
        }
        else
        {
            // 更新情况:删除后重新插入,保持原有ID
            var originalId = entity.Id;
 
            // 先删除原记录(如果存在)
            db.Deleteable<MesStaff>().Where(s => s.Id == originalId).ExecuteCommand();
 
            // 重新插入,保持原有ID
            entity.Id = originalId;
            return db.Insertable(entity).ExecuteCommand() > 0;
        }
    }
 
    // 插入或更新员工的方法
    //private bool InsertOrUpdateStaff(SqlSugarScope db, SysUser sysUser,MesStaff entity)
    //{
 
    //    var exists = db.Queryable<SysUser>().Any(u => u.Account == sysUser.Account);
    //    if (!exists)
    //    {
    //        var insertUser = db.Insertable(sysUser).ExecuteCommand();
    //        if (insertUser <= 0) return false;
    //    }
 
    //    //db.Deleteable<SysUser>()
    //    //    .Where(s => s.Account == sysUser.Account).ExecuteCommand();
 
    //    db.Deleteable<MesStaff>()
    //        .Where(s => s.Id == entity.Id).ExecuteCommand();
 
 
 
    //    var insertStaff = db.Insertable(entity).ExecuteCommand();
    //    return insertStaff > 0;
    //}
 
    // 删除员工的方法
    private bool DeleteStaff(SqlSugarScope db, SysUser sysUser, decimal staffId)
    {
        var deleteUser = db.Deleteable<SysUser>()
            .Where(s => s.Account == sysUser.Account).ExecuteCommand();
        if (deleteUser <= 0) throw new NotImplementedException("反审核失败");
        var deleteStaff =
            db.Deleteable<MesStaff>()
                .Where(s => s.Id == staffId).ExecuteCommand();
        if (deleteStaff > 0)
            return true;
 
        throw new NotImplementedException("反审核失败");
    }
 
    /// <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;
    }
 
    // 将 ErpStaff 对象转换为 MesStaff 对象的方法
    private MesStaff GetMesStaff(ErpStaff staff)
    {
        // 查找是否已存在相同编码的记录。
        var existingCustomer = Db.Queryable<MesStaff>()
            .Where(s => s.StaffNo == staff.FStaffNumber)
            .First();
 
        var entity = new MesStaff
        {
            // 如果存在,使用现有的ID,后续将删除后重新插入
            // 如果不存在,设为0,InsertOrUpdate方法将生成新ID
            Id = existingCustomer?.Id ?? 0,
            //Id = Convert.ToDecimal(staff.Id),
            StaffNo = staff.FStaffNumber,
            StaffName = staff.FName,
            DepartmentNo = staff.FPostDeptNo,//部门编码
            DepartmentName = staff.FPostDept,//部门名称
            PositionCode = staff.FPost,//岗位编码
            PositionName = staff.FPostId,//岗位名称
            PhoneNumber = staff.FMobile,
            Remark = staff.FDescription,
            FforbidStatus = staff.FForbidStatus,
            //FSubsidiary = staff.FUseOrgId,
            //Fumbrella = staff.FCreateOrgId,
            // 如果存在,使用现有的CreateDate,后续将删除后重新插入
            // 如果不存在,设为当前时间
            CreateDate = existingCustomer?.CreateDate ?? DateTime.Now,
            //CreateDate = DateTime.Now,
            LastupdateDate = DateTime.Now,
            Type = staff.Type,
 
            FSubsidiary = string.IsNullOrEmpty(staff.FUseOrgId) ? "1" : staff.FUseOrgId,
            Fumbrella = string.IsNullOrEmpty(staff.FCreateOrgId) ? "1" : staff.FCreateOrgId,
        };
 
        if (staff.FStaffStartDate != null)
            entity.StartDate = DateTime.ParseExact(staff.FStaffStartDate,
                "yyyy-MM-dd HH:mm:ss", null);
 
        // ERP: 0=未禁用, 1=禁用
        // MES: A=未禁用, B=禁用
        if (string.IsNullOrEmpty(staff.FForbidStatus))
        {
            entity.FforbidStatus = "A";
        }
        else
        {
            //我期望的值是A=否,B=是
            //实际给我的值是0或1,我希望为我转换从A和B的方式
            entity.FforbidStatus = staff.FForbidStatus == "1" ? "B" : "A";
        }
 
        return entity;
    }
 
    // 将 ErpStaff 对象转换为 SysUser 对象的方法
    private SysUser GetUser(ErpStaff staff)
    {
        return new SysUser
        {
            IsStatus = true,
            Account = staff.FStaffNumber,
            UserName = staff.FName,
            Password = "248436591099D5B8925DE067E9B898CE", // 初始密码
            DepartNo = staff.FPostDept,
            Type = staff.Type,
            CreateTime = DateTime.Now
        };
    }
 
    // SaveList 方法用于保存多个员工记录,根据类型批量执行不同的操作
    public bool SaveList(List<ErpStaff> departments)
    {
        var list = new List<MesStaff>();
        var userList = new List<SysUser>();
 
        departments.ForEach(s =>
        {
            var entity = GetMesStaff(s);
            entity.Type = s.Type;
            list.Add(entity);
 
            var sysUser = GetUser(s);
            sysUser.Type = s.Type;
            userList.Add(sysUser);
        });
 
        var groupBy = list.GroupBy(s => s.Type)
            .ToDictionary(g => g.Key, g => g.ToList());
        return UseTransaction(db =>
        {
            foreach (var staffGroup in groupBy)
                switch (staffGroup.Key)
                {
                    case "0":
                        if (!UpdateStaffStatusBatch(db, staffGroup.Value,
                                "A")) // 批量启用员工
                            throw new NotImplementedException("启用失败");
                        break;
                    case "1":
                        if (!UpdateStaffStatusBatch(db, staffGroup.Value,
                                "B")) // 批量禁用员工
                            throw new NotImplementedException("禁用失败");
                        break;
                    case "3":
                        if (!DeleteStaffBatch(db, userList,
                                staffGroup.Value)) // 批量删除员工
                            throw new NotImplementedException("删除失败");
                        break;
                    case "2":
                    case "4":
                        if (!InsertOrUpdateBatch(db, userList,
                                staffGroup.Value)) // 批量插入或更新员工
                            throw new NotImplementedException("同步失败");
                        break;
                    default:
                        throw new ArgumentNullException(
                            $"type没有{staffGroup.Key}这个类型的参数");
                }
 
            return 1;
        }) > 0;
    }
 
    // 批量更新员工状态的方法
    private bool UpdateStaffStatusBatch(SqlSugarScope db,
        List<MesStaff> staffList, string status)
    {
        var ids = staffList.Select(it => it.Id).ToArray();
        var result = db.Updateable<MesStaff>()
            .SetColumns(s => s.FforbidStatus == status)
            .Where(s => ids.Contains(s.Id)).ExecuteCommand();
 
        if (result > 0)
            return true;
 
        throw new NotImplementedException(status == "A" ? "启用失败" : "禁用失败");
    }
 
    // 批量插入员工的方法
    private bool InsertStaffBatch(SqlSugarScope db, List<SysUser> userList,
        List<MesStaff> staffList)
    {
        var userInsert = userList.FindAll(s => s.Type == "2");
        var executeCommand = db.Insertable(userInsert).ExecuteCommand();
        if (executeCommand <= 0) throw new ArgumentNullException("审核失败");
        if (db.Insertable(staffList).ExecuteCommand() > 0)
            return true;
 
        throw new ArgumentNullException("审核失败");
    }
 
    // 批量删除员工的方法
    private bool DeleteStaffBatch(SqlSugarScope db, List<SysUser> userList,
        List<MesStaff> staffList)
    {
        var sid = userList.FindAll(s => s.Type == "3").Select(s => s.Account)
            .ToArray();
        var result = db.Deleteable<SysUser>()
            .Where(s => sid.Contains(s.Account)).ExecuteCommand();
 
        if (result <= 0) throw new ArgumentNullException("反审核失败");
        var ids = staffList.Select(it => it.Id).ToArray();
        if (db.Deleteable<MesStaff>()
                .Where(s => ids.Contains(s.Id)).ExecuteCommand() > 0)
            return true;
 
        throw new ArgumentNullException("反审核失败");
    }
 
    // 批量插入或更新员工的方法
    private bool InsertOrUpdateBatch(SqlSugarScope db, List<SysUser> userList,
        List<MesStaff> staffList)
    {
        return !(from sysUser in userList
            let entity = staffList.First(s => s.StaffNo == sysUser.Account)
            where !InsertOrUpdateStaff(db, sysUser, entity)
            select sysUser).Any();
    }
}