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
using MES.Service.DB;
using MES.Service.Dto.webApi;
using MES.Service.Modes;
using MES.Service.util;
using SqlSugar;
 
namespace MES.Service.service;
 
public class WomcaaManager : Repository<Womcaa>
{
    //当前类已经继承了 Repository 增、删、查、改的方法
 
    //这里面写的代码不会给覆盖,如果要重新生成请删除 WomcaaManager.cs
 
    private readonly WomcabManager _womcabManager = new();
 
    public bool SaveList(List<ErpWOM> rohIns)
    {
        var result = rohIns.Select(Save).ToList();
        return result.All(b => b);
    }
 
    public bool Save(ErpWOM wom)
    {
        var womErpCaa = wom.ErpCaa;
 
        var mesWomcaa = MapErpCAAtoWomcaa(womErpCaa, wom.ErpCabs[0].FBillNo);
        var mesWomcabs =
            MapErpCABtoWomcab(wom.ErpCabs);
 
        return UseTransaction(db =>
        {
            switch (womErpCaa.Type)
            {
                case "3":
                    return SaveOrUpdateData(db, mesWomcaa, mesWomcabs,womErpCaa.Type)
                        ? 1
                        : 0;
                    //return UpdateData(db, mesWomcaa, mesWomcabs) ? 1 : 0; //反审核不删除,做update。
                case "2":
                case "4":
                //kyy 2024-09-13 变更
                case "5":
                    return SaveOrUpdateData(db, mesWomcaa, mesWomcabs,womErpCaa.Type)
                        ? 1
                        : 0;
                default:
                    throw new NotImplementedException(
                        $"type没有{womErpCaa.Type}这个类型");
            }
        }) > 0;
    }
 
    private bool SaveOrUpdateData(SqlSugarScope db, Womcaa mesWomcaa,
        List<Womcab> mesWomcabs, string type)
    {
        if(type == "3" || (mesWomcaa.DocumentStatus != null && mesWomcaa.DocumentStatus != "C"))
        {
            mesWomcaa.Typea = "3";  // 新增字段赋值
            mesWomcaa.Caa001 = mesWomcaa.Caa001 + "F" + mesWomcaa.Erpid.ToString();
        }
 
 
 
        if (StringUtil.CheckGuid(mesWomcaa.Guid))
            base.DeleteById(mesWomcaa.Guid);
 
        //if (mesWomcabs.Count > 0)
        //    db.Deleteable<Womcab>()
        //        .Where(s => s.Pid == mesWomcaa.Erpid).ExecuteCommand();
 
        // 在插入 mesWomcabs 之前,先删除所有 Guid 已存在的记录
        //var guids = mesWomcabs.Select(x => x.Guid).ToList();
        //if (guids.Count > 0)
        //{
        //    db.Deleteable<Womcab>().In(x => x.Guid, guids).ExecuteCommand();
        //}
        if (mesWomcabs.Count > 0)
        {
            // 先按 Pid 删除
            db.Deleteable<Womcab>()
                .Where(s => s.Pid == mesWomcaa.Erpid).ExecuteCommand();
 
            //    // 再按 Guid 删除,彻底避免主键冲突
            //    var guids = mesWomcabs.Select(x => x.Guid).ToList();
            //    db.Deleteable<Womcab>().In(x => x.Guid, guids).ExecuteCommand();
        }
 
        //// 检查 Guid 是否唯一
        //if (mesWomcabs.Select(x => x.Guid).Distinct().Count() != mesWomcabs.Count)
        //    throw new Exception("即将插入的Womcab数据中存在重复的Guid,请检查数据生成逻辑。");
 
        //单条插入忽略空字段
        var orUpdate = db.Insertable(mesWomcaa)
            .IgnoreColumns(true).ExecuteCommand() > 0;
 
        //批量插入忽略空字段
        var baOrUpdate = db.Insertable(mesWomcabs).PageSize(1)
            .IgnoreColumnsNull()
            .ExecuteCommand() > 0;
 
        // if (orUpdate && baOrUpdate) 
        // throw new NotImplementedException("插入或更新失败");
 
        if (orUpdate && baOrUpdate) 
        {
            // 调用存储过程更新用料清单
            db.Ado.ExecuteCommand("exec [dbo].[prc_update_womdab] @outMsg output,@outSum output,@inEdtUserGuid,@inCaaGuid",
                new {
                    outMsg = (string)null,  // 输出参数
                    outSum = (int?)null,     // 输出参数
                    inEdtUserGuid = new Guid("11111111-1111-1111-1111-111111111111"),
                    inCaaGuid = new Guid(mesWomcaa.Guid.ToString())
                });
            return true;
        }
        throw new NotImplementedException("插入或更新失败");
        
 
    }
 
