南骏 池
2025-04-11 9a722839b8068745b4ca418b01fa942d0b5f308e
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks.Dataflow;
using Masuit.Tools;
using NewPdaSqlServer.DB;
using NewPdaSqlServer.Dto.service;
using NewPdaSqlServer.entity;
using NewPdaSqlServer.util;
using SqlSugar;
 
namespace NewPdaSqlServer.service.Wom;
 
public class WwGdManager : Repository<WwGd>
{
    public ProductionPickDto ScanCode(WarehouseQuery query)
    {
        var _strMsg = "";
        var _intSum = "";
        using (var conn = new SqlConnection(DbHelperSQL.strConn))
        {
            if (query.userName.IsNullOrEmpty()) throw new Exception("用户名不允许为空");
            if (query.daa001.IsNullOrEmpty()) throw new Exception("领料单号不允许为空");
            if (query.barcode.IsNullOrEmpty()) throw new Exception("条码不允许为空");
 
            using (var cmd = new SqlCommand("[prc_pda_WWLL]", conn))
            {
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter[] parameters =
                    {
                        new("@outMsg", SqlDbType.NVarChar, 300),
                        new("@outSum", SqlDbType.NVarChar, 300),
                        new("@barcode_num", SqlDbType.NVarChar, 300),
                        new("@split_num", SqlDbType.NVarChar, 300),
                        new("@c_User", query.userName),
                        new("@p_biLL_no", query.daa001),
                        new("@p_item_barcode", query.barcode)
                    };
                    parameters[0].Direction = ParameterDirection.Output;
                    parameters[1].Direction = ParameterDirection.Output;
                    parameters[2].Direction = ParameterDirection.Output;
                    parameters[3].Direction = ParameterDirection.Output;
                    foreach (var parameter in parameters)
                        cmd.Parameters.Add(parameter);
                    cmd.ExecuteNonQuery();
                    _strMsg = parameters[0].Value.ToString();
                    _intSum = parameters[1].Value.ToString();
 
                    var barcodeNum = parameters[2].Value.ToString();
                    var splitNum = parameters[3].Value.ToString();
 
                    var result = Convert.ToInt32(_intSum);
                    if (result <= 0) throw new Exception(_strMsg);
 
                    var dto = new ProductionPickDto
                    {
                        daa001 = query.daa001,
                        barcodeNum = barcodeNum,
                        splitNum = splitNum,
                        barcode = query.barcode,
                        strMsg = _strMsg,
                        result = _intSum
                    };
 
                    return dto;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
 
    //prC_pda_SCLL_CF
    public ProductionPickDto ScanCodeCF(WarehouseQuery query)
    {
        if (query.userName.IsNullOrEmpty()) throw new Exception("用户名不允许为空");
        if (query.daa001.IsNullOrEmpty()) throw new Exception("领料单号不允许为空");
        if (query.barcode.IsNullOrEmpty()) throw new Exception("条码不允许为空");
 
        if (query.Num is null or 0) throw new Exception("条码拆分数不允许为空或者为0");
 
        var _strMsg = "";
        var _intSum = "";
        using (var conn = new SqlConnection(DbHelperSQL.strConn))
        {
            using (var cmd = new SqlCommand("[prc_pda_WWLL_CF]", conn))
            {
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter[] parameters =
                    {
                        new("@outMsg", SqlDbType.NVarChar, 300),
                        new("@outSum", SqlDbType.NVarChar, 300),
                        new("@c_User", query.userName),
                        new("@p_biLL_no", query.daa001),
                        new("@p_item_barcode", query.barcode),
                        new("@num", query.Num)
                    };
                    parameters[0].Direction = ParameterDirection.Output;
                    parameters[1].Direction = ParameterDirection.Output;
                    foreach (var parameter in parameters)
                        cmd.Parameters.Add(parameter);
                    cmd.ExecuteNonQuery();
                    _strMsg = parameters[0].Value.ToString();
                    _intSum = parameters[1].Value.ToString();
 
 
                    var result = Convert.ToInt32(_intSum);
                    if (result <= 0) throw new Exception(_strMsg);
 
                    var dto = new ProductionPickDto
                    {
                        daa001 = query.daa001,
                        barcode = query.barcode
                    };
 
                    return dto;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
 
    public ProductionPickDto GetItemsByDaa001(WarehouseQuery query)
    {
        return getDaa001(query);
    }
 
    private ProductionPickDto getDaa001(WarehouseQuery query)
    {
        if (string.IsNullOrEmpty(query.daa001)) throw new Exception("工单号为空");
 
        var wwgd = Db.Queryable<WwGd, MesItems>((a, i) =>
                new JoinQueryInfos(JoinType.Left,
                    a.Daa003 == i.ItemId))
            .Where((a, i) => a.Daa001 == query.daa001 && (a.PcSh ?? 0) == 1)
            .Select((a, i) => new
            {
                a.Daa001, a.RwdGuid
            }).First();
 
        if (wwgd?.Daa001 == null) throw new Exception("工单号不存在");
 
        var womdabs = Db
            .Queryable<WwGd, WwGdDetail, MesItems, ProductionOrderSub>(
                (a, b, c, d) =>
                    new JoinQueryInfos(
                        JoinType.Left,
                        a.Id == b.Pid,
                        JoinType.Inner,
                        c.Id == b.Dab003,
                        JoinType.Inner, b.Erpid.ToString() == d.ErpId
                    ))
            .Where((a, b, c, d) =>
                a.Daa001 == query.daa001 && d.IssuingMethod == "1")
            .Select((a, b, c, d) => new WwGdDetail
            {
                Pid = b.Pid,
                Dab003 = b.Dab003,
                Dab006 = b.Dab006,
                Dab007 = b.Dab007,
                wNum = b.Dab006 - b.Dab007, // 计算字段 W_NUM
                ItemName = c.ItemName, // 动态字段 ITEM_NAME
                ItemNo = c.ItemNo // 动态字段 ITEM_NO
            })
            .ToList();
 
        var list = womdabs.Where(s => s.wNum > 0).ToList();
 
        var mesInvItemOutCDetailsList = Db
            .Queryable<MesInvItemOutCDetails, MesItems, MesDepots>
            ((a, b, c) =>
                new JoinQueryInfos(
                    JoinType.Inner, a.ItemId == b.Id,
                    JoinType.Inner, c.DepotId == a.DepotId
                ))
            .Where((a, b, c) => a.WorkNo == query.daa001)
            .Select((a, b, c) => new MesInvItemOutCDetails
            {
                ItemName = b.ItemName,
                ItemNo = b.ItemNo,
                ItemId = a.ItemId,
                DepotId = a.DepotId,
                WorkNo = a.WorkNo,
                DepotName = c.DepotName,
                Quantity = a.Quantity
            })
            .ToList();
 
        var womcaa = Db.Queryable<ProductionOrder>()
            .Where(s => s.Guid == wwgd.RwdGuid)
            .First();
 
        var dto = new ProductionPickDto
        {
            daa001 = wwgd.Daa001,
            PlanNo = womcaa.ErpProductionOrderNo,
            totals1 = womdabs,
            daisao1 = list,
            yisao = mesInvItemOutCDetailsList
        };
 
        return dto;
    }
 
    #region 委外退料
 
    /// <summary>
    ///     委外退料扫描条码(生产退料的逻辑,只是调整了几个字段)
    /// </summary>
    /// <param name="query">仓库查询参数</param>
    /// <returns>处理结果</returns>
    public WarehouseQuery WwtlScanBarcode(WarehouseQuery query)
    {
        var p_item_barcode = query.barcode; // 物料条码
        var p_bill_no = query.billNo; // 单据号
        var p_section_code = query.DepotCode; // 库位编码
        var c_user = query.userName; // 用户名
 
        var p_bill_type_id = 100; // 单据类型ID
        var p_transction_no = 104; // 交易编号
 
        // 验证库位条码
        if (p_section_code.IsNullOrEmpty()) throw new Exception("请扫库位条码!");
 
        // 获取库位信息
        var c_depot_code = Db.Queryable<MesDepotSections, MesDepots>((a, b) =>
                new JoinQueryInfos(JoinType.Inner, a.DepotGuid == b.Guid))
            .Where((a, b) => a.DepotSectionCode == p_section_code)
            .Select((a, b) => b.DepotId).First();
 
        if (!c_depot_code.HasValue)
            throw new Exception("库位编码" + p_section_code + " 不存在,请确认!");
 
        // 获取库位分区信息
        var mesDepotSections = Db.Queryable<MesDepotSections>()
            .Where(a => a.DepotSectionCode == p_section_code).First();
 
        if (mesDepotSections == null)
            throw new Exception("库位编码" + p_section_code + " 不存在,请确认!");
 
        // 获取库位基础信息
        var c_mes_depots = Db.Queryable<MesDepots>()
            .Where(b => b.Guid == mesDepotSections.DepotGuid).First();
 
        if (c_mes_depots == null)
            throw new Exception("库位编码" + p_section_code + " 不存在,请确认!");
 
        // 检查条码是否已入库
        var c_num = Db.Queryable<MesInvItemIns, MesInvItemInCDetails>((a, b) =>
                new JoinQueryInfos(JoinType.Inner, a.Guid == b.ItemInId))
            .Where((a, b) => b.ItemBarcode == p_item_barcode
                             && a.BillTypeId == p_bill_type_id &&
                             a.TransctionNo == p_transction_no.ToString())
            .Count();
 
        if (c_num > 0) throw new Exception("此条码已扫入库,勿重复扫描!");
 
        c_num = Db.Queryable<MesInvItemStocks>()
            .Where(t => t.ItemBarcode == p_item_barcode).Count();
 
        if (c_num > 0) throw new Exception("此条码已扫入库,勿重复扫描!");
 
        // 获取条码信息
        var c_mes_inv_item_barcodes = Db.Queryable<MesInvItemBarcodes>()
            .Where(t => t.ItemBarcode == p_item_barcode).First();
 
        if (c_mes_inv_item_barcodes == null)
            throw new Exception("此条码不属于该退料单,请核对!");
 
       
 
        // if (c_mes_inv_item_barcodes.Memo != "生产退料")
        //     throw new Exception("此条码不是生产退料条码,不可使用生产退料模块!");
 
        // 获取退料单信息
        var C_MES_ITEM_TBL = Db.Queryable<MesItemTbl>()
            .Where(a => a.BillNo == c_mes_inv_item_barcodes.BillNo
                        && (a.Tbl013 ?? 0) == 1).First();
 
        if (C_MES_ITEM_TBL == null) throw new Exception("申请单已撤回,无法扫码!");
 
        if (C_MES_ITEM_TBL.Tbl020 == 1) throw new Exception("扫码完成,申请单已完结!");
 
        // 检查工单信息
        var wwgd = Db.Queryable<WwGd>()
            .Where(a => a.Id.ToString() == C_MES_ITEM_TBL.Tbl002)
            .First();
 
        if (wwgd == null) throw new Exception("申请单对应的工单不存在或已删除,无法扫码!");
 
        // 检查工单信息
        var WWRWD = Db.Queryable<ProductionOrder>()
            .Where(a => a.OrderNo == wwgd.Daa014)
            .First();
 
        // 获取退料单明细
        var C_MES_ITEM_TBL_DETAIL = Db.Queryable<MesItemTblDetail>()
            .Where(a => a.Tlid == c_mes_inv_item_barcodes.AboutGuid)
            .First();
 
        if (C_MES_ITEM_TBL_DETAIL == null)
            throw new Exception("条码不属于该申请单明细,无法扫码!");
 
        //判断货主信息
        var CABerpid = Db.Queryable<WwGdDetail>().Where(womdab => womdab.Id.ToString() == C_MES_ITEM_TBL_DETAIL.Tld013).Select(womdab => womdab.Erpid).First();
 
        var WWCAB = Db.Queryable<ProductionOrderSub>().Where(womcab => womcab.ErpId == CABerpid.Value.ToString()).First();
 
 
        if ( String.IsNullOrEmpty(WWCAB.Owner)) throw new Exception("用料清单货主信息不存在,无法扫码,请联系管理员!");
 
        //var owner_type = "";
        //if (Db.Queryable<SysOrganization>().Any(x => x.Fid == ownerId))
        //{
        //    owner_type = "BD_OwnerOrg";
        //}
        //else
        //{
        //    // 第二层判断:检查 MES_CUSTOMER
        //    if (Db.Queryable<MesCustomer>().Any(x => x.Id == Convert.ToInt32(ownerId)))
        //    {
        //        owner_type = "BD_Customer";
        //    }
        //    else
        //    {
        //        // 第三层判断:检查 MES_SUPPLIER
        //        if (Db.Queryable<MesSupplier>().Any(x => x.Id == Convert.ToInt32(ownerId)))
        //        {
        //            owner_type = "BD_Supplier";
        //        }
        //        else
        //        {
        //            throw new Exception("入库失败,用料清单货主信息存在问题,请联系管理员解决!");
        //        }
        //    }
        //}
 
        var c_quantity = c_mes_inv_item_barcodes.Quantity;
 
        var c_bill_no = "";
        var c_id = Guid.Empty;
 
        // 使用事务处理数据更新
        UseTransaction(db =>
        {
            // 查询入库单
            var mesInvItemIns = db.Queryable<MesInvItemIns>()
                .Where(d =>
                    d.Status == 0 && d.TransctionNo ==
                                  p_transction_no.ToString()
                                  && d.TaskNo == c_mes_inv_item_barcodes.BillNo
                                  && d.DepotsId == c_depot_code
                                  && d.InsDate.Value.ToString("yyyyMMdd") ==
                                  DateTime.Now.ToString("yyyyMMdd")).First();
 
            var totalResult = 0;
 
            // 如果入库单不存在则创建新的入库单
            if (mesInvItemIns == null)
            {
                c_bill_no = BillNo.GetBillNo("WWTL(委外退料)");
 
                c_id = Guid.NewGuid();
 
                totalResult += db.Insertable(new MesInvItemIns
                {
                    Guid = c_id,
                    BillNo = c_bill_no,
                    BillTypeId = p_bill_type_id,
                    InsDate = DateTime.Now,
                    DepotsId = c_depot_code,
                    UserNoBack = c_user,
                    Reason = C_MES_ITEM_TBL.Tbl005,
                    Remark = C_MES_ITEM_TBL.Tbl006,
                    //InsDate = DateTime.Now,
                    DepotsCode = c_mes_depots.DepotCode,
                    TaskNo = c_mes_inv_item_barcodes.BillNo,
                    //DepotsId = c_depot_code,
                    TransctionNo = p_transction_no.ToString(),
                    CreateBy = c_user,
                    CreateDate = DateTime.Now,
                    LastupdateBy = c_user,
                    LastupdateDate = DateTime.Now,
                    CbillNo = wwgd.Daa001,
                    InType = "委外退料",
                    ReceiveOrgId = c_mes_depots.FSubsidiary,
                    Fstatus = 0,
                    Status = 0,
                    WorkNo = WWRWD.ErpProductionOrderNo
                }).IgnoreColumns(true).ExecuteCommand();
            }
            else
            {
                c_id = mesInvItemIns.Guid;
                c_bill_no = mesInvItemIns.BillNo;
            }
 
            // 检查是否为合并打印条码
            var hbdy = c_mes_inv_item_barcodes.Hbdy ?? 0;
            if (hbdy == 1) throw new Exception("不支持合并打印的条码:" + p_item_barcode);
 
 
            // 检查是否存在于 MES_INV_ITEM_IN_C_ITEMS 表
            var existingCount = db.Queryable<MesInvItemInCItems>()
            .Where(it =>
                it.ItemInId == c_id &&
                                it.ItemId == C_MES_ITEM_TBL_DETAIL.Tld009 &&
                                it.DepotId == c_depot_code.ToString())
                .Count();
 
            if (existingCount == 0)
                // 不存在时插入新记录
                db.Insertable(new MesInvItemInCItems
                {
                    ItemInId = c_id,
                    Quantity = c_mes_inv_item_barcodes.Quantity,
                    CreateBy = c_user,
                    CreateDate = DateTime.Now,
                    ItemNo = c_mes_inv_item_barcodes.ItemNo,
                    //DepotCode = mesDepost.DepotCode,
                    ItemSname = c_mes_inv_item_barcodes.ItemSname,
                    Unit = c_mes_inv_item_barcodes.Unit,
                    Ebeln = c_mes_inv_item_barcodes.WorkNo,
                    BillNo = c_bill_no,
                    WorkNo = c_mes_inv_item_barcodes.WorkNo,
                    EbelnLineNo = c_mes_inv_item_barcodes.WorkLine,
                    CbillNo = c_mes_inv_item_barcodes.BillNo,
                    WorkLine = c_mes_inv_item_barcodes.WorkLine,
                    SuppId = c_mes_inv_item_barcodes.SuppId,
                    SuppNo = c_mes_inv_item_barcodes.SuppNo,
                    Remark = c_mes_inv_item_barcodes.Memo,
                    EbelnK3id = c_mes_inv_item_barcodes.EbelnK3id,
                    LineK3id = c_mes_inv_item_barcodes.LineK3id,
                    ItemId = c_mes_inv_item_barcodes.ItemId,
                    DepotCode = c_mes_depots.DepotCode,
                    DepotId = c_depot_code.ToString(),
                    itemDabid = c_mes_inv_item_barcodes.AboutGuid.ToString()
                }).IgnoreColumns(true).ExecuteCommand();
            else
                // 存在时更新数量
                db.Updateable<MesInvItemInCItems>()
                    .SetColumns(it => new MesInvItemInCItems
                    {
                        Quantity = SqlFunc.IsNull(it.Quantity, 0) + c_mes_inv_item_barcodes.Quantity // 确保 Quantity 不为 null
                    })
                .Where(it =>
                       it.ItemInId == c_id &&
                                it.ItemId == C_MES_ITEM_TBL_DETAIL.Tld009 &&
                                it.DepotId == c_depot_code.ToString())
                    //.IgnoreColumns(true) // 保留 IgnoreColumns
                    .ExecuteCommand();
 
            // 插入入库单明细
            totalResult += db.Insertable(new MesInvItemInCDetails
            {
                Guid = Guid.NewGuid(),
                ItemInId = c_id,
                BillNo = c_bill_no,
                ItemBarcode = p_item_barcode,
                Quantity = c_quantity,
                BarcodeFlag = true,
                EpFlag = true,
                WorkType = 1,
                ItemId = c_mes_inv_item_barcodes.ItemId,
                ItemNo = c_mes_inv_item_barcodes.ItemNo,
                LotNo = c_mes_inv_item_barcodes.LotNo,
                SuppId = c_mes_inv_item_barcodes.SuppId,
                SuppNo = c_mes_inv_item_barcodes.SuppNo,
                DepotId = c_mes_depots.DepotId,
                DepotCode = c_mes_depots.DepotCode,
                DepotSectionCode = p_section_code,
                ItemSname = c_mes_inv_item_barcodes.ItemSname,
                Unit = c_mes_inv_item_barcodes.Unit,
                CreateBy = c_user,
                CreateDate = DateTime.Now,
                LastupdateBy = c_user,
                LastupdateDate = DateTime.Now,
                Remark = c_mes_inv_item_barcodes.Memo,
                Ebeln = c_mes_inv_item_barcodes.Mblnr,
                EbelnLineNo = c_mes_inv_item_barcodes.Zeile,
                WorkNo = c_mes_inv_item_barcodes.WorkNo,
                WorkLine = c_mes_inv_item_barcodes.WorkLine,
                CbillNo = c_mes_inv_item_barcodes.BillNo,
                UrgentFlag = c_mes_inv_item_barcodes.UrgentFlag,
                BoardStyle = c_mes_inv_item_barcodes.BoardStyle,
                TaskNo = c_mes_inv_item_barcodes.TaskNo,
                RbillNo = C_MES_ITEM_TBL.Tbl002,
                ReceiveOrgId = c_mes_depots.FSubsidiary,
                EbelnK3id = c_mes_inv_item_barcodes.EbelnK3id,
                LineK3id = c_mes_inv_item_barcodes.LineK3id,
                Ischeck = true,
            }).IgnoreColumns(true).ExecuteCommand();
 
            // 插入业务记录
            totalResult += db.Insertable(new MesInvBusiness2
            {
                Guid = Guid.NewGuid(),
                Status = 1,
                BillTypeId = p_bill_type_id,
                TransactionCode = p_transction_no.ToString(),
                BusinessType = 1,
                ItemBarcode = p_item_barcode,
                ItemNo = c_mes_inv_item_barcodes.ItemNo,
                LotNo = c_mes_inv_item_barcodes.LotNo,
                EpFlag = true,
                Quantity = c_mes_inv_item_barcodes.Quantity,
                ToInvDepotsCode = c_mes_depots.DepotCode,
                InvDepotId = c_depot_code,
                ToInvDepotSectionsCode = p_section_code,
                Description = "委外退料",
                CreateBy = c_user,
                CreateDate = DateTime.Now,
                LastupdateBy = c_user,
                LastupdateDate = DateTime.Now,
                TaskNo = c_mes_inv_item_barcodes.TaskNo,
                BillNo = c_bill_no,
                WorkNo = c_mes_inv_item_barcodes.WorkNo,
                WorkLine = c_mes_inv_item_barcodes.WorkLine,
                SuppId = c_mes_inv_item_barcodes.SuppId,
                SuppNo = c_mes_inv_item_barcodes.SuppNo,
                ItemId = c_mes_inv_item_barcodes.ItemId
            }).IgnoreColumns(true).ExecuteCommand();
 
            // 插入库存记录
            totalResult += db.Insertable(new MesInvItemStocks
            {
                Guid = Guid.NewGuid(),
                TaskNo = c_mes_inv_item_barcodes.TaskNo,
                ItemBarcode = p_item_barcode,
                ItemNo = c_mes_inv_item_barcodes.ItemNo,
                LotNo = c_mes_inv_item_barcodes.LotNo,
                Quantity = c_mes_inv_item_barcodes.Quantity,
                //EpFlag = c_mes_inv_item_barcodes.EpFlag.Value
                //    ? (byte)1
                //    : (byte)0,
                DepotId = c_mes_depots.DepotId,
                DepotsCode = c_mes_depots.DepotCode,
                DepotSectionsCode = p_section_code,
                CheckDate = c_mes_inv_item_barcodes.CreateDate,
                IndepDate = DateTime.Now,
                BoardStyle = c_mes_inv_item_barcodes.BoardStyle,
                WorkNo = c_mes_inv_item_barcodes.WorkNo,
                WorkLine = c_mes_inv_item_barcodes.WorkLine,
                SuppNo = c_mes_inv_item_barcodes.SuppNo,
                ItemId = c_mes_inv_item_barcodes.ItemId,
                BillNo = c_mes_inv_item_barcodes.BillNo,
                //DepotId = Convert.ToInt32(c_depot_code),
                OwnerId = WWCAB.Owner,
                OwnerType = WWCAB.OwnerType,
                StockOrgId = c_mes_depots.FSubsidiary,
                IndepUserCode = c_user
            }).IgnoreColumns(true).ExecuteCommand();
 
            // 根据退料类型(良品退料、来料不良退料、作业不良退料)更新相关数据
            if (C_MES_ITEM_TBL.Tbl005 is "良品退料" or "来料不良退料")
            {
                // 良品退料 - 更新工单表(WOMDAB)相关数量
                if (C_MES_ITEM_TBL.Tbl005 == "良品退料")
                    totalResult += Db.Updateable<Womdab>()
                        .SetColumns(it => new Womdab
                        {
                            Dab007 = it.Dab007 -
                                     c_mes_inv_item_barcodes.Quantity, // 减少工单数量
                            Dab022 = (it.Dab022 ?? 0) +
                                     c_mes_inv_item_barcodes.Quantity, // 增加退料数量
                            LpTl = (it.LpTl ?? 0) +
                                   (int)c_mes_inv_item_barcodes
                                       .Quantity, // 增加良品退料数量
                            Dab020 = (it.Dab020 ?? 0) -
                                     c_mes_inv_item_barcodes.Quantity // 减少已发料数量
                        })
                        .Where(it => it.Dab001 == c_mes_inv_item_barcodes.WorkNo
                                     && it.Dab002 == c_mes_inv_item_barcodes
                                         .WorkLine
                                     && it.Dab003 == c_mes_inv_item_barcodes
                                         .ItemId.ToString())
                        .ExecuteCommand();
                // 来料不良退料 - 更新工单表(WOMDAB)相关数量
                else if (C_MES_ITEM_TBL.Tbl005 == "来料不良退料")
                    totalResult += Db.Updateable<Womdab>()
                        .SetColumns(it => new Womdab
                        {
                            Dab007 = it.Dab007 -
                                     c_mes_inv_item_barcodes.Quantity, // 减少工单数量
                            Dab022 = (it.Dab022 ?? 0) +
                                     c_mes_inv_item_barcodes.Quantity, // 增加退料数量
                            LlBl = (it.LlBl ?? 0) +
                                   (int)c_mes_inv_item_barcodes
                                       .Quantity, // 增加来料不良数量
                            Dab020 = (it.Dab020 ?? 0) -
                                     c_mes_inv_item_barcodes.Quantity // 减少已发料数量
                        })
                        .Where(it => it.Dab001 == c_mes_inv_item_barcodes.WorkNo
                                     && it.Dab002 == c_mes_inv_item_barcodes
                                         .WorkLine
                                     && it.Dab003 == c_mes_inv_item_barcodes
                                         .ItemId.ToString())
                        .ExecuteCommand();
 
                // 更新退料单明细表已退数量
                totalResult += Db.Updateable<MesItemTblDetail>()
                    .SetColumns(it => new MesItemTblDetail
                    {
                        Tld006 = (it.Tld006 ?? 0) +
                                 (int)c_mes_inv_item_barcodes.Quantity // 增加已退数量
                    })
                    .Where(it => it.Tlmid == C_MES_ITEM_TBL.Id
                                 && it.Tld009 == c_mes_inv_item_barcodes.ItemId)
                                 //&& it.Tld010 ==
                                 //c_mes_inv_item_barcodes.WorkLine)
                    .ExecuteCommand();
            }
            // 作业不良退料 - 更新工单表和退料单明细表
            else if (C_MES_ITEM_TBL.Tbl005 == "作业不良退料")
            {
                totalResult += Db.Updateable<Womdab>()
                    .SetColumns(it => new Womdab
                    {
                        Dab022 = (it.Dab022 ?? 0) +
                                 c_mes_inv_item_barcodes.Quantity, // 增加退料数量
                        ZyBl = (it.ZyBl ?? 0) +
                               (int)c_mes_inv_item_barcodes
                                   .Quantity, // 增加作业不良数量
                        Dab020 = (it.Dab020 ?? 0) -
                                 c_mes_inv_item_barcodes.Quantity // 减少已发料数量
                    })
                    .Where(it => it.Dab001 == c_mes_inv_item_barcodes.WorkNo
                                 && it.Dab002 ==
                                 c_mes_inv_item_barcodes.WorkLine
                                 && it.Dab003 == c_mes_inv_item_barcodes.ItemId
                                     .ToString())
                    .ExecuteCommand();
 
                // 更新退料单明细表已退数量
                totalResult += Db.Updateable<MesItemTblDetail>()
                    .SetColumns(it => new MesItemTblDetail
                    {
                        Tld006 = (it.Tld006 ?? 0) +
                                 (int)c_mes_inv_item_barcodes.Quantity // 增加已退数量
                    })
                    .Where(it => it.Tlmid == C_MES_ITEM_TBL.Id
                                 && it.Tld009 == c_mes_inv_item_barcodes.ItemId)
                                 //&& it.Tld010 ==
                                 //c_mes_inv_item_barcodes.WorkLine)
                    .ExecuteCommand();
            }
 
            // 如果待退数量等于本次退料数量,则更新明细完成状态
            if ((C_MES_ITEM_TBL_DETAIL.Tld005 ?? 0) -
                (C_MES_ITEM_TBL_DETAIL.Tld006 ?? 0) ==
                c_mes_inv_item_barcodes.Quantity)
                totalResult += Db.Updateable<MesItemTblDetail>()
                    .SetColumns(it => new MesItemTblDetail
                        { Tld008 = 1 }) // 设置完成标志
                    .Where(it => it.Tlid == C_MES_ITEM_TBL_DETAIL.Tlid)
                    .ExecuteCommand();
 
            // 检查退料单是否所有明细都已完成
            var remainingCount = Db.Queryable<MesItemTbl, MesItemTblDetail>(
                    (a, b) =>
                        new JoinQueryInfos(JoinType.Left, a.Id == b.Tlmid))
                .Where((a, b) =>
                    a.BillNo == p_bill_no &&
                    (b.Tld005 ?? 0) - (b.Tld006 ?? 0) > 0)
                .Count();
 
            // 如果所有明细都已完成,则更新退料单状态为已完成
            if (remainingCount < 1)
                totalResult += Db.Updateable<MesItemTbl>()
                    .SetColumns(it => it.Tbl020 == 1) // 设置完成标志
                    .Where(it => it.BillNo == p_bill_no)
                    .ExecuteCommand();
 
            // 检查必要的插入操作是否都成功执行
            var minimumExpectedOperations = 3; // 至少需要执行的插入操作数
            if (totalResult < minimumExpectedOperations)
                throw new Exception(
                    $"关键数据插入失败,预期至少{minimumExpectedOperations}个操作,实际执行{totalResult}个操作");
 
            // 创建 插入日志
            var logService = new LogService();
            var LogMsg = "[PDA]委外退料。条码【" + query.barcode + "】 退料单号【" + c_bill_no + "】";
            logService.CreateLog(db, query.userName, wwgd.Id.ToString(), "WW_GD", LogMsg, wwgd.Daa001);
 
            return totalResult;
        });
 
        query.itemNo = c_mes_inv_item_barcodes.ItemNo;
        query.Num = c_quantity.Value;
        return query;
    }
 
    #endregion
 
    #region 委外补料
 
    /// <summary>
    /// 委外工单补料扫码
    ///     扫描条码  prc_rf_pda_scan_zout_barcode3
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>扫描结果</returns>
    /// <remarks>
    ///     参数说明:
    ///     - billNo: 单据号(必填)
    ///     - barcode: 条码(必填)
    ///     - userName: 用户名
    ///     - blNo: 补料单号(必填)
    /// </remarks>
    public (WarehouseQuery item, List<MesItemBlDetail> pendingList)
        WwblScanBarcode(WarehouseQuery query)
    {
        if (string.IsNullOrEmpty(query.billNo))
            throw new Exception("请选取单据号!");
 
        if (string.IsNullOrEmpty(query.barcode))
            throw new Exception("请扫描条码!");
 
        if (string.IsNullOrEmpty(query.userName))
            throw new Exception("用户名不能为空!");
 
        if (string.IsNullOrEmpty(query.blNo))
            throw new Exception("补料单号不能为空!");
 
 
        // 检验是否重复扫描
        var exists = Db.Queryable<MesInvItemOutCDetails>()
            .Where(b => b.ItemBarcode == query.barcode)
            .Any();
 
        if (exists)
            throw new Exception("此条码已扫描,勿重复扫码!");
 
        // 查询条码库存信息
        var stockBarcode = Db.Queryable<MesInvItemStocks>()
            .Where(t => t.ItemBarcode == query.barcode && t.Quantity > 0)
            .First();
 
        if (stockBarcode == null)
            throw new Exception($"库存中无此条码,请核对!{query.barcode}");
 
        // 检查补料单状态
        var mesItemBl = Db.Queryable<MesItemBl>()
            .Where(a => a.BlNo == query.blNo)
            .First();
 
        if (mesItemBl == null)
            throw new Exception($"申请单 {query.blNo} 已撤回!");
 
        if (mesItemBl.Bl018 != true)
            throw new Exception($"申请单 {query.blNo} 未审核!");
 
        if (mesItemBl.Bl019 == true)
            throw new Exception($"申请单 {query.blNo} 已完结!");
 
        // 获取补料单明细并校验
        var blDetail = Db.Queryable<MesItemBlDetail>()
            .Where(b =>
                b.Mid == mesItemBl.Id && b.Bld012 == stockBarcode.ItemId && b.Bld007 > b.Bld008)
            .First();
 
        if (blDetail == null)
            throw new Exception($"申请单不存在此物料 {stockBarcode.ItemNo} 请确认!");
 
        // 检查待补数量
        var quantity = (blDetail.Bld007 ?? 0) - (blDetail.Bld008 ?? 0);
        if (quantity == 0)
            throw new Exception("物料已扫码完成,请核对!");
 
        // 检查工单信息
        var wwgd = Db.Queryable<WwGd>()
            .Where(a => a.Daa001 == query.billNo)
            .First();
 
        // 检查工单信息
        var WWRWD = Db.Queryable<ProductionOrder>()
            .Where(a => a.OrderNo == wwgd.Daa014)
            .First();
 
        if (wwgd == null)
            throw new Exception($"工单 {query.billNo} 不存在,请确认!");
 
        // 检查备料明细
        var womdab = Db.Queryable<WwGdDetail>()
            .Where(b => b.Dab001 == query.billNo && b.Erpid == blDetail.Bld014)
            .First();
 
        if (womdab == null)
            throw new Exception($"备料明细不存在此物料 {stockBarcode.ItemNo} 请确认!");
 
 
        var depots = Db.Queryable<MesDepots>()
            .Where(t => t.DepotId == stockBarcode.DepotId)
            .First();
 
        if (stockBarcode.Quantity > quantity)
        {
            // 获取待发料明细列表
            var pendingList = Db.Queryable<MesItemBl, MesItemBlDetail>((a, b) =>
                    new JoinQueryInfos(JoinType.Left, a.Id == b.Mid))
                .Where((a, b) => a.BlNo == query.blNo
                                 && (b.Bld007 ?? 0) - (b.Bld008 ?? 0) > 0)
                .Select((a, b) => new MesItemBlDetail
                {
                    Bld012 = b.Bld012,
                    Bld002 = b.Bld002,
                    Bld003 = b.Bld003,
                    Bld004 = b.Bld004,
                    Bld007 = b.Bld007,
                    Bld008 = b.Bld008
                })
                .ToList();
 
 
            query.Num = stockBarcode.Quantity;
            query.Fum = quantity;
 
            return (query, pendingList);
        }
 
        // 开启事务处理
        var success = UseTransaction(db =>
        {
            //query.Type = "委外补料";
            var outNoType = "WWBL(委外补料)";
            if (query.Type == "委外补料")
            {
                outNoType = "WWBL(委外补料)";
            }
            else
            {
                outNoType = "WWCL(委外超领)";
            }
            //outNoType = "WWBL(委外补料)";
            // 获取或创建出库单
            var outId = Guid.NewGuid();
            var outNo = BillNo.GetBillNo(outNoType);
 
            var existingOut = db.Queryable<MesInvItemOuts>()
                .Where(a => a.TaskNo == query.blNo
                            && a.DepotId == stockBarcode.DepotId
                            && a.OutDate.Value.Date.ToString("yyyy-MM-dd") ==
                            DateTime.Now.Date.ToString("yyyy-MM-dd")
                            && a.BillTypeId == 200
                            && a.TransactionNo == 209
                            && a.Status == 0)
                .First();
 
            if (existingOut != null)
            {
                outId = existingOut.Guid;
                outNo = existingOut.ItemOutNo;
            }
            else
            {
                // 插入出库单主表
                db.Insertable(new MesInvItemOuts
                {
                    Guid = outId,
                    ItemOutNo = outNo,
                    TaskNo = query.blNo,
                    CreateBy = query.userName,
                    CreateDate = DateTime.Now,
                    LastupdateBy = query.userName,
                    LastupdateDate = DateTime.Now,
                    BillTypeId = 200,
                    TransactionNo = 209,
                    Remark = mesItemBl.Bl007,
                    DepotCode = depots.DepotCode,
                    OutPart = wwgd.DepartId.ToString(),
                    OutType = query.Type,
                    FType = 0,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    WorkNo = WWRWD.ErpProductionOrderNo,
                    BoardItem = wwgd.Daa003.ToString(),
                    PbillNo = wwgd.Daa001,
                    OutDate = DateTime.Now,
                    Status = 0,
                    DepotId = stockBarcode.DepotId,
                    THORGID = stockBarcode.StockOrgId,
                    //BbillNo = query.billNo
                }).IgnoreColumns(true).ExecuteCommand();
            }
 
            // 检查并更新出库单物料明细
            var itemCount = db.Queryable<MesInvItemOutItems>()
                .Where(i =>
                    i.ItemOutId == outId && i.ItemId == stockBarcode.ItemId && i.ItemOutId == outId && i.DepotId == stockBarcode.DepotsId.ToString())
                .Count();
 
            if (itemCount > 0)
                // 更新已存在的物料明细数量
                db.Updateable<MesInvItemOutItems>()
                    .SetColumns(i =>
                        i.TlQty == i.TlQty + stockBarcode.Quantity)
                    .Where(i =>
                        i.ItemOutId == outId && i.ItemId == stockBarcode.ItemId && i.ItemOutId == outId && i.DepotId == stockBarcode.DepotsId.ToString())
                    .ExecuteCommand();
            else
                // 插入新的物料明细记录
                db.Insertable(new MesInvItemOutItems
                {
                    Guid = Guid.NewGuid(),
                    ItemOutId = outId,
                    ItemNo = blDetail.Bld002,
                    Quantity = stockBarcode.Quantity,
                    TlQty = stockBarcode.Quantity,
                    CreateBy = query.userName,
                    CreateDate = DateTime.Now,
                    LastupdateBy = query.userName,
                    LastupdateDate = DateTime.Now,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    DepotCode = depots.DepotCode,
                    TaskNo = query.blNo,
                    WorkNo = WWRWD.ErpProductionOrderNo,
                    WorkLine = blDetail.Bld013,
                    ErpItemNo = womdab.Dab003.ToString(),
                    ErpId = womdab.Eid,
                    ErpAutoid = womdab.Erpid,
                    PbillNo = query.billNo,
                    ItemId = blDetail.Bld012,
                    DepotId = stockBarcode.DepotsId.ToString(),
                    ItemDabid = blDetail.Id,
                    //AboutGuid = womdab.Id
                    // Unit = blDetail.Bld009,
                    // DepotId = (int)stockBarcode.DepotsId
                }).IgnoreColumns(true).ExecuteCommand();
 
            // 插入出库单条码明细
            db.Insertable(new MesInvItemOutCDetails
            {
                Guid = Guid.NewGuid(),
                ItemOutId = outId,
                ItemBarcode = stockBarcode.ItemBarcode,
                ItemNo = stockBarcode.ItemNo,
                LotNo = stockBarcode.LotNo,
                Quantity = stockBarcode.Quantity,
                ForceOutFlag = 0,
                CreateBy = query.userName,
                CreateDate = DateTime.Now,
                LastupdateBy = query.userName,
                LastupdateDate = DateTime.Now,
                DepotCode = depots.DepotCode,
                DepotSectionCode = stockBarcode.DepotSectionsCode,
                Remark = blDetail.Bld010,
                Factory = stockBarcode.Factory,
                Company = stockBarcode.Company,
                TaskNoy = mesItemBl.Bl013,
                BoardStyle = mesItemBl.Bl002,
                TaskNo = query.blNo,
                WorkNo = blDetail.Bld001,
                WorkLine = blDetail.Bld013,
                SuppNo = stockBarcode.SuppNo,
                PbillNo = query.billNo,
                ItemId = blDetail.Bld012,
                Unit = blDetail.Bld009,
                DepotId = (int)stockBarcode.DepotId,
                EbelnK3id = womdab.Eid,
                LineK3id = womdab.Erpid
            }).IgnoreColumns(true).ExecuteCommand();
 
            // 插入业务交易记录
            db.Insertable(new MesInvBusiness2
            {
                Guid = Guid.NewGuid(),
                Status = 1,
                BillTypeId = 200, // p_bill_type_id
                TransactionCode = "209", // p_transaction_no
                BusinessType = -1,
                ItemBarcode = stockBarcode.ItemBarcode,
                ItemNo = stockBarcode.ItemNo,
                LotNo = stockBarcode.LotNo,
                EpFlag = true,
                Quantity = stockBarcode.Quantity,
                FromInvDepotsCode = stockBarcode.DepotsCode,
                FromInvDepotSectionsCode = stockBarcode.DepotSectionsCode,
                CreateBy = query.userName,
                CreateDate = DateTime.Now,
                LastupdateBy = query.userName,
                LastupdateDate = DateTime.Now,
                Factory = stockBarcode.Factory,
                Company = stockBarcode.Company,
                TaskNo = mesItemBl.Bl012, // Matches C_QTCK.Bl012
                BillNo = query.blNo,
                WorkNo = blDetail.Bld001, // Matches C_QTCK_D.Bld001
                WorkLine = blDetail.Bld013, // Matches C_QTCK_D.Bld013
                SuppNo = stockBarcode.SuppNo,
                ItemId = stockBarcode.ItemId
                // CkDepot = stockBarcode.DepotsId
            }).IgnoreColumns(true).ExecuteCommand();
 
 
            // 更新工单表数量
            db.Updateable<WwGdDetail>()
                .SetColumns(it => new WwGdDetail
                {
                    Dab007 = (it.Dab007 ?? 0) + (int)stockBarcode.Quantity,
                    Dab020 = (it.Dab020 ?? 0) + (int)stockBarcode.Quantity,
                    Dab021 = (it.Dab021 ?? 0) + (int)stockBarcode.Quantity
                })
                .Where(it => it.Id == womdab.Id && it.Dab003 == womdab.Dab003)
                .ExecuteCommand();
 
 
            // 更新补料单明细已补数量
            db.Updateable<MesItemBlDetail>()
                .SetColumns(it => new MesItemBlDetail
                {
                    Bld008 = (it.Bld008 ?? 0) + (int)stockBarcode.Quantity
                })
                .Where(it => it.Id == blDetail.Id)
                .ExecuteCommand();
 
            // 检查补料单明细是否完成
            var blDetail1 = db.Queryable<MesItemBlDetail>()
                .Where(it => it.Id == blDetail.Id)
                .First();
 
            if ((blDetail1.Bld007 ?? 0) <= (blDetail1.Bld008 ?? 0))
                // 更新明细完成状态
                db.Updateable<MesItemBlDetail>()
                    .SetColumns(it => it.Bld011 == 1)
                    .Where(it => it.Id == blDetail1.Id)
                    .ExecuteCommand();
 
            // 更新库存数量为0
            db.Updateable<MesInvItemStocks>()
                .SetColumns(it => it.Quantity == 0)
                .Where(it => it.Guid == stockBarcode.Guid)
                .ExecuteCommand();
 
 
            // 检查是否所有明细都已完成
            var unfinishedDetail = db.Queryable<MesItemBlDetail>()
                .LeftJoin<MesItemBl>((b, a) => a.Id == b.Mid)
                .Where((b, a) => a.BlNo == query.blNo && (b.Bld011 ?? 0) == 0)
                .Select((b, a) => b)
                .First();
 
            if (unfinishedDetail == null)
                // 如果没有未完成的明细,更新补料单状态为已完成
                db.Updateable<MesItemBl>()
                    .SetColumns(it => new MesItemBl
                    {
                        Bl019 = true,
                        WcUser = query.userName,
                        WcTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    })
                    .Where(it => it.Id == mesItemBl.Id)
                    .ExecuteCommand();
 
            // 创建 插入日志
            var logService = new LogService();
            var LogMsg = "[PDA]"+query.Type + "。条码【" +query.barcode+"】 出库单号【"+ outNo +"】";
            logService.CreateLog(db,query.userName,wwgd.Id.ToString(), "WW_GD", LogMsg,wwgd.Daa001);
 
            return 1;
        });
 
        // 获取最终的待发料明细列表
        var finalPendingList = Db.Queryable<MesItemBl, MesItemBlDetail>(
                (a, b) =>
                    new JoinQueryInfos(JoinType.Left, a.Id == b.Mid))
            .Where((a, b) => a.BlNo == query.blNo
                             && (b.Bld007 ?? 0) - (b.Bld008 ?? 0) > 0)
            .Select((a, b) => new MesItemBlDetail
            {
                Bld012 = b.Bld012,
                Bld002 = b.Bld002,
                Bld003 = b.Bld003,
                Bld004 = b.Bld004,
                Bld007 = b.Bld007,
                Bld008 = b.Bld008
            })
            .ToList();
 
        return (query, finalPendingList);
    }
 
    /// <summary>
    ///     生产补料单条码拆分 prc_rf_pda_prnt_zout_barcode2
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>(成功标志, 待处理列表)</returns>
    /// <remarks>
    ///     前台需要传入的参数:
    ///     - userName: 用户名(必填)
    ///     - billNo: 工单号(必填)
    ///     - barcode: 物料条码(必填)
    ///     - Num: 发料数量(必填,必须大于0)
    ///     - blNo: 补料单号(必填)
    /// </remarks>
    public (bool success, List<MesItemBlDetail> pendingList) SplitBarcode(
        WarehouseQuery query)
    {
        if (string.IsNullOrEmpty(query.userName))
            throw new Exception("用户名不能为空!");
 
        if (string.IsNullOrEmpty(query.billNo))
            throw new Exception("请选取单据号!");
 
        if (string.IsNullOrEmpty(query.barcode))
            throw new Exception("请扫描条码!");
 
        if (query.Num <= 0)
            throw new Exception("请输入正确的发料数量!");
 
        if (string.IsNullOrEmpty(query.blNo))
            throw new Exception("补料单号不能为空!");
 
 
        // 检验是否重复扫描
        var exists = Db.Queryable<MesInvItemOutCDetails>()
            .Where(b => b.ItemBarcode == query.barcode)
            .Any();
 
        if (exists)
            throw new Exception("此条码已扫描,勿重复扫码!");
 
        // 查询条码库存信息
        var stockBarcode = Db.Queryable<MesInvItemStocks>()
            .Where(t => t.ItemBarcode == query.barcode && t.Quantity > 0)
            .First();
 
        if (stockBarcode == null)
            throw new Exception($"库存中无此条码,请核对!{query.barcode}");
 
        var totalQty = stockBarcode.Quantity;
        string newBarcode = null;
 
        // 开启事务处理
        var success = UseTransaction(db =>
        {
            var executeCommand = 0;
 
            // 拆分条码
            if (totalQty > query.Num)
            {
                var mesItems = db.Queryable<MesItems>()
                    .Where(s => s.Id == stockBarcode.ItemId).First();
 
                // 生成新条码号
                newBarcode = BillNo.GetBillNo("TM(条码)", mesItems.ItemNo);
 
                // 写入新条码
                executeCommand += db.Insertable(new MesInvItemBarcodes
                {
                    Guid = Guid.NewGuid(),
                    ItemBarcode = newBarcode,
                    CustNo = stockBarcode.CustomerNo,
                    // ProductCode = stockBarcode.ProductCode, 
                    // ItemBarcode2 = stockBarcode.ItemBarcode2,
                    // ItemCode = stockBarcode.ItemCode,
                    ItemNo = stockBarcode.ItemNo,
                    LotNo = stockBarcode.LotNo,
                    Quantity = query.Num,
                    EpFlag = true,
                    TaskNo = stockBarcode.TaskNo,
                    CreateBy = query.userName,
                    CreateDate = DateTime.Now,
                    LastupdateBy = query.userName,
                    LastupdateDate = DateTime.Now,
                    OldItemBarcode = query.barcode,
                    // Mblnr = stockBarcode.Mblnr,
                    // Zeile = stockBarcode.Zeile,
                    // RohInId = stockBarcode.RohInId,
                    Barcodestatus = false,
                    Oldqty = query.Num as long?,
                    // Unit = stockBarcode.Unit,
                    // WeightUnit = stockBarcode.WeightUnit,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    BillNo = stockBarcode.BillNo,
                    BoardStyle = stockBarcode.BoardStyle,
                    // ColorName = stockBarcode.ColorName,
                    WorkNo = stockBarcode.WorkNo,
                    WorkLine = stockBarcode.WorkLine,
                    // MemoBad = stockBarcode.MemoBad,
                    ComeFlg = 5,
                    // Memo = stockBarcode.Memo,
                    SuppId = stockBarcode.SuppId,
                    SuppNo = stockBarcode.SuppNo,
                    InsDate = stockBarcode.IndepDate, // Added InsDate
                    ItemId = stockBarcode.ItemId
                    // ItemUnit = stockBarcode.ItemUnit // Added ItemUnit
                }).IgnoreColumns(true).ExecuteCommand();
 
                // 更新原条码数量
                executeCommand += db.Updateable<MesInvItemBarcodes>()
                    .SetColumns(it => it.Quantity == totalQty - query.Num)
                    .Where(it => it.ItemBarcode == query.barcode)
                    .ExecuteCommand();
 
                // 删除原条码库存记录
                executeCommand += db.Deleteable<MesInvItemStocks>()
                    .Where(it => it.ItemBarcode == query.barcode)
                    .ExecuteCommand();
 
                // 插入剩余条码数量的新库存记录
                executeCommand += db.Insertable(new MesInvItemStocks
                {
                    Guid = Guid.NewGuid(),
                    TaskNo = stockBarcode.TaskNo,
                    ItemBarcode = stockBarcode.ItemBarcode,
                    ItemNo = stockBarcode.ItemNo,
                    LotNo = stockBarcode.LotNo,
                    Quantity = totalQty - query.Num,
                    EpFlag = stockBarcode.EpFlag,
                    CustomerNo = stockBarcode.CustomerNo,
                    ItemWt = stockBarcode.ItemWt,
                    DepotsCode = stockBarcode.DepotsCode,
                    DepotsId = stockBarcode.DepotsId,
                    DepotSectionsCode = stockBarcode.DepotSectionsCode,
                    CheckDate = stockBarcode.CheckDate,
                    ItemType = stockBarcode.ItemType,
                    IndepDate = stockBarcode.IndepDate,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    IqcStatus = stockBarcode.IqcStatus,
                    BoardStyle = stockBarcode.BoardStyle,
                    WorkNo = stockBarcode.WorkNo,
                    WorkLine = stockBarcode.WorkLine,
                    SuppNo = stockBarcode.SuppNo,
                    ItemId = stockBarcode.ItemId
                    // UnitId = stockBarcode.ItemUnit
                }).IgnoreColumns(true).ExecuteCommand();
 
                // 写入新条码的交易记录
                executeCommand += db.Insertable(new MesInvBusiness2
                {
                    Guid = Guid.NewGuid(),
                    Status = 1,
                    BillTypeId = 200, // p_bill_type_id
                    TransactionCode = "220", // p_transaction_no
                    BusinessType = -1,
                    ItemBarcode = newBarcode,
                    ItemNo = stockBarcode.ItemNo,
                    LotNo = stockBarcode.LotNo,
                    EpFlag = true,
                    Quantity = query.Num,
                    FromInvDepotsCode = null,
                    FromInvDepotSectionsCode = null,
                    ToInvDepotsCode = stockBarcode.DepotsCode,
                    ToInvDepotSectionsCode = stockBarcode.DepotSectionsCode,
                    Description = null,
                    CreateBy = query.userName,
                    CreateDate = DateTime.Now,
                    LastupdateBy = query.userName,
                    LastupdateDate = DateTime.Now,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    TaskNo = stockBarcode.TaskNo,
                    BillNo = stockBarcode.BillNo,
                    WorkNo = stockBarcode.WorkNo,
                    WorkLine = stockBarcode.WorkLine,
                    SuppNo = stockBarcode.SuppNo,
                    SuppId = stockBarcode.SuppId,
                    ItemId = stockBarcode.ItemId
                    // CkDepot = stockBarcode.DepotsId
                }).IgnoreColumns(true).ExecuteCommand();
            }
            else if (totalQty < query.Num)
            {
                throw new Exception("发料数量大于条码数,请核对!");
            }
 
            if (string.IsNullOrEmpty(newBarcode)) newBarcode = query.barcode;
 
            // 检查补料单状态
            var mesItemBl = Db.Queryable<MesItemBl>()
                .Where(a => a.BlNo == query.blNo && (a.Bl018 ?? false) == false)
                .First();
 
            if (mesItemBl == null)
                throw new Exception($"申请单 {query.blNo} 已撤回!");
 
            if (mesItemBl.Bl018 != true)
                throw new Exception($"申请单 {query.blNo} 未审核!");
 
            if (mesItemBl.Bl019 == true)
                throw new Exception($"申请单 {query.blNo} 已完结!");
 
            // 获取补料单明细并校验
            var blDetail = Db.Queryable<MesItemBlDetail>()
                .Where(b =>
                    b.Mid == mesItemBl.Id && b.Bld012 == stockBarcode.ItemId)
                .First();
 
            if (blDetail == null)
                throw new Exception($"申请单不存在此物料 {stockBarcode.ItemNo} 请确认!");
 
            var remainingQty = (blDetail.Bld007 ?? 0) - (blDetail.Bld008 ?? 0);
            if (remainingQty == 0)
                throw new Exception("物料已扫码完成,请核对!");
 
            if (query.Num > remainingQty)
                throw new Exception(
                    $"拆分数量:{query.Num} 大于待发料数量:{remainingQty},请核对!");
 
            // 检查工单信息
            var womdaa = Db.Queryable<WwGd>()
                .Where(a => a.Daa001 == query.billNo)
                .First();
 
            if (womdaa == null)
                throw new Exception($"工单 {query.billNo} 不存在,请确认!");
 
            var womdab = Db.Queryable<WwGdDetail>()
                .Where(b =>
                    b.Dab001 == query.billNo && b.Erpid == blDetail.Bld014)
                .First();
 
            if (womdab == null)
                throw new Exception($"备料明细不存在此物料 {stockBarcode.ItemNo} 请确认!");
 
            // 检查已发料数量是否超过待发料数量
            var sumQty = db.Queryable<MesInvItemOutCDetails>()
                .Where(it =>
                    it.TaskNo == query.blNo && it.ItemId == stockBarcode.ItemId)
                .Sum(it => it.Quantity);
 
            if (sumQty > remainingQty)
                throw new Exception(
                    $"拆分数量:{sumQty} 大于待发料数量:{remainingQty},请核对!");
 
            // 获取或创建出库单
            var itemOut = db.Queryable<MesInvItemOuts>()
                .Where(a => a.BbillNo == query.blNo
                            && a.DepotCode == womdab.Dab017
                            && a.OutDate.Value.Date.ToString("yyyy-MM-dd") ==
                            DateTime.Now.Date.ToString("yyyy-MM-dd")
                            && a.BillTypeId == 200
                            && a.TransactionNo == 220
                            && a.Status == 0)
                .First();
 
            if (itemOut == null)
            {
                // 创建新的出库单
                var outId = Guid.NewGuid();
                var outNo = BillNo.GetBillNo("BL(工单补料)");
 
                // 插入出库单主表
                executeCommand += db.Insertable(new MesInvItemOuts
                {
                    Guid = outId,
                    ItemOutNo = outNo,
                    TaskNo = query.blNo,
                    CreateBy = query.userName,
                    CreateDate = DateTime.Now,
                    LastupdateBy = query.userName,
                    LastupdateDate = DateTime.Now,
                    BillTypeId = 200,
                    TransactionNo = 220,
                    Remark = mesItemBl.Bl007,
                    DepotCode = womdab.Dab017,
                    OutPart = womdaa.Daa013.ToString(),
                    FType = 0,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    // WorkNo = womdaa.Daa021,
                    // BoardItem = womdaa.Daa002,
                    PbillNo = womdaa.Daa001,
                    OutDate = DateTime.Now,
                    Status = 0,
                    BbillNo = query.blNo
                }).IgnoreColumns(true).ExecuteCommand();
            }
 
            // 检查是否已存在出库单明细
            var itemOutItemCount = db.Queryable<MesInvItemOutItems>()
                .Where(it =>
                    it.ItemOutId == itemOut.Guid &&
                    it.ItemId == stockBarcode.ItemId)
                .Count();
 
            if (itemOutItemCount == 0)
                // 插入新的出库单明细
                executeCommand += db.Insertable(new MesInvItemOutItems
                {
                    Guid = Guid.NewGuid(),
                    ItemOutId = itemOut.Guid,
                    ItemNo = blDetail.Bld002,
                    Quantity = query.Num,
                    CreateBy = query.userName,
                    CreateDate = DateTime.Now,
                    LastupdateBy = query.userName,
                    LastupdateDate = DateTime.Now,
                    Factory = stockBarcode.Factory,
                    Company = stockBarcode.Company,
                    DepotCode = womdab.Dab017,
                    TaskNo = query.blNo,
                    // WorkNo = womdaa.Daa021,
                    WorkLine = blDetail.Bld013,
                    ErpItemNo = womdab.Dab003.ToString(),
                    ErpId = womdab.Eid,
                    ErpAutoid = womdab.Erpid,
                    PbillNo = query.billNo,
                    ItemId = blDetail.Bld012
                    // Unit = blDetail.Bld009,
                    // DepotId = (int)stockBarcode.DepotsId
                }).IgnoreColumns(true).ExecuteCommand();
            else
                // 更新已有出库单明细数量
                executeCommand += db.Updateable<MesInvItemOutItems>()
                    .SetColumns(it => it.Quantity == it.Quantity + query.Num)
                    .Where(it =>
                        it.ItemOutId == itemOut.Guid &&
                        it.ItemId == stockBarcode.ItemId)
                    .ExecuteCommand();
 
            // 插入出库条码明细
            executeCommand += db.Insertable(new MesInvItemOutCDetails
            {
                Guid = Guid.NewGuid(),
                ItemOutId = itemOut.Guid,
                ItemBarcode = newBarcode ?? query.barcode,
                ItemNo = stockBarcode.ItemNo,
                LotNo = stockBarcode.LotNo,
                Quantity = query.Num,
                ForceOutFlag = 0,
                CreateBy = query.userName,
                CreateDate = DateTime.Now,
                LastupdateBy = query.userName,
                LastupdateDate = DateTime.Now,
                DepotCode = stockBarcode.DepotsCode,
                DepotSectionCode = stockBarcode.DepotSectionsCode,
                Remark = blDetail.Bld010,
                Factory = stockBarcode.Factory,
                Company = stockBarcode.Company,
                TaskNoy = mesItemBl.Bl013,
                BoardStyle = mesItemBl.Bl002,
                TaskNo = query.blNo,
                WorkNo = blDetail.Bld001,
                WorkLine = blDetail.Bld013,
                SuppNo = stockBarcode.SuppNo,
                PbillNo = query.billNo,
                ItemId = blDetail.Bld012,
                Unit = blDetail.Bld009,
                DepotId = (int)stockBarcode.DepotsId
            }).IgnoreColumns(true).ExecuteCommand();
 
            // 插入业务流水
            executeCommand += db.Insertable(new MesInvBusiness2
            {
                Guid = Guid.NewGuid(),
                Status = 1,
                BillTypeId = 200, // p_bill_type_id
                TransactionCode = "210", // p_transaction_no 
                BusinessType = 1,
                ItemBarcode = newBarcode ?? query.barcode,
                ItemNo = stockBarcode.ItemNo,
                LotNo = stockBarcode.LotNo,
                EpFlag = true,
                Quantity = query.Num,
                FromInvDepotsCode = stockBarcode.DepotsCode,
                FromInvDepotSectionsCode = stockBarcode.DepotSectionsCode,
                Description = null,
                CreateBy = query.userName,
                CreateDate = DateTime.Now,
                LastupdateBy = query.userName,
                LastupdateDate = DateTime.Now,
                Factory = stockBarcode.Factory,
                Company = stockBarcode.Company,
                TaskNo = mesItemBl.Bl012,
                BillNo = query.blNo,
                WorkNo = blDetail.Bld001,
                WorkLine = blDetail.Bld013,
                SuppNo = stockBarcode.SuppNo,
                ItemId = stockBarcode.ItemId
                // CkDepot = stockBarcode.DepotsId
            }).IgnoreColumns(true).ExecuteCommand();
 
            // 更新工单表数量
            executeCommand += db.Updateable<WwGdDetail>()
                .SetColumns(it => new WwGdDetail
                {
                    Dab007 = (it.Dab007 ?? 0) + (int)query.Num, // 工单数量
                    Dab020 = (it.Dab020 ?? 0) + (int)query.Num, // 已发料数量
                    Dab021 = (it.Dab021 ?? 0) + (int)query.Num // 已发料数量
                })
                .Where(it => it.Id == womdab.Id && it.Dab003 == womdab.Dab003)
                .IgnoreColumns(true)
                .ExecuteCommand();
 
            // 更新补料单明细已补数量
            executeCommand += db.Updateable<MesItemBlDetail>()
                .SetColumns(it => new MesItemBlDetail
                {
                    Bld008 = (it.Bld008 ?? 0) + (int)query.Num
                })
                .Where(it => it.Id == blDetail.Id)
                .ExecuteCommand();
 
            // 获取更新后的补料单明细数量
            var updatedDetail = db.Queryable<MesItemBlDetail>()
                .Where(it => it.Id == blDetail.Id)
                .Select(it => new { it.Bld007, it.Bld008 })
                .First();
 
            if ((updatedDetail.Bld007 ?? 0) <= (updatedDetail.Bld008 ?? 0))
                // 更新明细完成状态
                executeCommand += db.Updateable<MesItemBlDetail>()
                    .SetColumns(it => new MesItemBlDetail { Bld011 = 1 })
                    .Where(it => it.Id == blDetail.Id)
                    .ExecuteCommand();
 
            // 检查是否还有未完成的明细
 
            var unfinishedDetail = db.Queryable<MesItemBlDetail>()
                .Where(it => it.Mid == mesItemBl.Id && (it.Bld011 ?? 0) == 0)
                .First();
 
            if (unfinishedDetail == null)
                // 如果没有找到未完成明细,则更新补料单状态为已完成
                executeCommand += db.Updateable<MesItemBl>()
                    .SetColumns(it => new MesItemBl
                    {
                        Bl019 = true,
                        WcUser = query.userName,
                        WcTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    })
                    .Where(it => it.Id == mesItemBl.Id)
                    .ExecuteCommand();
 
            if (executeCommand <= 1) throw new Exception("更新失败");
 
            return executeCommand;
        }) > 0;
 
        // 获取最终的待发料明细列表
        var pendingList = Db.Queryable<MesItemBl, MesItemBlDetail>((a, b) =>
                new JoinQueryInfos(JoinType.Left, a.Id == b.Mid))
            .Where((a, b) => a.BlNo == query.blNo
                             && (b.Bld007 ?? 0) - (b.Bld008 ?? 0) > 0)
            .Select((a, b) => new MesItemBlDetail
            {
                Bld012 = b.Bld012,
                Bld002 = b.Bld002,
                Bld003 = b.Bld003,
                Bld004 = b.Bld004,
                Bld007 = b.Bld007,
                Bld008 = b.Bld008
            })
            .ToList();
 
        return (success, pendingList);
    }
 
    #endregion
}