1
yangpeixing
2026-01-22 2a978847c0dfef510349b097ef8202afe5647997
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
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
using AutoMapper;
using MailKit.Search;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_BasicRepository;
using WIDESEA_Common;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.CodeConfigEnum;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_Core.Utilities;
using WIDESEA_DTO;
using WIDESEA_DTO.Basic;
using WIDESEA_DTO.ERP;
using WIDESEA_DTO.Inbound;
using WIDESEA_DTO.Outbound;
using WIDESEA_IBasicRepository;
using WIDESEA_IBasicService;
using WIDESEA_IInboundRepository;
using WIDESEA_IInboundService;
using WIDESEA_InboundRepository;
using WIDESEA_IStockRepository;
using WIDESEA_IStockService;
using WIDESEA_ITaskInfoRepository;
using WIDESEA_Model.Models;
using WIDESEA_Model.Models.Inbound;
using static WIDESEA_Common.HouseInventoryIn;
using static WIDESEA_Common.HouseSyncretism;
using static WIDESEA_Common.InventoryAllocate;
using Parameter = WIDESEA_Common.Parameter;
 
namespace WIDESEA_InboundService
{
    public partial class InboundOrderService : ServiceBase<Dt_InboundOrder, IInboundOrderRepository>, IInboundOrderService
    {
        private readonly IMapper _mapper;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly ITaskRepository _taskRepository;
        private readonly IInboundRepository _inboundRepository;
        private readonly IBasicRepository _basicRepository;
        private IBasicService _basicService;
        private IStockService _stockService;
        private IInboundOrderDetailService _inboundOrderDetailService;
        private IInboundOrder_HtyService _inboundOrderHtyService;
        private IInboundOrderDetail_HtyService _inboundOrderDetail_HtyService;
        private IWarehouseService _warehouseService;
        private readonly IStockRepository _stockRepository;
        private IPalletTypeInfoRepository _palletTypeInfoRepository;
        private readonly IReturnOrderRepository _returnOrderRepository;
        private readonly ICPInboundOrderDetailRepository _cPInboundOrderDetailRepository;
 
 
        public IInboundOrderRepository Repository => BaseDal;
 
        public InboundOrderService(IInboundOrderRepository BaseDal, IMapper mapper, IBasicService basicService, IBasicRepository basicRepository, IInboundRepository inboundRepository, IUnitOfWorkManage unitOfWorkManage, ITaskRepository taskRepository, IStockService stockService, IInboundOrderDetailService inboundOrderDetailService, IInboundOrder_HtyService inboundOrderHtyService, IInboundOrderDetail_HtyService inboundOrderDetail_HtyService, IWarehouseService warehouseService, IStockRepository stockRepository, IPalletTypeInfoRepository palletTypeInfoRepository, IReturnOrderRepository returnOrderRepository, ICPInboundOrderDetailRepository cPInboundOrderDetailRepository) : base(BaseDal)
        {
            _mapper = mapper;
            _unitOfWorkManage = unitOfWorkManage;
            _taskRepository = taskRepository;
            _stockService = stockService;
            _inboundRepository = inboundRepository;
            _basicRepository = basicRepository;
            _inboundOrderDetailService = inboundOrderDetailService;
            _inboundOrderHtyService = inboundOrderHtyService;
            _inboundOrderDetail_HtyService = inboundOrderDetail_HtyService;
            _basicService = basicService;
            _warehouseService = warehouseService;
            _stockRepository = stockRepository;
            _palletTypeInfoRepository = palletTypeInfoRepository;
            _returnOrderRepository = returnOrderRepository;
            _cPInboundOrderDetailRepository = cPInboundOrderDetailRepository;
        }
 
        /// <summary>
        /// PDA扫码组盘
        /// </summary>
        /// <param name="materielGroupDTO"></param>
        /// <returns></returns>
        public WebResponseContent MaterielGroup(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
 
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var palletCode = saveModel.MainData["palletCode"].ToString();
                var warehouseId = saveModel.MainData["warehouseId"].ObjToInt();
                var Initiallife = saveModel.MainData["initiallife"].ObjToInt();
                List<string> serialNumbers = new List<string>();
                List<decimal> quantitys = new List<decimal>();
                foreach (var item in saveModel.DelKeys)
                {
                    string json = JsonConvert.SerializeObject(item);
                    Dictionary<string, object> delKeyDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
 
 
                    if (delKeyDict.TryGetValue("serialNumber", out object serialNumberObj))
                    {
                        string serialNumber = serialNumberObj?.ToString();
                        if (!string.IsNullOrEmpty(serialNumber))
                        {
                            serialNumbers.Add(serialNumber);
                        }
                        else
                        {
                            return WebResponseContent.Instance.Error("serialNumber的值为空");
                        }
                    }
                    if (delKeyDict.TryGetValue("quantity", out object quantityObj))
                    {
                        if (quantityObj == null)
                        {
                            return WebResponseContent.Instance.Error("物料数量的值为空");
                        }
                        decimal quantity;
                        try
                        {
                            quantity = Convert.ToDecimal(quantityObj);
                        }
                        catch
                        {
                            return WebResponseContent.Instance.Error($"物料数量{quantityObj}无法转换为数字");
                        }
                        if (quantity <= 0)
                        {
                            return WebResponseContent.Instance.Error("物料数量必须大于0");
                        }
 
                        quantitys.Add(quantity);
                    }
                    else
                    {
                        return WebResponseContent.Instance.Error("缺少物料数量字段");
                    }
                }
                Dt_Warehouse warehouse = _warehouseService.Repository.QueryFirst(x => x.WarehouseId == warehouseId);
                if (warehouse == null)
                {
                    return WebResponseContent.Instance.Error($"未找到该仓库信息");
                }
 
                Dt_InboundOrder inboundOrder = BaseDal.Db.Queryable<Dt_InboundOrder>().Where(x => x.OrderNo == orderNo && x.WarehouseId == warehouse.WarehouseId).Includes(x => x.Details).First();
                if (inboundOrder == null)
                {
                    return WebResponseContent.Instance.Error($"未找到入库单信息");
                }
                if (inboundOrder.Details == null || inboundOrder.Details.Count <= 0)
                {
                    return WebResponseContent.Instance.Error($"未找到入库单明细信息");
                }
                List<MatSerNumAnalysisModel> models = CodeAnalysisHelper.CodeAnalysis<MatSerNumAnalysisModel>(AnalysisCodeEnum.MatSerNumAnalysis, serialNumbers);
                //验证判断时间格式
                WebResponseContent IsValidContent = IsValidMCDates(models);
                if (!IsValidContent.Status)
                {
                    return content.Error(IsValidContent.Message);
                }
 
                string materielCode = models.FirstOrDefault()?.MaterielCode ?? "";
                Dt_MaterielInfo materielInfo = _basicRepository.MaterielInfoRepository.QueryFirst(x => x.MaterielCode == materielCode);
                if (materielInfo == null)
                {
                    return WebResponseContent.Instance.Error($"未找到该物料的信息");
                }
                List<Dt_InboundOrderDetail> inboundOrderDetails = new List<Dt_InboundOrderDetail>();
                ///找数量匹配的
                if (warehouse.WarehouseCode.Contains("BC"))
                {
                    inboundOrderDetails = inboundOrder.Details.Where(x => x.MaterielCode == materielCode && x.SupplierBatch == (models.FirstOrDefault()?.LotNo ?? "") && x.OrderQuantity > x.ReceiptQuantity && x.OrderQuantity == (quantitys.FirstOrDefault())).ToList();
                }
                else
                {
                    inboundOrderDetails = inboundOrder.Details.Where(x => x.MaterielCode == materielCode && x.BatchNo == (models.FirstOrDefault()?.LotNo ?? "")).ToList();
                }
 
 
                if (inboundOrderDetails == null || inboundOrderDetails.Count <= 0)
                {
                    return WebResponseContent.Instance.Error($"未在入库单明细中找到该物料信息或数量不匹配");
                }
                var inboundOrderDet = inboundOrderDetails.FirstOrDefault();
 
                //Dt_StockInfo? stockInfo = _stockService.StockInfoService.GetStockByPalletCode(palletCode);
 
                decimal beforeQuantity = 0;
 
                Dt_StockInfo stockInfo = _stockRepository.StockInfoRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == palletCode).Includes(x => x.Details).First();
                if (stockInfo == null)
                {
                    stockInfo = new Dt_StockInfo()
                    {
                        BatchNo = inboundOrderDet.BatchNo,
                        PalletCode = palletCode,
                        PalletType = GetPalletType(warehouse, palletCode),//GetPalletType(warehouse, palletCode)
                        IsFull = true,
                        StockStatus = (int)StockStatusEmun.组盘暂存,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                        MaterialType = (int)InventoryMaterialType.原材料,
                        Materialweight = 0,
                        Wlstatus = (int)InventoryMaterialStatus.合格,
                        Mgeneratetime = DateTime.Now,
                        WarehouseId = warehouse.WarehouseId,
                        System = inboundOrder.System,
                        Details = new List<Dt_StockInfoDetail>()
                    };
                }
                else
                {
                    //if (stockInfo.StockStatus != StockStatusEmun.组盘暂存.ObjToInt())
                    //{
                    return WebResponseContent.Instance.Error($"托盘号重复,该托盘已组过物料");
                    //}
                    //beforeQuantity = stockInfo.Details.Sum(x => x.StockQuantity);
                }
 