    private bool UpdateData(SqlSugarScope db, Womcaa mesWomcaa,
        List<Womcab> mesWomcabs)
    {
        //throw new NotImplementedException("存在下有单据,不允许反审");
 
        var decimals = mesWomcabs.Select(s => s.Guid).ToArray();
        var update = base.DeleteById(mesWomcaa.Guid);
        var insertOrUpdate = db
            .Deleteable<Womcab>().In(decimals)
            .ExecuteCommand() > 0;
 
        if (update && insertOrUpdate) return true;
        throw new NotImplementedException("更新失败");
    }
 
    private Womcaa MapErpCAAtoWomcaa(ErpCAA dto,string PPBOMNO)
    {
        var entity = new Womcaa
        {
            Erpid = Convert.ToInt32(dto.Id), ///     ERPID
 
            SrcBillType = dto.FSrcBillType, ///     工单单别
            Caa001=dto.FBillNo, ///     工单单号
            //Caa001 = PPBOMNO, ///     单号
            Caa021 = dto.FWorkShopID0, ///     工作中心
            //Caa021 = dto.FWorkShopID, ///     工作车间
            RoutingId = dto.FRoutingId, ///     工艺路线
            WorkShopId = dto.FREMWorkShopId, ///     产线
            DepotCode = dto.FStockId, ///     仓库
            CreateDate = dto.FDate, ///     单据日期
 
            Caa004 = dto.FBILLTYPE, ///     单据类型
            Caa023 = dto.FStatus, ///     状态 完工,未完工
            Caa006 = dto.FMaterialId, ///     产品编码
            Caa009 = dto.FUnitId, ///     单位
            Caa012 = !string.IsNullOrEmpty(dto.FQty)
                ? Convert.ToDecimal(dto.FQty)
                : null, ///     数量
            WorkGroupId = dto.FWorkGroupId, ///     计划组
            PlanId = dto.FPlannerID, ///     计划员
            Caa010 = dto.FPlanStartDate, ///     预计开工时间
            Caa011 = dto.FPlanFinishDate, ///     预计完工时间
            Caa005 = DateTime.TryParse(dto.FConveyDate, out var conveyDate) 
            ? (conveyDate <= new DateTime(1900, 1, 1) ? null : conveyDate.ToString())
                : null, ///     开单日期
            StockInlimith = dto.FStockInLimitH, ///     入库上限
            StockInlimitl = dto.FStockInLimitL, ///     入库下限
            Mtono = dto.FMTONO, ///     计划跟踪号
            Lot = dto.FLot, ///     批号
            Caa013 = dto.FBomId, ///     BOM版次
            Caa015 = dto.F_UNW_Text_xsddh, ///     订单单号
            Caa015Head = dto.xsddh_type, ///     订单单别
            CreateType = dto.FCreateType, ///     生成方式
 
            Caa018 = !string.IsNullOrEmpty(dto.PLAN_ID)
                ? Convert.ToInt32(dto.PLAN_ID)
                : null, ///     ERP源单ID
            Caa019 = !string.IsNullOrEmpty(dto.PLAN_SEQ)
                ? Convert.ToInt32(dto.PLAN_SEQ)
                : null, ///     ERP源单行号
            Caa020 = dto.PLAN_NUM, ///     ERP源单单号(任务单号)
 
            ForceCloserid = dto.FForceCloserId, ///     结案人
            CloseType = dto.FCloseType, ///     结案类型
            SrcSplitBillno = dto.FSrcSplitBillNo, ///     源拆分订单编号
            Caa016 = dto.FMemoItem, ///     备注
 
            SrcBillNo = dto.FSrcBillNo, ///     源单编号
            SrcBillentryseq = dto.FSrcBillEntrySeq, ///     源单分录行号
            SaleOrderNo = dto.FSaleOrderNo, ///     需求单据号
            SaleOrderEntryseq = dto.FSaleOrderEntrySeq, ///     需求单据行号
            
            
            
            ErpSczz = Convert.ToInt32(dto.FPrdOrgId), ///     生产组织ID
            ErpWtzz = Convert.ToInt32(dto.FEnTrustOrgId), ///     委托组织ID
            Btbz = dto.Btbz, ///     委托组织ID
            
            //MainProductNo = dto.F_XIFG_Base_w5c, ///     主产品编码
            // MainProductQty =
            //     Convert.ToInt32(dto.F_XIFG_Qty_yrr), ///     主产品生产数量
            // CustomerItemNumber = dto.F_XIFG_Text_fg2, ///     客户货号
            // PackingListNumber = dto.F_XIFG_Text_yrr, ///     包装单号
            // CustomerName = dto.F_XIFG_Text_qtr1, ///     客户名称
            // Customer = dto.F_XIFG_Base_83g1, ///     客户
            //Caa0111 = dto.FPlanFinishDate, ///     预计完工时间备份
            //Typea = dto.TypeA, ///     预计完工时间备份
            //Typeb = dto.TypeB ///     预计完工时间备份
            SynchronousDate = DateTime.Now,
            DocumentStatus = dto.FDocumentStatus
        };
 
        //根据单号+单别,获取对应的id
        var singleId = Db.Queryable<Womcaa>()
            .Where(x => x.SrcBillType == dto.FSrcBillType && x.Caa001 == dto.FBillNo)
            .Select(x => x.Erpid)
            .First();
 
        //如果没有则生成一个新的id
        if (singleId == null || string.IsNullOrWhiteSpace(singleId.ToString()))
        {
            entity.Erpid = (int)GenerateNewId();
            //entity.Erpid = GenerateNewId().ToString();
            //rohIn.id = GenerateNewId().ToString("0");
        }
        else//如果有则使用已有的id
        {
            entity.Erpid = Convert.ToInt32(singleId);
            //entity.Erpid = singleId.ToString();
        }
 
        var single = base.GetSingle(it => it.Erpid == entity.Erpid);
        if (single != null) entity.Guid = single.Guid;
 
        return entity;
    }
 
    private List<Womcab> MapErpCABtoWomcab(List<ErpCAB> dtoList)
    {
        var womcabList = new List<Womcab>();
 
        foreach (var dto in dtoList)
        {
            var womcab = new Womcab
            {
                Erpid = Convert.ToInt32(dto.Id), /// ERPID 
                Cab001 = dto.FBillNo, /// 工单单号 
                //Cab002 = Convert.ToInt32(dto.FSeq), /// 序号 
                Cab002 = Convert.ToInt32(dto.FBillNoType), /// 序号 
                Cab003 = dto.FMaterialID2, /// 材料编码 
                Cab006 = !string.IsNullOrEmpty(dto.FNeedQty)
                    ? Convert.ToDecimal(dto.FNeedQty)
                    : null, /// 需领用量 
                Cab007 = !string.IsNullOrEmpty(dto.FPickedQty)
                    ? Convert.ToDecimal(dto.FPickedQty)
                    : null, /// 已领用量 
                PositionNo = dto.FPositionNO, /// 位置号 
                SupplyOrganization = dto.FChildSupplyOrgId, /// 供应组织 
                IssuingOrganization = dto.FSUPPLYORG, /// 发料组织 
                OwnerId = dto.FOwnerID, /// 货主 
                Mtono = dto.FMTONO, /// 计划跟踪号 
                Lot = dto.FLot, /// 批号 
                DepotCode = dto.FStockID, /// 仓库 
                IssueType = dto.FIssueType, /// 发料方式 
                Cab008 = dto.F_UNW_Text_tpgy, /// 工艺 
                Cab009 = dto.FUnitID, /// 单位 
                SupplyType = dto.FSupplyType, /// 供应类型(C采购 Z自制 W委外) 
                Cab012 = !string.IsNullOrEmpty(dto.FStdQty)
                    ? Convert.ToDecimal(dto.FStdQty)
                    : null, /// 组成用量 
                Cab014 = dto.FIsKeyItem, /// 是否替料 
                Numerator = dto.FNumerator, /// 分子 
                Denominator = dto.FDenominator, /// 分母 
                Pid = Convert.ToInt32(dto.PID), /// ERP头ID 
                Eid = Convert.ToInt32(dto.Id), /// ERP ID 
 
                Scrapqty = dto.FFixScrapQty, /// 固定损耗 
                Scraprate = dto.FScrapRate, /// 变动损耗率
                Freplacegroup = Convert.ToInt32(dto.FReplaceGroup),
                UseRate = Convert.ToDecimal(dto.FUseRate),
                MaterialType = dto.FMaterialType,
                MustQty = Convert.ToDecimal(dto.FMustQty),
                Typeb = dto.TypeB,
                F_UNW_QTY_YFSL = dto.F_UNW_QTY_YFSL,
                // Fsaleorderno = dto.FSALEORDERNO, /// 销售订单 
                //
                // CustomerItemNumber = dto.F_XIFG_Text_re5, /// 客户货号 
                // PackingListNumber = dto.F_XIFG_Text_apv, /// 包装单号 
                // MainProduct = dto.F_XIFG_Base_re5, /// 主产品 
                // MainProductQty =
                //     Convert.ToInt32(dto.F_XIFG_Qty_apv), /// 主产品数量 
                // ParentItemName = dto.F_XIFG_Base_apv /// 父项物料名称 
            };
 
            //根据单号+单别+材料品号,获取对应的id
            var singleId = Db.Queryable<Womcab>()
            .Where(x => x.Cab001 == dto.FBillNo && x.Cab003 == dto.FMaterialID2 && x.Cab002 == Convert.ToInt32(dto.FBillNoType))
            .Select(x => x.Erpid)
            .First();
 
            if (singleId == null)//如果没有则生成一个新的id
            {
                //entity.EbelnK3id = GenerateNewId2().ToString();
                womcab.Erpid = (int)GenerateNewId2();
            }
            else//如果有则使用已有的id
            {
                //entity.EbelnK3id = singleId.EbelnK3id;
                womcab.Erpid = singleId;
            }
 
            var entity = Db.Queryable<Womcab>()
                .Where(s => s.Cab001 == womcab.Cab001 && s.Cab002 == womcab.Cab002 && s.Cab003 == womcab.Cab003)
                .Single();
            if (entity != null)
                womcab.Guid = entity.Guid;
            else
                womcab.Guid = Guid.NewGuid(); // 确保每条新数据唯一
 
            womcabList.Add(womcab);
        }
 
        return womcabList;
    }
 