                if (warehouse.WarehouseCode == WarehouseEnum.SC01_BC.ToString())
                {
                    stockInfo.Remark = Initiallife.ToString();
                    string batchNo = models.FirstOrDefault()?.LotNo ?? "";
                    //Dt_StockInfoDetail existDetail = _stockRepository.StockInfoDetailRepository.QueryFirst(x => x.BatchNo == batchNo);
                    //if (existDetail != null)
                    //{
                    //    return WebResponseContent.Instance.Error($"{batchNo}测试架已存在");
                    //}
                    if (models.Count >= 2)
                    {
                        return WebResponseContent.Instance.Error($"组盘明细不唯一");
                    }
                    //if (palletCode.Substring(0, 1) == "6")
                    //{
                    //    stockInfo.PalletType = PalletTypeEnum.MediumPallet.ObjToInt();
                    //}
                    //else
                    //{
                    //    stockInfo.PalletType = PalletTypeEnum.LargestPallet.ObjToInt();
                    //}
                }
                else if (warehouse.WarehouseCode == WarehouseEnum.SC01_BC.ToString())
                {
                    if (models.Count >= 2)
                    {
                        return WebResponseContent.Instance.Error($"组盘明细不唯一");
                    }
                }
 
                List<Dt_StockInfoDetail> stockInfoDetails = new List<Dt_StockInfoDetail>();
                foreach (var model in models)
                {
 
                    Dt_InboundOrderDetail notGroupDetail = new Dt_InboundOrderDetail();
                    ///找数量匹配的
                    if (warehouse.WarehouseCode.Contains("BC"))
                    {
                        notGroupDetail = inboundOrderDetails.Where(x => x.OrderDetailStatus <= OrderDetailStatusEnum.Inbounding.ObjToInt() && x.MaterielCode == model.MaterielCode && x.SupplierBatch == model.LotNo && x.OrderQuantity > x.ReceiptQuantity).FirstOrDefault();
                    }
                    else
                    {
                        notGroupDetail = inboundOrderDetails.Where(x => x.OrderDetailStatus <= OrderDetailStatusEnum.Inbounding.ObjToInt() && x.MaterielCode == model.MaterielCode && x.BatchNo == model.LotNo && x.OrderQuantity > x.ReceiptQuantity).FirstOrDefault();
                    }
 
 
                    if (notGroupDetail == null)
                    {
                        return WebResponseContent.Instance.Error($"该物料在该入库单中已全部组盘完成");
                    }
                    Dt_StockInfoDetail stockInfoDetail = new Dt_StockInfoDetail()
                    {
                        MaterielCode = inboundOrderDet.MaterielCode,
                        MaterielName = inboundOrderDet.MaterielName,
                        OrderNo = inboundOrder.OrderNo,
                        BatchNo = inboundOrderDet.BatchNo,
                        LinId = inboundOrderDet.LinId,
                        StockQuantity = (quantitys.FirstOrDefault()),
                        Status = (int)StockStatusEmun.组盘暂存,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                        Id = inboundOrderDet.LinId.ObjToInt(),
                        DeliveryNote = model.DeliveryNote,
                        SupplierBatch = inboundOrderDet.SupplierBatch,
                        MaterieSpec = inboundOrderDet.MaterieSpec,
                        OrinalLocation = inboundOrderDet.OrinalLocation
                    };
 
                    if (stockInfo.Id > 0)
                    {
                        stockInfoDetail.StockId = stockInfo.Id;
                    }
                    stockInfo.Details.Add(stockInfoDetail);
 
                    stockInfoDetails.Add(stockInfoDetail);
 
                    decimal decimalReceiptQuantity = Convert.ToDecimal(notGroupDetail.ReceiptQuantity);
                    decimal decimalModelQuantity = Convert.ToDecimal((quantitys.FirstOrDefault()));
                    decimal decimalOrderQuantity = Convert.ToDecimal(notGroupDetail.OrderQuantity);
                    decimalReceiptQuantity += decimalModelQuantity;
                    // 检查是否超出订单数量
                    if (decimalReceiptQuantity > decimalOrderQuantity)
                    {
                        return WebResponseContent.Instance.Error($"组盘数量溢出{decimalReceiptQuantity - decimalOrderQuantity}");
                    }
                    // 转回float类型存储,但比较和计算都使用decimal完成
                    notGroupDetail.ReceiptQuantity = Convert.ToDecimal(decimalReceiptQuantity);
                    if (notGroupDetail.OrderDetailStatus == OrderDetailStatusEnum.New.ObjToInt())
                    {
                        notGroupDetail.OrderDetailStatus = OrderDetailStatusEnum.GroupAndInbound.ObjToInt();
                    }
                }
 
                decimal totalQuantity = stockInfo.Details.Sum(x => x.StockQuantity);
 
                inboundOrder.OrderStatus = InOrderStatusEnum.入库中.ObjToInt();
 