    /// <summary>
    /// 生成新的主表ID,确保不重复
    /// </summary>
    private decimal GenerateNewId()
    {
        // 处理空表的情况,从1开始
        var maxId = Db.Queryable<Womcaa>().Max(x => (decimal?)x.Erpid) ?? 0;
        var newId = maxId + 1;
 
        // 双重检查,确保生成的ID不存在
        while (Db.Queryable<Womcaa>().Where(x => x.Erpid == newId).Any())
        {
            newId++;
        }
 
        return newId;
    }
 
    ///// <summary>
    ///// 生成新的主表ID,通过数据库序列获取唯一ID
    ///// </summary>
    //private decimal GenerateNewId()
    //{
    //    try
    //    {
    //        // 替换为:
    //        var sequenceValueObj = Db.Ado.GetScalar("SELECT NEXT VALUE FOR MES_WOMCAB_IN_seq");
    //        var sequenceValue = Convert.ToDecimal(sequenceValueObj);
    //        // 验证序列值是否有效
    //        if (sequenceValue <= 0)
    //        {
    //            throw new InvalidOperationException($"数据库序列 MES_WOMCAB_IN_seq 返回了无效的值: {sequenceValue}");
    //        }
 
    //        return sequenceValue;
    //    }
    //    catch (Exception ex)
    //    {
    //        // 记录异常信息
    //        Console.WriteLine($"调用数据库序列 MES_WOMCAB_IN_seq 失败: {ex.Message}");
 
    //        // 向上层抛出明确的异常信息
    //        throw new InvalidOperationException($"生成子表ID失败,无法获取数据库序列值: {ex.Message}", ex);
    //    }
    //}
 
    /// <summary>
    /// 生成新的子表ID,通过数据库序列获取唯一ID
    /// </summary>
    private decimal GenerateNewId2()
    {
        try
        {
            // 替换为:
            var sequenceValueObj = Db.Ado.GetScalar("SELECT NEXT VALUE FOR MES_WOMCAB_IN_DATA_seq");
            var sequenceValue = Convert.ToDecimal(sequenceValueObj);
            // 验证序列值是否有效
            if (sequenceValue <= 0)
            {
                throw new InvalidOperationException($"数据库序列 MES_WOMCAB_IN_DATA_seq 返回了无效的值: {sequenceValue}");
            }
 
            return sequenceValue;
        }
        catch (Exception ex)
        {
            // 记录异常信息
            Console.WriteLine($"调用数据库序列 MES_WOMCAB_IN_DATA_seq 失败: {ex.Message}");
 
            // 向上层抛出明确的异常信息
            throw new InvalidOperationException($"生成子表ID失败,无法获取数据库序列值: {ex.Message}", ex);
        }
    }
}