                _unitOfWorkManage.BeginTran();
                if (stockInfo.Id == 0)
                {
                    _stockRepository.StockInfoRepository.Db.InsertNav(stockInfo).Include(x => x.Details).ExecuteCommand();
                }
                else
                {
                    _stockRepository.StockInfoRepository.Db.UpdateNav(stockInfo).Include(x => x.Details, new UpdateNavOptions() { OneToManyInsertOrUpdate = true }).ExecuteCommand();
                }
                _inboundRepository.InboundOrderDetailRepository.UpdateData(inboundOrderDetails);
                _inboundRepository.InboundOrderRepository.UpdateData(inboundOrder);
                _unitOfWorkManage.CommitTran();
                content.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
 
            }
            return content;
        }
 
        //药水,低温仓组盘
        public WebResponseContent NewMaterielGroup(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
 
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var palletCode = saveModel.MainData["palletCode"].ToString();
                var warehouseId = saveModel.MainData["warehouseId"].ObjToInt();
                var Initiallife = saveModel.MainData["initiallife"].ObjToInt();
                List<string> serialNumbers = new List<string>();
                List<decimal> quantitys = new List<decimal>();
                foreach (var item in saveModel.DelKeys)
                {
                    string json = JsonConvert.SerializeObject(item);
                    Dictionary<string, object> delKeyDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
 
 
                    if (delKeyDict.TryGetValue("serialNumber", out object serialNumberObj))
                    {
                        string serialNumber = serialNumberObj?.ToString();
                        if (!string.IsNullOrEmpty(serialNumber))
                        {
                            serialNumbers.Add(serialNumber);
                        }
                        else
                        {
                            return WebResponseContent.Instance.Error("serialNumber的值为空");
                        }
                    }
                    if (delKeyDict.TryGetValue("quantity", out object quantityObj))
                    {
                        if (quantityObj == null)
                        {
                            return WebResponseContent.Instance.Error("物料数量的值为空");
                        }
                        decimal quantity;
                        try
                        {
                            quantity = Convert.ToDecimal(quantityObj);
                        }
                        catch
                        {
                            return WebResponseContent.Instance.Error($"物料数量{quantityObj}无法转换为数字");
                        }
                        if (quantity <= 0)
                        {
                            return WebResponseContent.Instance.Error("物料数量必须大于0");
                        }
 
                        quantitys.Add(quantity);
                    }
                    else
                    {
                        return WebResponseContent.Instance.Error("缺少物料数量字段");
                    }
                }
                Dt_Warehouse warehouse = _warehouseService.Repository.QueryFirst(x => x.WarehouseId == warehouseId);
                if (warehouse == null)
                {
                    return WebResponseContent.Instance.Error($"未找到该仓库信息");
                }
 
                Dt_InboundOrder inboundOrder = BaseDal.Db.Queryable<Dt_InboundOrder>().Where(x => x.OrderNo == orderNo && x.WarehouseId == warehouse.WarehouseId).Includes(x => x.Details).First();
                if (inboundOrder == null)
                {
                    return WebResponseContent.Instance.Error($"未找到入库单信息");
                }
                if (inboundOrder.Details == null || inboundOrder.Details.Count <= 0)
                {
                    return WebResponseContent.Instance.Error($"未找到入库单明细信息");
                }
                List<MatSerNumAnalysisModel> models = CodeAnalysisHelper.CodeAnalysis<MatSerNumAnalysisModel>(AnalysisCodeEnum.MatSerNumAnalysis, serialNumbers);
                //验证判断时间格式
                WebResponseContent IsValidContent = IsValidMCDates(models);
                if (!IsValidContent.Status)
                {
                    return content.Error(IsValidContent.Message);
                }
 
                string materielCode = models.FirstOrDefault()?.MaterielCode ?? "";
                Dt_MaterielInfo materielInfo = _basicRepository.MaterielInfoRepository.QueryFirst(x => x.MaterielCode == materielCode);
                if (materielInfo == null)
                {
                    return WebResponseContent.Instance.Error($"未找到该物料的信息");
                }
 
                decimal beforeQuantity = 0;
 
                Dt_StockInfo stockInfo = _stockRepository.StockInfoRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == palletCode).Includes(x => x.Details).First();
                if (stockInfo == null)
                {
                    stockInfo = new Dt_StockInfo()
                    {
                        BatchNo = "",
                        PalletCode = palletCode,
                        PalletType = GetPalletType(warehouse, palletCode),//GetPalletType(warehouse, palletCode)
                        IsFull = true,
                        StockStatus = (int)StockStatusEmun.组盘暂存,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                        MaterialType = (int)InventoryMaterialType.原材料,
                        Materialweight = 0,
                        Wlstatus = (int)InventoryMaterialStatus.合格,
                        Mgeneratetime = DateTime.Now,
                        WarehouseId = warehouse.WarehouseId,
                        System = inboundOrder.System,
                        Details = new List<Dt_StockInfoDetail>()
                    };
                }
                else
                {
                    return WebResponseContent.Instance.Error($"托盘号重复,该托盘已组过物料");
                }
                List<Dt_StockInfoDetail> stockInfoDetails = new List<Dt_StockInfoDetail>();
                foreach (var model in models)
                {
 
                    Dt_InboundOrderDetail notGroupDetail = new Dt_InboundOrderDetail();
 
                    notGroupDetail = inboundOrder.Details.Where(x => x.OrderDetailStatus <= OrderDetailStatusEnum.Inbounding.ObjToInt() && x.MaterielCode == model.MaterielCode && x.BatchNo == model.LotNo).FirstOrDefault();
 
                    if (notGroupDetail == null)
                    {
                        return WebResponseContent.Instance.Error($"该物料在该入库单中已全部组盘完成");
                    }
                    Dt_StockInfoDetail stockInfoDetail = new Dt_StockInfoDetail()
                    {
                        MaterielCode = notGroupDetail.MaterielCode,
                        MaterielName = notGroupDetail.MaterielName,
                        OrderNo = inboundOrder.OrderNo,
                        BatchNo = notGroupDetail.BatchNo,
                        LinId = notGroupDetail.LinId,
                        StockQuantity = model.Quantity,
                        Status = (int)StockStatusEmun.组盘暂存,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                        Id = notGroupDetail.LinId.ObjToInt(),
                        DeliveryNote = model.DeliveryNote,
                        SupplierBatch = notGroupDetail.SupplierBatch,
                        MaterieSpec = notGroupDetail.MaterieSpec,
                        OrinalLocation = notGroupDetail.OrinalLocation
                    };
 
                    if (stockInfo.Id > 0)
                    {
                        stockInfoDetail.StockId = stockInfo.Id;
                    }
                    stockInfo.Details.Add(stockInfoDetail);
 
                    stockInfoDetails.Add(stockInfoDetail);
 
                    decimal decimalReceiptQuantity = Convert.ToDecimal(notGroupDetail.ReceiptQuantity);
                    decimal decimalModelQuantity = Convert.ToDecimal(notGroupDetail.OrderQuantity);
                    decimal decimalOrderQuantity = Convert.ToDecimal(notGroupDetail.OrderQuantity);
                    decimalReceiptQuantity += model.Quantity;
                    // 检查是否超出订单数量
                    if (decimalReceiptQuantity > decimalOrderQuantity)
                    {
                        return WebResponseContent.Instance.Error($"组盘数量溢出{decimalReceiptQuantity - decimalOrderQuantity}");
                    }
                    // 转回float类型存储,但比较和计算都使用decimal完成
                    notGroupDetail.ReceiptQuantity = Convert.ToDecimal(decimalReceiptQuantity);
                    if (notGroupDetail.OrderDetailStatus == OrderDetailStatusEnum.New.ObjToInt())
                    {
                        notGroupDetail.OrderDetailStatus = OrderDetailStatusEnum.GroupAndInbound.ObjToInt();
                    }
                }
 
                decimal totalQuantity = stockInfo.Details.Sum(x => x.StockQuantity);
 
                inboundOrder.OrderStatus = InOrderStatusEnum.入库中.ObjToInt();
 
                _unitOfWorkManage.BeginTran();
                if (stockInfo.Id == 0)
                {
                    _stockRepository.StockInfoRepository.Db.InsertNav(stockInfo).Include(x => x.Details).ExecuteCommand();
                }
                else
                {
                    _stockRepository.StockInfoRepository.Db.UpdateNav(stockInfo).Include(x => x.Details, new UpdateNavOptions() { OneToManyInsertOrUpdate = true }).ExecuteCommand();
                }
                _inboundRepository.InboundOrderDetailRepository.UpdateData(inboundOrder.Details);
                _inboundRepository.InboundOrderRepository.UpdateData(inboundOrder);
                _unitOfWorkManage.CommitTran();
                content.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
 
            }
            return content;
        }
 
        /// <summary>
        /// 成品组盘
        /// </summary>
        /// <param name="materielGroupDTO"></param>
        /// <returns></returns>
        public WebResponseContent CPMaterielGroup(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var palletCode = saveModel.MainData["palletCode"].ToString();
                var warehouseId = saveModel.MainData["warehouseId"].ObjToInt();
                var serialNumbers = new List<string>();
                var quantities = new List<decimal>();
                var lotNos = new List<string>();
                var materielCodes = new List<string>();
 
                foreach (var item in saveModel.DelKeys)
                {
                    var delKeyDict = item as IDictionary<string, object>;
                    if (delKeyDict == null)
                    {
                        string json = JsonConvert.SerializeObject(item);
                        delKeyDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                    }
 
                    // 处理序列号
                    if (!delKeyDict.TryGetValue("serialNumber", out object serialNumberObj) || serialNumberObj == null)
                    {
                        return WebResponseContent.Instance.Error("缺少serialNumber字段或值为空");
                    }
 
                    string serialNumber = serialNumberObj.ToString();
                    if (string.IsNullOrWhiteSpace(serialNumber))
                    {
                        return WebResponseContent.Instance.Error("serialNumber的值为空");
                    }
                    serialNumbers.Add(serialNumber);
                }
                // 获取仓库信息
                Dt_Warehouse warehouse = _warehouseService.Repository.QueryFirst(x => x.WarehouseId == warehouseId);
                if (warehouse == null)
                {
                    return WebResponseContent.Instance.Error($"未找到该仓库信息");
                }
 
                // 获取入库单信息
                Dt_InboundOrder inboundOrder = BaseDal.Db.Queryable<Dt_InboundOrder>()
                    .Where(x => x.OrderNo == orderNo && x.WarehouseId == warehouse.WarehouseId)
                    .Includes(x => x.Details)
                    .First();
 
                if (inboundOrder == null || inboundOrder.Details == null || inboundOrder.Details.Count <= 0)
                {
                    return WebResponseContent.Instance.Error($"未找到入库单信息");
                }
 
                // 批量查询所有相关箱号的CP入库单明细
                List<Dt_CPInboundOrderDetail> CPinboundOrderDetails = BaseDal.Db.Queryable<Dt_CPInboundOrderDetail>()
                    .LeftJoin<Dt_InboundOrderDetail>((cp, d) => cp.OrderDetailId == d.Id)
                    .LeftJoin<Dt_InboundOrder>((cp, d, o) => d.OrderId == o.Id)
                    .Where((cp, d, o) =>
                        o.OrderNo == orderNo &&
                        o.WarehouseId == warehouse.WarehouseId &&
                        serialNumbers.Contains(cp.BoxCode)
                    )
                    .Select((cp, d, o) => cp)
                    .ToList();
 
                //float totalQty = CPinboundOrderDetails.Sum(x => x.QtyOfpcs);
 
 
                // 验证查询到的数据数量是否匹配
                if (CPinboundOrderDetails.Count < serialNumbers.Count)
                {
                    return WebResponseContent.Instance.Error($"未找到所有对应的箱号信息,找到{CPinboundOrderDetails.Count}条,期望{serialNumbers.Count}条");
                }
 
                // 按照箱号分组,用于后续处理
                var cpDetailsByBoxCode = CPinboundOrderDetails
                    .GroupBy(x => x.BoxCode)
                    .ToDictionary(g => g.Key, g => g.ToList());
 
 
                var existingStockBoxCodes = _stockRepository.StockInfoRepository.Db
                .Queryable<Dt_StockInfo>()
                .LeftJoin<Dt_StockInfoDetail>((s, d) => s.Id == d.StockId)
                .LeftJoin<Dt_StockInfoDetailCP>((s, d, cp) => d.Id == cp.StockDetailId)
                .Where((s, d, cp) =>
                    serialNumbers.Contains(cp.BoxCode))
                .Select((s, d, cp) => cp.BoxCode)
                .Distinct()
                .ToList();
 
                if (existingStockBoxCodes.Any())
                {
                    return WebResponseContent.Instance.Error($"以下箱号已在库存中:{string.Join(",", existingStockBoxCodes)}");
                }
 
                // 获取所有相关的入库单明细ID
                var orderDetailIds = CPinboundOrderDetails.Select(x => x.OrderDetailId).Distinct().ToList();
 
                // 查询对应的入库单明细
                List<Dt_InboundOrderDetail> inboundOrderDetails = BaseDal.Db.Queryable<Dt_InboundOrderDetail>()
                    .Where(x => orderDetailIds.Contains(x.Id))
                    .ToList();
 
                if (inboundOrderDetails.Sum(x => x.OrderQuantity) <= inboundOrderDetails.Sum(x => x.ReceiptQuantity))
                {
                    return WebResponseContent.Instance.Error($"此单据已全部组盘完成");
                }
 
                // 按订单明细ID分组,检查每个明细的所有箱号是否都扫描了
                var detailsByOrderDetailId = CPinboundOrderDetails
                    .GroupBy(x => x.OrderDetailId)
                    .ToDictionary(g => g.Key, g => g.ToList());
 
                // 获取相关的订单明细
                List<Dt_InboundOrderDetail> orderDetails = new List<Dt_InboundOrderDetail>();
                List<Dt_InboundOrderDetail> detailsToUpdate = new List<Dt_InboundOrderDetail>();
 
                // 检查每个订单明细是否完成了所有箱号的扫描
                foreach (var kvp in detailsByOrderDetailId)
                {
                    int orderDetailId = kvp.Key;
                    var cpDetails = kvp.Value;
 
                    // 获取订单明细
                    var orderDetail = inboundOrder.Details.FirstOrDefault(x => x.Id == orderDetailId);
                    if (orderDetail == null)
                    {
                        orderDetail = BaseDal.Db.Queryable<Dt_InboundOrderDetail>()
                            .First(x => x.Id == orderDetailId);
                    }
 
                    if (orderDetail == null)
                    {
                        return WebResponseContent.Instance.Error($"未找到订单明细ID:{orderDetailId}");
                    }
 
                    orderDetails.Add(orderDetail);
 
                    // 标记该明细为已完成组盘
                    orderDetail.OrderDetailStatus = OrderDetailStatusEnum.GroupAndInbound.ObjToInt();
                    var recqty = orderDetail.ReceiptQuantity;
                    float totalQty = cpDetails.Sum(item => item.QtyOfpcs);
                    orderDetail.ReceiptQuantity = (decimal)totalQty + recqty; // 收货数量等于订单数量
 
                    detailsToUpdate.Add(orderDetail);
                }
 
 
 
                // 检查托盘是否已存在
                Dt_StockInfo stockInfo = _stockRepository.StockInfoRepository.Db
                    .Queryable<Dt_StockInfo>()
                    .Where(x => x.PalletCode == palletCode)
                    .First();
 
                if (stockInfo == null)
                {
                    // 创建新托盘
                    stockInfo = new Dt_StockInfo()
                    {
                        BatchNo = "", // 使用入库单批次号
                        PalletCode = palletCode,
                        PalletType = GetPalletType(warehouse, palletCode),
                        IsFull = true,
                        StockStatus = (int)StockStatusEmun.组盘暂存,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                        MaterialType = (int)InventoryMaterialType.原材料,
                        Materialweight = 0,
                        Wlstatus = (int)InventoryMaterialStatus.合格,
                        Mgeneratetime = DateTime.Now,
                        WarehouseId = warehouse.WarehouseId,
                        System = inboundOrder.System,
                        Details = new List<Dt_StockInfoDetail>()
                    };
                }
                else
                {
                    // 如果托盘已存在,检查是否已经是组盘暂存状态
                    if (stockInfo.StockStatus != (int)StockStatusEmun.组盘暂存)
                    {
                        return WebResponseContent.Instance.Error($"托盘号重复,该托盘已组过物料");
                    }
                }
 
                List<Dt_CPInboundOrderDetail> cPInboundOrderDetail = new List<Dt_CPInboundOrderDetail>();
                // 创建库存明细 - 按订单明细创建
                foreach (var orderDetail in orderDetails)
                {
                    // 获取该明细对应的所有箱号
                    var detailBoxCodes = detailsByOrderDetailId[orderDetail.Id]
                        .Select(x => x.BoxCode)
                        .ToList();
 
                    cPInboundOrderDetail = BaseDal.Db.Queryable<Dt_CPInboundOrderDetail>().Where(x => detailBoxCodes.Contains(x.BoxCode)).ToList();
 
                    List<Dt_StockInfoDetailCP> stockInfoDetailCP = new List<Dt_StockInfoDetailCP>();
                    foreach (var item in cPInboundOrderDetail)
                    {
                        Dt_StockInfoDetailCP stockInfoDetailCP1 = new Dt_StockInfoDetailCP()
                        {
                            BoxId = item.BoxId,
                            BoxCode = item.BoxCode,
                            DateCode = item.DateCode,
                            JobId = item.JobId,
                            PartNum = item.PartNum,
                            QtyOfpcs = item.QtyOfpcs,
                            QtyOfxout = item.QtyOfxout,
                            CPStockDetailStatus = (int)StockStatusEmun.组盘暂存,
                            Creater = "上游WMS",
                        };
                        stockInfoDetailCP.Add(stockInfoDetailCP1);
 
                        item.CPOrderDetailStatus = InOrderStatusEnum.入库中.ObjToInt();
                    }
 
                    // 创建库存明细
                    Dt_StockInfoDetail stockInfoDetail = new Dt_StockInfoDetail()
                    {
                        MaterielCode = orderDetail.MaterielCode,
                        MaterielName = orderDetail.MaterielName,
                        OrderNo = inboundOrder.OrderNo,
                        BatchNo = orderDetail.BatchNo,
                        SupplierBatch = orderDetail.SupplierBatch,
                        LinId = orderDetail.LinId,
                        StockQuantity = (decimal)cPInboundOrderDetail.Sum(item => item.QtyOfpcs),
                        Status = (int)StockStatusEmun.组盘暂存,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                        Id = orderDetail.LinId.ObjToInt(),
                        //DeliveryNote = orderDetail.DeliveryNote,
                        MaterieSpec = orderDetail.MaterieSpec,
                        StockDetails = stockInfoDetailCP,
                        OrinalLocation = orderDetail.OrinalLocation
                    };
 
                    if (stockInfo.Id > 0)
                    {
                        stockInfoDetail.StockId = stockInfo.Id;
                    }
                    stockInfo.Details.Add(stockInfoDetail);
                }
 
                // 检查入库单是否所有明细都已完成组盘
                bool allDetailsCompleted = inboundOrder.Details.All(x =>
                    detailsToUpdate.Any(d => d.Id == x.Id) ||
                    x.OrderDetailStatus == OrderDetailStatusEnum.GroupAndInbound.ObjToInt());
 
 
 
                // 事务处理
                _unitOfWorkManage.BeginTran();
                try
                {
                    if (stockInfo.Id == 0)
                    {
                        _stockRepository.StockInfoRepository.Db.InsertNav(stockInfo)
                            .Include(x => x.Details).ThenInclude(x => x.StockDetails)
                            .ExecuteCommand();
                    }
                    else
                    {
                        _stockRepository.StockInfoRepository.Db.UpdateNav(stockInfo)
                            .Include(x => x.Details, new UpdateNavOptions()
                            {
                                OneToManyInsertOrUpdate = true
                            }).ThenInclude(x => x.StockDetails)
                            .ExecuteCommand();
                    }
 
                    // 更新订单明细
                    if (detailsToUpdate.Count > 0)
                    {
                        _inboundRepository.InboundOrderDetailRepository.UpdateData(detailsToUpdate);
                    }
 
                    // 更新订单
                    _inboundRepository.InboundOrderRepository.UpdateData(inboundOrder);
 
                    _cPInboundOrderDetailRepository.UpdateData(cPInboundOrderDetail);
 
                    _unitOfWorkManage.CommitTran();
 
                    content = WebResponseContent.Instance.OK("组盘成功");
                }
                catch (Exception ex)
                {
                    _unitOfWorkManage.RollbackTran();
                    throw new Exception($"组盘事务处理失败:{ex.Message}", ex);
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error($"组盘失败:{ex.Message}");
            }
 
            return content;
        }
        public string ReceiveWMSTaskin = WIDESEA_Core.Helper.AppSettings.Configuration["ReceiveWMSTaskin"];
        /// <summary>
        /// 组盘合托
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public WebResponseContent SYMaterielGroup(SaveModel saveModel)
        {
 
            WebResponseContent webResponseContent = new WebResponseContent();
            try
            {
                var soussAddress = saveModel.MainData["soussAddress"];
                var targetAddress = saveModel.MainData["targetAddress"];
 
                Dt_StockInfo stockInfo = _stockRepository.StockInfoRepository.Db.Queryable<Dt_StockInfo>().Includes(x => x.Details).Where(x => x.PalletCode == soussAddress).First();
                Dt_StockInfo targetstockInfo = _stockRepository.StockInfoRepository.Db.Queryable<Dt_StockInfo>().Includes(x => x.Details).Where(x => x.PalletCode == targetAddress).First();
                Dt_Warehouse warehouse = _warehouseService.Repository.QueryFirst(x => x.WarehouseId == targetstockInfo.WarehouseId);
                if (stockInfo == null || targetstockInfo == null)
                {
                    throw new Exception("库存未找到托盘号");
                }
 
                var sameItems = from sourceItem in stockInfo.Details
                                join targetItem in targetstockInfo.Details
                                on new
                                {
                                    sourceItem.BatchNo,
                                    sourceItem.MaterielName,
                                    sourceItem.MaterielCode
                                }
                                equals new
                                {
                                    targetItem.BatchNo,
                                    targetItem.MaterielName,
                                    targetItem.MaterielCode
                                }
                                select new
                                {
                                    SourceItem = sourceItem,
                                    TargetItem = targetItem,
                                    BatchNo = sourceItem.BatchNo,
                                    MaterialCode = sourceItem.MaterielCode,
                                    MaterialType = sourceItem.MaterielName
                                };
 
                var matchedSourceItemIds = sameItems.Select(x => x.SourceItem.Id).ToList();
 
                foreach (var item in stockInfo.Details)
                {
                    if (!matchedSourceItemIds.Contains(item.Id))
                    {
                        item.StockId = targetstockInfo.Id;
                    }
                }
                var differentItems = stockInfo.Details
      .Where(x => !matchedSourceItemIds.Contains(x.Id))
      .ToList();
                targetstockInfo.Details = targetstockInfo.Details
      .Where(x => !matchedSourceItemIds.Contains(x.Id))
      .Concat(differentItems)
      .ToList();
                if (warehouse.WarehouseCode == "SC02_CP")
                {
                    warehouse.WarehouseCode = "SC01_CP";
                }
                if (warehouse.WarehouseCode == "SC02_BC")
                {
                    warehouse.WarehouseCode = "SC01_BC";
                }
                var houseSyncretism = new HouseSyncretism
                {
                    ApiType = "InventoryMoveController",
                    Method = "AsrsSubmitMoveDatas",
 
                    Parameters = new List<HouseSyncretism.Parame>
                    {
                        new HouseSyncretism.Parame {
                            Value =  stockInfo.Details.Select(g => new Parame.Syncretism
                        {
                            Lpn = stockInfo.PalletCode,
                            MoveType = 0,
                            WareHouseCode = warehouse.WarehouseCode,
                            ItemCode = g.MaterielCode,
                            MoveNumber = g.StockQuantity,
                            LotNo = g.BatchNo,
                            WipBatch = g.BatchNo,
                            LocationName = stockInfo.LocationCode,
                            TargetLocName = targetstockInfo.LocationCode,
                            TargetLpn = targetstockInfo.PalletCode,
 
                        }).ToList()
                            }
                    }
                };
                var authResult = AuthenticateWithWMS();
                if (authResult.IsSuccess)
                {
                    houseSyncretism.Context = new Dictionary<string, string>
                                            {
                                                { "Ticket", authResult.Ticket },
                                                { "InvOrgId", authResult.InvOrgId }
 
                                            };
 
                    var response = HttpHelper.Post<MomRequestContent>(ReceiveWMSTaskin, houseSyncretism, "立库入库数量回传WMS");
                    if (!response.Success)
                    {
                        throw new Exception($"操作失败: {response.Message ?? "未提供错误信息"}");
                    }
 
                }
                _unitOfWorkManage.BeginTran();
                foreach (var sameItem in sameItems)
                {
                    sameItem.TargetItem.StockQuantity += sameItem.SourceItem.StockQuantity;
                    _stockRepository.StockInfoDetailRepository.UpdateData(sameItem.TargetItem);
                    _stockRepository.StockInfoDetailRepository.DeleteData(sameItem.SourceItem);
                }
                _stockRepository.StockInfoRepository.UpdateData(targetstockInfo);
                _stockRepository.StockInfoDetailRepository.UpdateData(targetstockInfo.Details);
                _stockRepository.StockInfoRepository.DeleteData(stockInfo);
 
                _unitOfWorkManage.CommitTran();
                webResponseContent = WebResponseContent.Instance.OK("合托成功");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                webResponseContent = WebResponseContent.Instance.Error($"组盘失败:{ex.Message}");
            }
            return webResponseContent;
        }
 
        private (bool IsSuccess, string Ticket, string InvOrgId) AuthenticateWithWMS()
        {
            var authentication = new Authentication
            {
                ApiType = "AuthenticationController",
                Parameters = new List<Parameter>
        {
            new Parameter { Value = "LK-Admin" },
            new Parameter { Value = "LK-Admin" }
        },
                Method = "Login",
            };
 
            var response = HttpHelper.Post<WebResponseContent>(ReceiveWMSTaskin, authentication, "登录WMS账号");
 
            if (response.Context != null)
            {
                return (true, response.Context["Ticket"].ToString(), response.Context["InvOrgId"].ToString());
            }
 
            return (false, null, null);
        }
 
 
        public int GetPalletType(Dt_Warehouse warehouse, string palletCode)
        {
 
            if (warehouse.WarehouseCode == WarehouseEnum.SC01_DW.ObjToString())
            {
                Dt_PalletTypeInfo palletTypeInfo = _palletTypeInfoRepository.QueryFirst(x => x.CodeStartStr == palletCode.Substring(0, 3));
                if (palletTypeInfo == null)
                {
                    throw new Exception($"托盘号错误");
                }
                return palletTypeInfo.PalletType;
            }
 
 
            //else if (warehouse.WarehouseCode == WarehouseEnum.HA152.ObjToString())
            //{
            //    Dt_PalletTypeInfo palletTypeInfo = _palletTypeInfoRepository.QueryFirst(x => x.CodeStartStr == palletCode.Substring(0, 2));
            //    if (palletTypeInfo == null)
            //    {
            //        throw new Exception($"托盘号错误");
            //    }
            //    return palletTypeInfo.PalletType;
            //}
            //else if (warehouse.WarehouseCode == WarehouseEnum.HA57.ObjToString())
            //{
            //    Dt_PalletTypeInfo palletTypeInfo = _palletTypeInfoRepository.QueryFirst(x => x.CodeStartStr == palletCode.Substring(0, 3));
            //    if (palletTypeInfo == null)
            //    {
            //        throw new Exception($"托盘号错误");
            //    }
            //    return palletTypeInfo.PalletType;
            //}
            //else if (warehouse.WarehouseCode == WarehouseEnum.HA58.ObjToString())
            //{
            //    Dt_PalletTypeInfo palletTypeInfo = _palletTypeInfoRepository.QueryFirst(x => x.CodeStartStr == palletCode.Substring(0, 2));
            //    if (palletTypeInfo == null)
            //    {
            //        throw new Exception($"托盘号错误");
            //    }
            //    return palletTypeInfo.PalletType;
            //}
            return -1;
        }
        /// <summary>
        /// 判断正确时间格式
        /// </summary>
        public WebResponseContent IsValidMCDates(List<MatSerNumAnalysisModel> analysisModels)
        {
            string[] effDates = analysisModels.Select(x => x.EffectiveDate).Distinct().ToArray();
            string[] ProDates = analysisModels.Select(x => x.ProductionDate).Distinct().ToArray();
            foreach (string effDate in effDates)
            {
                string format = "yyyy-MM-dd"; // 目标格式
                DateTime parsedDate;
                // 解析并验证格式
                bool isValid = DateTime.TryParseExact(
                    effDate,
                    format,
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None,
                    out parsedDate
                );
 
                if (!isValid)
                {
                    return WebResponseContent.Instance.Error("格式无效或日期不合法");
                }
            }
            foreach (string ProDate in ProDates)
            {
                string format = "yyyy-MM-dd"; // 目标格式
                DateTime parsedDate;
                // 解析并验证格式
                bool isValid = DateTime.TryParseExact(
                    ProDate,
                    format,
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None,
                    out parsedDate
                );
 
                if (!isValid)
                {
                    return WebResponseContent.Instance.Error("格式无效或日期不合法");
                }
            }
            return WebResponseContent.Instance.OK();
        }
 
        /// <summary>
        /// 入库单据下发
        /// </summary>
        /// <param name="orderAddDTO"></param>
        /// <returns></returns>
        public WebResponseContent AddInboundOrders(HouseInbound model)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                _unitOfWorkManage.BeginTran();
                foreach (var item in model.DetailList)
                {
                    //获取物料信息
                    Dt_MaterielInfo materielInfo = _basicRepository.MaterielInfoRepository.QueryFirst(x => x.MaterielCode == item.MaterielCode);
                    if (materielInfo == null)
                    {
                        return content.Error($"物料{item.MaterielCode}不存在!");
                    }
                    Dt_Warehouse warehouse = _basicRepository.WarehouseRepository.QueryFirst(x => x.WarehouseCode == model.InWarehouse);
                    if (warehouse == null)
                    {
                        return content.Error($"未找到仓库信息");
                    }
                    if (warehouse.WarehouseCode.Contains("CP"))
                    {
                        if (item.SupplierBatch == null)
                        {
                            return content.Error("供应商批次不可为空");
                        }
                        Dt_InboundOrder inboundOrderOld = BaseDal.Db.Queryable<Dt_InboundOrder>().Where(x => x.UpperOrderNo == model.AsnNo).Includes(x => x.Details).First();
 
                        if (inboundOrderOld != null)
                        {
                            if (inboundOrderOld.OrderStatus == InOrderStatusEnum.入库完成.ObjToInt())
                            {
                                inboundOrderOld.OrderStatus = InOrderStatusEnum.入库中.ObjToInt();
                                _inboundRepository.InboundOrderRepository.UpdateData(inboundOrderOld);
                            }
                            Dt_InboundOrderDetail orderDetail1 = BaseDal.Db.Queryable<Dt_InboundOrderDetail>().Where(x => x.OrderId == inboundOrderOld.Id).First();
                            Dt_InboundOrderDetail? inboundOrderDetailOld = inboundOrderOld.Details?.FirstOrDefault(x => x.LinId == item.LinId && x.MaterielCode == item.MaterielCode);
                            if (inboundOrderDetailOld != null)
                            {
                                inboundOrderDetailOld.OrderQuantity += item.OrderQuantity;
                                _inboundRepository.InboundOrderDetailRepository.UpdateData(inboundOrderDetailOld);
                            }
                            else
                            {
                                List<Dt_CPInboundOrderDetail> cPInboundOrderDetail = new List<Dt_CPInboundOrderDetail>();
                                foreach (var list in item.BoxList)
                                {
                                    Dt_CPInboundOrderDetail cPInboundOrderDetail1 = new Dt_CPInboundOrderDetail()
                                    {
                                        BoxId = (float)list.BoxId,
                                        BoxCode = list.BoxCode,
                                        DateCode = list.DateCode,
                                        JobId = (float)list.JobId,
                                        PartNum = list.PartNum,
                                        QtyOfpcs = (float)list.QtyOfpcs,
                                        QtyOfxout = (float)list.QtyOfxout,
                                        CPOrderDetailStatus = OrderDetailStatusEnum.New.ObjToInt(),
                                        Creater = "上游WMS",
                                    };
                                    cPInboundOrderDetail.Add(cPInboundOrderDetail1);
                                }
 
                                Dt_InboundOrderDetail orderDetail = new Dt_InboundOrderDetail()
                                {
                                    OrderId = orderDetail1.OrderId,
                                    MaterielCode = item.MaterielCode,
                                    BatchNo = item.BatchNo,
                                    OrderQuantity = item.OrderQuantity,
                                    ReceiptQuantity = 0,
                                    OverInQuantity = 0,
                                    OrderDetailStatus = OrderDetailStatusEnum.New.ObjToInt(),
                                    LinId = item.LinId,
                                    LPNNo = item.LPNNo,
                                    MaterielName = item.MaterielName,
                                    MaterieSpec = item.MaterieSpec,
                                    Creater = "上游WMS",
                                    SupplierBatch = item.SupplierBatch,
                                    OrinalLocation = item.OrinalLocation,
                                    CPDetails = cPInboundOrderDetail
                                };
                                //_inboundRepository.InboundOrderDetailRepository.AddData(orderDetail);
                                Db.InsertNav(orderDetail).Include(x => x.CPDetails).ExecuteCommand();
                            }
                        }
                        else
                        {
                            List<Dt_CPInboundOrderDetail> cPInboundOrderDetail = new List<Dt_CPInboundOrderDetail>();
                            foreach (var list in item.BoxList)
                            {
                                Dt_CPInboundOrderDetail cPInboundOrderDetail1 = new Dt_CPInboundOrderDetail()
                                {
                                    BoxId = (float)list.BoxId,
                                    BoxCode = list.BoxCode,
                                    DateCode = list.DateCode,
                                    JobId = (float)list.JobId,
                                    PartNum = list.PartNum,
                                    QtyOfpcs = (float)list.QtyOfpcs,
                                    QtyOfxout = (float)list.QtyOfxout,
                                    CPOrderDetailStatus = OrderDetailStatusEnum.New.ObjToInt(),
                                    Creater = "上游WMS",
                                };
                                cPInboundOrderDetail.Add(cPInboundOrderDetail1);
                            }
 
                            Dt_InboundOrderDetail orderDetail = new Dt_InboundOrderDetail()
                            {
                                MaterielCode = item.MaterielCode,
                                BatchNo = item.BatchNo,
                                OrderQuantity = item.OrderQuantity,
                                ReceiptQuantity = 0,
                                OverInQuantity = 0,
                                OrderDetailStatus = OrderDetailStatusEnum.New.ObjToInt(),
                                LinId = item.LinId,
                                LPNNo = item.LPNNo,
                                MaterielName = item.MaterielName,
                                MaterieSpec = item.MaterieSpec,
                                Creater = "上游WMS",
                                SupplierBatch = item.SupplierBatch,
                                OrinalLocation = item.OrinalLocation,
                                CPDetails = cPInboundOrderDetail
                            };
 
                            Dt_InboundOrder inboundOrder = new Dt_InboundOrder()
                            {
                                OrderNo = model.AsnNo,
                                UpperOrderNo = model.AsnNo,
                                WarehouseId = warehouse.WarehouseId,
                                //SupplierId = "",
                                OrderStatus = InboundStatusEnum.未开始.ObjToInt(),
                                CreateType = CreateType.UpperSystemPush.ObjToInt(),
                                Remark = "",
                                TransactionCode = model.TransactionCode,
                                InoutType = model.OrderType,
                                OrderType = model.InoutType.ObjToInt(),
                                Creater = "上游WMS",
                                System = model.System,
                                Details = new List<Dt_InboundOrderDetail> { orderDetail }
                            };
                            //switch (model.OrderType)//单据类型
                            //{
                            //    case 1:
                            //        inboundOrder.OrderType = InOrderTypeEnum.Allocat.ObjToInt();
                            //        break;
                            //    case 3:
                            //        inboundOrder.OrderType = InOrderTypeEnum.CustomerRecovery.ObjToInt();
                            //        break;
                            //    case 6:
                            //        inboundOrder.OrderType = InOrderTypeEnum.SaleReturn.ObjToInt();
                            //        break;
                            //    default:
                            //        break;
                            //};
 
 
                            Db.InsertNav(inboundOrder).Include(x => x.Details).ThenInclude(x => x.CPDetails).ExecuteCommand();
                        }
                    }
                    else
                    {
                        if (item.SupplierBatch == null)
                        {
                            return content.Error("供应商批次不可为空");
                        }
                        Dt_InboundOrder inboundOrderOld = BaseDal.Db.Queryable<Dt_InboundOrder>().Where(x => x.UpperOrderNo == model.AsnNo).Includes(x => x.Details).First();
 
                        if (inboundOrderOld != null)
                        {
                            if (inboundOrderOld.OrderStatus == InOrderStatusEnum.入库完成.ObjToInt())
                            {
                                inboundOrderOld.OrderStatus = InOrderStatusEnum.入库中.ObjToInt();
                                _inboundRepository.InboundOrderRepository.UpdateData(inboundOrderOld);
                            }
                            Dt_InboundOrderDetail orderDetail1 = BaseDal.Db.Queryable<Dt_InboundOrderDetail>().Where(x => x.OrderId == inboundOrderOld.Id).First();
                            Dt_InboundOrderDetail? inboundOrderDetailOld = inboundOrderOld.Details?.FirstOrDefault(x => x.LinId == item.LinId && x.MaterielCode == item.MaterielCode);
                            if (inboundOrderDetailOld != null)
                            {
                                inboundOrderDetailOld.OrderQuantity += item.OrderQuantity;
                                inboundOrderDetailOld.OrderDetailStatus = OrderDetailStatusEnum.Inbounding.ObjToInt();
                                _inboundRepository.InboundOrderDetailRepository.UpdateData(inboundOrderDetailOld);
                            }
                            else
                            {
                                Dt_InboundOrderDetail orderDetail = new Dt_InboundOrderDetail()
                                {
                                    OrderId = orderDetail1.OrderId,
                                    MaterielCode = item.MaterielCode,
                                    BatchNo = item.BatchNo,
                                    OrderQuantity = item.OrderQuantity,
                                    ReceiptQuantity = 0,
                                    OverInQuantity = 0,
                                    OrderDetailStatus = OrderDetailStatusEnum.New.ObjToInt(),
                                    LinId = item.LinId,
                                    LPNNo = item.LPNNo,
                                    MaterielName = item.MaterielName,
                                    MaterieSpec = item.MaterieSpec,
                                    Creater = "上游WMS",
                                    SupplierBatch = item.SupplierBatch
                                };
                                _inboundRepository.InboundOrderDetailRepository.AddData(orderDetail);
                            }
                        }
                        else
                        {
                            Dt_InboundOrderDetail orderDetail = new Dt_InboundOrderDetail()
                            {
                                MaterielCode = item.MaterielCode,
                                BatchNo = item.BatchNo,
                                OrderQuantity = item.OrderQuantity,
                                ReceiptQuantity = 0,
                                OverInQuantity = 0,
                                OrderDetailStatus = OrderDetailStatusEnum.New.ObjToInt(),
                                LinId = item.LinId,
                                LPNNo = item.LPNNo,
                                MaterielName = item.MaterielName,
                                MaterieSpec = item.MaterieSpec,
                                Creater = "上游WMS",
                                SupplierBatch = item.SupplierBatch
                            };
 
                            Dt_InboundOrder inboundOrder = new Dt_InboundOrder()
                            {
                                OrderNo = model.AsnNo,
                                UpperOrderNo = model.AsnNo,
                                WarehouseId = warehouse.WarehouseId,
                                //SupplierId = "",
                                OrderStatus = InboundStatusEnum.未开始.ObjToInt(),
                                CreateType = CreateType.UpperSystemPush.ObjToInt(),
                                Remark = "",
                                TransactionCode = model.TransactionCode,
                                InoutType = model.OrderType,
                                OrderType = model.InoutType.ObjToInt(),
                                Creater = "上游WMS",
                                System = model.System,
                                Details = new List<Dt_InboundOrderDetail> { orderDetail }
                            };
                            //switch (model.OrderType)//单据类型
                            //{
                            //    case 1:
                            //        inboundOrder.OrderType = InOrderTypeEnum.Allocat.ObjToInt();
                            //        break;
                            //    case 3:
                            //        inboundOrder.OrderType = InOrderTypeEnum.CustomerRecovery.ObjToInt();
                            //        break;
                            //    case 6:
                            //        inboundOrder.OrderType = InOrderTypeEnum.SaleReturn.ObjToInt();
                            //        break;
                            //    default:
                            //        break;
                            //};
                            Db.InsertNav(inboundOrder).Include(x => x.Details).ExecuteCommand();
 
                        }
                    }
                }
                _unitOfWorkManage.CommitTran();
                content = WebResponseContent.Instance.OK();
                //InboundOrderAddDTO orderAddDTO1 = new InboundOrderAddDTO();
                //orderAddDTO1.OrderNo = orderAddDTO.AsnNo;
                //orderAddDTO1.UpperOrderNo = orderAddDTO.AsnNo;
                //orderAddDTO1.OutWareHouse = orderAddDTO.InWarehouse;
                //orderAddDTO1.TransactionCode = orderAddDTO.TransactionCode;
                //orderAddDTO1.InoutType = orderAddDTO.OrderType;
                //orderAddDTO1.OrderType = orderAddDTO.InoutType.ObjToInt();
                //orderAddDTO1.Details = orderAddDTO.DetailList.DicToIEnumerable<InboundOrderDetailAddDTO>();
                //#region 验证数据
                //(bool, string, object?) result = CheckInboundOrderAddData(orderAddDTO1);
                //if (!result.Item1) return content = WebResponseContent.Instance.Error(result.Item2);
                //#endregion
 
                //Dt_InboundOrder inboundOrder = _mapper.Map<Dt_InboundOrder>(orderAddDTO1);
                //inboundOrder.OrderStatus = InboundStatusEnum.未开始.ObjToInt();
                //inboundOrder.Creater = "WMS";
                //inboundOrder.CreateDate = DateTime.Now;
                //bool a = BaseDal.Db.InsertNav(inboundOrder).Include(x => x.Details).ExecuteCommand();
 
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content = WebResponseContent.Instance.Error(ex.Message);
 
            }
            finally
            {
 
            }
            return content;
        }
        /// <summary>
        /// 盘点入库
        /// </summary>
        /// <returns></returns>
        public WebResponseContent InventoryIn(string name)
        {
            WebResponseContent content = new();
            try
            {
                //Dt_StockInfoDetail stockInfoDetail = _stockService.StockInfoDetailService.Repository.QueryFirst(x => x.OrderNo == name);
                ////Dt_OutboundOrderDetail outboundOrderDetail= 
                //HouseInventoryIn houseInventoryIn1 = new HouseInventoryIn();
                //houseInventoryIn1.No = name;
                //InventoryIn inventoryIn = new InventoryIn();
                //inventoryIn.LinId = stockInfoDetail.LinId;
                ////inventoryIn.LPN_No =stockInfoDetail.
                //inventoryIn.MaterielCode = stockInfoDetail.MaterielCode;
                //inventoryIn.OrderQuantity = stockInfoDetail.StockQuantity;
                //inventoryIn.BatchNo = stockInfoDetail.BatchNo;
                //inventoryIn.FinishQty = stockInfoDetail.FinishQty;
                //inventoryIn.WarehouseCode =
                //  inventoryIn.StorageAreaCode =
                //  inventoryIn.StorageLocationCode =
                //          #region 验证数据
                //(bool, string, object ?) result = CheckInboundOrderAddData(orderAddDTO1);
                //          if (!result.Item1) return content = WebResponseContent.Instance.Error(result.Item2);
                //          #endregion
 
                //          Dt_OutboundOrder inboundOrder = _mapper.Map<Dt_OutboundOrder>(orderAddDTO1);
                //          inboundOrder.OrderStatus = InboundStatusEnum.未开始.ObjToInt();
                //          inboundOrder.OrderType = OutOrderTypeEnum.OutInventory.ObjToInt();
                //          inboundOrder.Creater = "WMS";
                //          inboundOrder.CreateDate = DateTime.Now;
                //          bool a = BaseDal.Db.InsertNav(inboundOrder).Include(x => x.Details).ExecuteCommand();
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
 
            }
            return content;
        }
        /// <summary>
        /// 入库单据取消
        /// </summary>
        /// <param name="houseInventoryIn"></param>
        /// <returns></returns>
        public WebResponseContent CancelIn(HouseCancelIn houseCancelIn)
        {
            WebResponseContent content = new();
            try
            {
                InboundOrderAddDTO orderAddDTO1 = new InboundOrderAddDTO();
                orderAddDTO1.OrderNo = houseCancelIn.AsnNo;
                orderAddDTO1.Details = houseCancelIn.DetailList.DicToIEnumerable<InboundOrderDetailAddDTO>();
                Dt_InboundOrder oldOutboundOrder = BaseDal.Db.Queryable<Dt_InboundOrder>().Where(x => x.UpperOrderNo == orderAddDTO1.OrderNo).Includes(x => x.Details).First();
                Dt_InboundOrderDetail dt_InboundOrderDetail = BaseDal.Db.Queryable<Dt_InboundOrderDetail>().Where(x => x.OrderId == oldOutboundOrder.Id).First();
                if (oldOutboundOrder.OrderStatus != InboundStatusEnum.未开始.ObjToInt())
                {
                    return WebResponseContent.Instance.Error("该入库单任务已开始执行,不可取消");
                }
                oldOutboundOrder.OrderStatus = InboundStatusEnum.取消.ObjToInt();
                BaseDal.UpdateData(oldOutboundOrder);
 
                Dt_InboundOrder_Hty inboundOrder_Hty = new Dt_InboundOrder_Hty
                {
                    OrderStatus = oldOutboundOrder.OrderStatus,
                    CreateType = oldOutboundOrder.CreateType,
                    //SourceId = oldOutboundOrder.SourceId,
                    UpperOrderNo = oldOutboundOrder.UpperOrderNo,
                    //OrderNo = oldOutboundOrder.OrderNo,
                    //OutWareHouse = oldOutboundOrder.OutWareHouse,
                    TransactionCode = oldOutboundOrder.TransactionCode,
                    InoutType = oldOutboundOrder.InoutType,
                    OrderType = oldOutboundOrder.OrderType,
                    Creater = "WMS",
                    CreateDate = DateTime.Now,
                };
                _inboundOrderHtyService.AddData(inboundOrder_Hty);
                foreach (var item in oldOutboundOrder.Details)
                {
                    Dt_InboundOrderDetail_Hty dt_InboundOrderDetail_Hty = new Dt_InboundOrderDetail_Hty
                    {
                        OrderId = dt_InboundOrderDetail.OrderId,
                        MaterielCode = dt_InboundOrderDetail.MaterielCode,
                        MaterielName = dt_InboundOrderDetail.MaterielName,
                        BatchNo = dt_InboundOrderDetail.BatchNo,
                        OrderQuantity = dt_InboundOrderDetail.OrderQuantity,
                        ReceiptQuantity = dt_InboundOrderDetail.ReceiptQuantity,
                        OverInQuantity = dt_InboundOrderDetail.OverInQuantity,
                        OrderDetailStatus = dt_InboundOrderDetail.OrderDetailStatus,
                        Creater = "WMS",
                        CreateDate = DateTime.Now,
                    };
                    _inboundOrderDetail_HtyService.AddData(dt_InboundOrderDetail_Hty);
                    _inboundOrderDetailService.DeleteData(item);
                }
                BaseDal.DeleteData(oldOutboundOrder);
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
 
            }
            return content;
        }
 
        public WebResponseContent GetInboundOrders(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                int pageNo = saveModel.MainData["pageNo"].ObjToInt();
                string? orderNo = saveModel.MainData["orderNo"].ToString();
                int warehouseId = saveModel.MainData["warehouseId"].ObjToInt();
                List<Dt_InboundOrder> dt_ReceiveOrders = new List<Dt_InboundOrder>();
                if (string.IsNullOrEmpty(orderNo))
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_InboundOrder>().Where(x => x.OrderStatus < InboundStatusEnum.入库完成.ObjToInt() && x.WarehouseId == warehouseId).Includes(x => x.Details).OrderByDescending(x => x.CreateDate).ToPageList(pageNo, 10);
                }
                else
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_InboundOrder>().Where(x => (x.OrderNo.Contains(orderNo)) && x.OrderStatus < InboundStatusEnum.入库完成.ObjToInt() && x.WarehouseId == warehouseId).Includes(x => x.Details).OrderByDescending(x => x.CreateDate).ToPageList(pageNo, 10);
                }
 
                content.OK(data: dt_ReceiveOrders);
            }
            catch (Exception ex)
            {
                content.Error(ex.Message);
            }
            return content;
        }
        /// <summary>
        /// erp单据下发
        /// </summary>
        /// <param name="addInboundOrder"></param>
        /// <returns></returns>
        public WebResponseContent Save(AddInboundOrderModel addInboundOrder)
        {
            try
            {
                List<Dt_InboundOrderDetail> inboundOrderDetails = new List<Dt_InboundOrderDetail>();
                Random random = new Random();
                if (addInboundOrder.Details != null)
                {
                    foreach (var model in addInboundOrder.Details)
                    {
                        // 生成3位随机数(1-999之间)
                        int randomNum = random.Next(1, 1000);
 
                        // 格式化当前日期为年月日(例如:20230820)
                        string datePart = DateTime.Now.ToString("yyyyMMdd");
                        Dt_InboundOrderDetail inboundOrderDetail = new Dt_InboundOrderDetail()
                        {
                            MaterielCode = model.MaterielCode,
                            MaterielName = model.MaterielName,
                            SupplierBatch = model.SupplierBatch,
                            OrderQuantity = model.OrderQuantity,
                            BatchNo = "PC" + $"{datePart}{randomNum}",
                            OrderDetailStatus = InOrderStatusEnum.未开始.ObjToInt(),
                            Creater = "WMS",
                            CreateDate = DateTime.Now,
 
                        };
                        inboundOrderDetails.Add(inboundOrderDetail);
                    }
                }
                int randomNum2 = random.Next(1, 1000);
                string datePart2 = DateTime.Now.ToString("yyyyMMdd");
                Dt_InboundOrder erpProScrapSheet = new Dt_InboundOrder()
                {
                    OrderNo = "WMSIN" + $"{datePart2}{randomNum2}",
                    UpperOrderNo = "WMSIN" + $"{datePart2}{randomNum2}",
                    WarehouseId = addInboundOrder.WarehouseId,
                    OrderType = OrderTypeEnum.生产入库单.ObjToInt(),
                    InoutType = InoutTypeEnum.OtherIn.ToString(),
                    OrderStatus = InOrderStatusEnum.未开始.ObjToInt(),
                    CreateType = OrderCreateTypeEnum.CreateInSystem.ObjToInt(),
                    System = "WMS",
                    Details = inboundOrderDetails,
                    Creater = "WMS",
                    CreateDate = DateTime.Now,
                };
                _unitOfWorkManage.BeginTran();
                Db.InsertNav(erpProScrapSheet).Include(x => x.Details).ExecuteCommand();
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK();
 
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
 
        }
 
        public string CancelInMaterialWarehousing = WIDESEA_Core.Helper.AppSettings.Configuration["CancelInMaterialWarehousing"];
        /// <summary>
        /// 入库单据取消推送ERP
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public WebResponseContent FeedbackInboundCanceERP(int[] keys)
        {
            try
            {
                List<Dt_InboundOrderDetail> inboundOrderDetails = _inboundRepository.InboundOrderDetailRepository.QueryData(x => keys.Contains(x.Id));
 
                if (inboundOrderDetails == null || inboundOrderDetails.Count == 0)
                {
                    return WebResponseContent.Instance.Error("未找到入库单明细信息");
                }
                if (inboundOrderDetails.FirstOrDefault(x => x.OrderDetailStatus > OrderDetailStatusEnum.New.ObjToInt() && x.OrderDetailStatus != OrderDetailStatusEnum.AssignOverPartial.ObjToInt()) != null)
                {
                    return WebResponseContent.Instance.Error("所选入库单明细存在入库中或已完成");
                }
                Dt_InboundOrder inboundOrder = _inboundRepository.InboundOrderRepository.QueryFirst(x => x.Id == inboundOrderDetails[0].OrderId);
                if (inboundOrder == null)
                {
                    return WebResponseContent.Instance.Error("未通过该明细找到入库单信息");
                }
                if (!inboundOrder.System.Equals("ERP"))
                {
                    return WebResponseContent.Instance.Error("该入库单据非ERP推送,无法取消");
                }
                List<FeedbackInboundOrderERP> feedbackInboundOrders = new List<FeedbackInboundOrderERP>();
                foreach (var item in inboundOrderDetails)
                {
                    FeedbackInboundOrderERP feedbackInbound = new FeedbackInboundOrderERP()
                    {
                        code = inboundOrder.UpperOrderNo,
                        itemId = item.LinId,
                    };
                    feedbackInboundOrders.Add(feedbackInbound);
                }
 
                var response = HttpHelper.Post<WebResponseContent>(CancelInMaterialWarehousing, feedbackInboundOrders, "入库明细取消回传ERP");
                _unitOfWorkManage.BeginTran();
                if (response.Code == 0)
                {
                    _inboundRepository.InboundOrderDetailRepository.DeleteAndMoveIntoHty(inboundOrderDetails, OperateType.人工取消);
 
                    //检查该主订单是否还有剩余明细
                    int remainingDetailsCount = _inboundRepository.InboundOrderDetailRepository
                        .Db.Queryable<Dt_InboundOrderDetail>()
                        .Where(d => d.OrderId == inboundOrder.Id)
                        .Count();
                    //检查明细完成的个数
                    int overCount = _inboundRepository.InboundOrderDetailRepository
                        .Db.Queryable<Dt_InboundOrderDetail>()
                        .Where(d => d.OrderId == inboundOrder.Id && d.OrderDetailStatus == OrderDetailStatusEnum.Over.ObjToInt())
                        .Count();
                    // 如果没有剩余明细,再删除主订单
                    if (remainingDetailsCount == 0)
                    {
                        _inboundRepository.InboundOrderRepository.DeleteAndMoveIntoHty(inboundOrder, OperateType.人工取消);
                    }
                    //如果取消以后明细已经全部完成
                    if (remainingDetailsCount == overCount)
                    {
                        inboundOrder.OrderStatus = InOrderStatusEnum.入库完成.ObjToInt();
                        _inboundRepository.InboundOrderRepository.UpdateData(inboundOrder);
                    }
 
 
                    _unitOfWorkManage.CommitTran();
                    return WebResponseContent.Instance.OK();
                }
                else
                {
                    throw new Exception($"操作失败: {response.Message ?? "未提供错误信息"}");
 
                }
 
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        //反拣回库单
        public WebResponseContent ReceiveReturnOrder(List<HouseReturnOrder> houseReturnOrder)
        {
            try
            {
                Random random = new Random();
                List<Dt_ReturnOrder> returnOrders = new List<Dt_ReturnOrder>();
                _unitOfWorkManage.BeginTran();
                foreach (var item in houseReturnOrder)
                {
                    int randomNum = random.Next(1, 1000);
                    string datePart = DateTime.Now.ToString("yyyyMMdd");
                    Dt_ReturnOrder returnOrder = _returnOrderRepository.QueryFirst(x => x.LPNNo == item.LPNNo && x.OrderStatus == InOrderStatusEnum.未开始.ObjToInt());
                    if (returnOrder == null)
                    {
                        Dt_ReturnOrder newReturnOrder = new Dt_ReturnOrder
                        {
                            OrderType = OrderTypeEnum.反拣回库单.ObjToInt(),
                            MaterielCode = item.MaterielCode,
                            MaterielName = item.MaterielName,
                            MaterieSpec = item.MaterieSpec,
                            BatchNo = item.BatchNo,
                            OrderQuantity = item.OrderQuantity,
                            Remark = item.Remark,
                            LinId = item.LinId,
                            LPNNo = item.LPNNo,
                            LocationCode = item.LocationCode,
                            WarehouseCode = item.WarehouseCode,
                            System = item.System,
                            OrderStatus = InOrderStatusEnum.未开始.ObjToInt(),
                            Creater = "SMOM",
                            CreateDate = DateTime.Now
                        };
                        _returnOrderRepository.AddData(newReturnOrder);
                        Dt_StockInfo stockInfo = _stockRepository.StockInfoRepository.Db.Queryable<Dt_StockInfo, Dt_StockInfoDetail>((stock, detail) => stock.Id == detail.StockId).Where((stock, detail) => stock.PalletCode == item.LPNNo && stock.LocationCode == item.LocationCode).First();
                        Dt_OutboundOrderDetail outboundOrderDetail = new Dt_OutboundOrderDetail();
                        Dt_OutboundOrder outboundOrder = new Dt_OutboundOrder();
                        if (stockInfo == null)
                        {
                            Dt_Warehouse warehouse = _warehouseService.Repository.QueryData(x => x.WarehouseCode == item.WarehouseCode).FirstOrDefault();
                            if (warehouse == null)
                            {
                                return WebResponseContent.Instance.Error($"该仓库编号{item.WarehouseCode}未配置");
                            }
                            Dt_StockInfoDetail stockInfoDetail = new Dt_StockInfoDetail
                            {
                                MaterielCode = item.MaterielCode,
                                MaterielName = item.MaterielName,
                                MaterieSpec = item.MaterieSpec,
                                BatchNo = item.BatchNo,
                                LinId = item.LinId,
                                Status = StockStatusEmun.组盘暂存.ObjToInt(),
                                Creater = "SMOM",
                                CreateDate = DateTime.Now,
                                OrderNo = newReturnOrder.OrderNo,
                                StockQuantity = item.OrderQuantity,
                            };
                            Dt_StockInfo stockInfo1 = new Dt_StockInfo
                            {
                                PalletCode = item.LPNNo,
                                WarehouseId = warehouse.WarehouseId,
                                BatchNo = item.BatchNo,
                                PalletType = GetPalletType(warehouse, item.LPNNo),
                                IsFull = true,
                                StockStatus = (int)StockStatusEmun.反拣入库,
                                Creater = "WMS",
                                CreateDate = DateTime.Now,
                                MaterialType = (int)InventoryMaterialType.原材料,
                                Materialweight = 0,
                                Wlstatus = (int)InventoryMaterialStatus.合格,
                                Mgeneratetime = DateTime.Now,
                                Details = new List<Dt_StockInfoDetail> { stockInfoDetail }
                            };
                            Db.InsertNav(stockInfo1).Include(x => x.Details).ExecuteCommand();
                        }
                        else
                        {
                            outboundOrderDetail = new Dt_OutboundOrderDetail
                            {
                                MaterielCode = item.MaterielCode,
                                MaterielName = item.MaterielName,
                                MaterieSpec = item.MaterieSpec,
                                BatchNo = item.BatchNo,
                                OrderQuantity = stockInfo.Details.Sum(x => x.StockQuantity),
                                Remark = item.Remark,
                                LinId = item.LinId,
                                LPNNo = item.LPNNo,
                                Creater = "SMOM",
                                CreateDate = DateTime.Now,
                                LocationName = item.LocationCode
                            };
                            outboundOrder = new Dt_OutboundOrder
                            {
                                OrderNo = "FJCK" + $"{datePart}{randomNum}",
                                UpperOrderNo = "WMSFJCK" + $"{datePart}{randomNum}",
                                OrderStatus = OutOrderStatusEnum.未开始.ObjToInt(),
                                OrderType = OrderTypeEnum.反拣出库单.ObjToInt(),
                                InoutType = InoutTypeEnum.OtherOut.ToString(),
                                System = item.System,
                                Creater = "SMOM",
                                CreateDate = DateTime.Now,
                                CreateType = OrderCreateTypeEnum.UpperSystemPush.ObjToInt(),
                                Details = new List<Dt_OutboundOrderDetail> { outboundOrderDetail }
                            };
                            Db.InsertNav(outboundOrder).Include(x => x.Details).ExecuteCommand();
                        }
 
                    }
                    else
                    {
                        Dt_StockInfo stockInfo = _stockRepository.StockInfoRepository.Db.Queryable<Dt_StockInfo, Dt_StockInfoDetail>((stock, detail) => stock.Id == detail.StockId).Where((stock, detail) => stock.PalletCode == item.LPNNo && stock.StockStatus == StockStatusEmun.余料退库.ObjToInt()).First();
                        stockInfo.StockStatus = StockStatusEmun.反拣入库.ObjToInt();
                        returnOrder.LinId = item.LinId;
                        returnOrder.System = item.System;
                        returnOrder.WarehouseCode = item.WarehouseCode;
                        returnOrder.LocationCode = item.LocationCode;
                        returnOrder.OrderType = OrderTypeEnum.反拣回库单.ObjToInt();
                        returnOrder.OrderQuantity += item.OrderQuantity;
                        returnOrder.ReceiptQuantity += item.OrderQuantity;
                        _returnOrderRepository.UpdateData(returnOrder);
                        _stockRepository.StockInfoRepository.UpdateData(stockInfo);
 
                    }
                }
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent GetMaterielCode(int warehouseId)
        {
            try
            {
                List<Dt_MaterielInfo> materielInfos = _basicRepository.MaterielInfoRepository.QueryData(x => x.WarehouseId == warehouseId).ToList();
                List<string> materielCodes = materielInfos.Select(x => x.MaterielCode).Distinct().ToList();
                return WebResponseContent.Instance.OK("成功", data: materielCodes);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent GetMaterielName(int warehouseId, string materielCode)
        {
            try
            {
                List<Dt_MaterielInfo> materielInfos = _basicRepository.MaterielInfoRepository.QueryData(x => x.WarehouseId == warehouseId && x.MaterielCode == materielCode).ToList();
                List<string> materielNames = materielInfos.Select(x => x.MaterielName).Distinct().ToList();
                return WebResponseContent.Instance.OK("成功", data: materielNames);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        /// <summary>
        /// 验证单据添加DTO对象
        /// </summary>
        /// <param name="inboundOrderAddDTO">单据添加DTO</param>
        /// <returns></returns>
        //private (bool, string, object?) CheckInboundOrderAddData(InboundOrderAddDTO inboundOrderAddDTO)
        //{
        //    (bool, string, object?) result1 = ModelValidate.ValidateModelData(inboundOrderAddDTO);
        //    if (!result1.Item1) return result1;
 
        //    (bool, string, object?) result2 = ModelValidate.ValidateModelData(inboundOrderAddDTO.Details);
        //    if (!result2.Item1) return result2;
 
        //    IEnumerable<int> inOrderTypes = Enum.GetValues<OrderTypeEmun>().Cast<int>();
        //    if (!inOrderTypes.Contains(inboundOrderAddDTO.OrderType))
        //    {
        //        return (false, "未找到该单据类型", inboundOrderAddDTO);
        //    }
 
        //    List<string> materielCodes = inboundOrderAddDTO.Details.Select(x => x.MaterielCode).ToList();
        //    if (!_basicService.MaterielInfoService.ExsitMateriels(materielCodes))
        //    {
        //        return (false, "有物料信息未录入,请录入物料信息", inboundOrderAddDTO);
        //    }
        //    Dt_Warehouse warehouse = _basicRepository.WarehouseRepository.QueryFirst(x => x.WarehouseCode == inboundOrderAddDTO.OutWareHouse);
        //    if (warehouse == null)
        //    {
        //        return (false, "未找到仓库信息", inboundOrderAddDTO);
        //    }
        //    if (BaseDal.QueryFirst(x => x.OrderName == inboundOrderAddDTO.orderName && !string.IsNullOrEmpty(x.OrderName)) != null)
        //    {
        //        return (false, "单据已存在", inboundOrderAddDTO);
        //    }
        //    return (true, "成功", inboundOrderAddDTO);
        //}
 
 
    }
}