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
using HslCommunication;
using MailKit.Search;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Common;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_IBasicService;
using WIDESEA_ISquareCabinServices;
using WIDESEA_IWMsInfoServices;
using WIDESEA_Model.Models;
 
using static System.Net.WebRequestMethods;
using static WIDESEA_DTO.SquareCabin.OrderDto;
using static WIDESEA_DTO.SquareCabin.TowcsDto;
 
 
namespace WIDESEA_SquareCabinServices
{
    public class CabinOrderServices : ServiceBase<Dt_CabinOrder, IRepository<Dt_CabinOrder>>, ICabinOrderServices
    {
 
        static string SearchDate = "";
        private readonly IBasicService _basicService;
        private readonly IMedicineGoodsServices _medicineGoodsServices;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IInventory_BatchServices _inventory_BatchServices;
        private readonly IInventoryInfoService _inventoryInfoService;
        private readonly ICabinOrderDetailServices _cabinOrderDetailServices;
        private readonly ISupplyTaskService _supplyTaskService;
        public IRepository<Dt_CabinOrder> Repository => BaseDal;
 
        public CabinOrderServices(IRepository<Dt_CabinOrder> BaseDal, IBasicService basicService, IMedicineGoodsServices medicineGoodsServices, IUnitOfWorkManage unitOfWorkManage, IInventory_BatchServices inventory_BatchServices, IInventoryInfoService inventoryInfoService, ICabinOrderDetailServices cabinOrderDetailServices, ICabinOrderHtyServices cabinOrderHtyServices, ICabinOrderDetailHtyServices cabinOrderDetailHtyServices, ISupplyTaskService supplyTaskService) : base(BaseDal)
        {
            _basicService = basicService;
            _medicineGoodsServices = medicineGoodsServices;
            _unitOfWorkManage = unitOfWorkManage;
            _inventory_BatchServices = inventory_BatchServices;
            _inventoryInfoService = inventoryInfoService;
            _cabinOrderDetailServices = cabinOrderDetailServices;
            _supplyTaskService = supplyTaskService;
        }
 
        /// <summary>
        /// 获取上游系统的入库单
        /// </summary>
        /// <param name="searchDate"></param>
        /// <returns></returns>
        //public WebResponseContent GetUpstreamOrder(DateTime searchDate)
        //{
        //    var responseContent = new WebResponseContent();
 
        //    try
        //    {
        //        // 请求地址
        //        var url = "http://127.0.0.1:9090/GYZ2/95fck/inOrder";
 
        //        //// 请求参数
        //        var requestData = new
        //        {
        //            searchDate = searchDate.ToString("yyyy-MM-dd HH:mm:ss")
        //        };
 
        //        // 发起请求
        //        var result = HttpHelper.Post(url, requestData.ToJsonString());
 
        //        // 反序列化
        //        var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstreamOrderInfo>>(result);
 
        //        if (response.resultCode != "0")
        //        {
        //            // 调用异常接口
        //            SendErrorToUpstream(1, "", response.resultMsg ?? "上游接口返回失败", "");
        //            return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
        //        }
 
        //        if (response.data == null || !response.data.Any())
        //        {
        //            return responseContent.OK("无新入库单数据");
        //        }
 
        //        Db.Ado.BeginTran();
        //        List<Dt_CabinOrder> _CabinOrders = new List<Dt_CabinOrder>();
        //        foreach (var order in response.data)
        //        {
        //            try
        //            {
        //                // 插入入库单表
        //                var entityOrder = new Dt_CabinOrder
        //                {
 
        //                    Order_no = order.order_no,
        //                    Order_type = order.order_type,
        //                    Supplier_no = order.supplier_no,
        //                    Account_tiem = order.account_time,
        //                    OdrderStatus = "新建",
        //                };
        //                //var orderId = Db.Insertable(entityOrder).ExecuteReturnIdentity(); //就是返回主键ID。
 
        //                // 插入入库明细表
        //                var detailEntities = order.details.Select(d => new Dt_CabinOrderDetail
        //                {
        //                    //OrderId= orderId,
        //                    Goods_no = d.goods_no,
        //                    Order_qty = d.order_qty,
        //                    Batch_num = d.batch_num,
        //                    Exp_date = d.exp_date,
        //                    Warehouse_no = d.warehouse_no,
        //                    Status = 0,
        //                }).ToList();
        //                entityOrder.Details.AddRange(detailEntities); //建立主对象与子对象的关联关系
        //                _CabinOrders.Add(entityOrder);
 
        //                //自己
        //                /// Db.Insertable(detailEntities).ExecuteCommand();
 
        //                //这里要调用一个接口将上面的信息传给wcs,然后改变状态
        //            }
        //            catch (Exception innerEx)
        //            {
        //                // 针对某条订单报错时,推送异常给上游
        //                SendErrorToUpstream(1, order.order_no, innerEx.Message, "");
        //                throw; // 抛出异常,让外层捕获回滚
        //            }
        //        }
        //        // 批量插入(SqlSugar自动处理主外键关系)
        //        Db.Insertable(_CabinOrders).ExecuteCommand();
        //        Db.Ado.CommitTran();
 
        //        //如果EdiIn完成那么就调用CompleteOrder接口
 
        //        return responseContent.OK("同步入库单成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        // 全局异常时,也推送异常给上游
        //        SendErrorToUpstream(1, "", ex.Message, "");
        //        Db.Ado.RollbackTran();
        //        return responseContent.Error("同步失败: " + ex.Message);
        //    }
        //}
        public WebResponseContent GetCabinOrders(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                int pageNo = saveModel.MainData["pageNo"].ObjToInt();
                string warehouseCode = saveModel.MainData["warehouseId"].ToString();
                string orderNo = saveModel.MainData["orderNo"].ToString();
                List<Dt_CabinOrder> dt_ReceiveOrders = new List<Dt_CabinOrder>();
                if (string.IsNullOrEmpty(orderNo))
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_CabinOrder>().Where(x => (x.OdrderStatus == "新建" || x.OdrderStatus == "开始") && x.Warehouse_no == warehouseCode).Includes(x => x.Details).OrderByDescending(x => x.CreateDate).ToPageList(pageNo, 5);
                }
                else
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_CabinOrder>().Where(x => (x.Order_no.Contains(orderNo) || x.Supplier_no.Contains(orderNo)) && (x.OdrderStatus == "新建" || x.OdrderStatus == "开始") && x.Warehouse_no == warehouseCode).OrderByDescending(x => x.CreateDate).Includes(x => x.Details).ToPageList(pageNo, 5);
                }
 
                content.OK(data: dt_ReceiveOrders);
            }
            catch (Exception)
            {
 
                throw;
            }
            return content;
        }
        public WebResponseContent GetCabinOrderDetail(int pageNo, string orderNo)
        {
            WebResponseContent content = new WebResponseContent();
            Dt_CabinOrder cabinOrder = Db.Queryable<Dt_CabinOrder>().Includes(x => x.Details).First(x => x.Order_no == orderNo);
            List<Dt_CabinOrderDetail> cabinOrderDetails = cabinOrder.Details.Where(x => x.Reservoirarea == pageNo.ToString()).ToList();
            content.OK(data: cabinOrderDetails);
            return content;
        }
        public WebResponseContent FeedbackIn([FromBody] SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                var LocationCode = saveModel.MainData["LocationCode"].ToString();
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var batchNo = saveModel.MainData["batchNo"].ToString();
                var Inqty = saveModel.MainData["Inqty"].ObjToInt();
                var warehouseCode = saveModel.MainData["warehouseCode"].ToString();
                Dt_CabinOrder cabinOrder = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == orderNo && x.Warehouse_no == warehouseCode).Includes(x => x.Details).First();
                if (cabinOrder == null) return WebResponseContent.Instance.Error($"入库单已完成");
                Dt_CabinOrderDetail cabinOrderDetail = cabinOrder.Details.Where(x => x.Batch_num == batchNo && x.Reservoirarea == warehouseCode).First();
                if (cabinOrderDetail == null) return WebResponseContent.Instance.Error($"入库单明细已完成");
                Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == cabinOrderDetail.Goods_no);
                if (materielInfo == null) return WebResponseContent.Instance.Error($"请维护物料编号【{cabinOrderDetail.Goods_no}】的物料信息");
                cabinOrderDetail.Order_Inqty += Inqty;
                if (cabinOrderDetail.Order_Inqty > cabinOrderDetail.Order_qty)
                    return WebResponseContent.Instance.Error($"入库数量不可超出单据数量");
 
                #region 处理入库单,货位,库存,库存批次信息
                _unitOfWorkManage.BeginTran();
 
                #region 入库单
                cabinOrder.OdrderStatus = "开始";
                cabinOrderDetail.OrderDetailStatus = "开始";
                if (cabinOrderDetail.Order_Inqty == cabinOrderDetail.Order_qty)
                {
                    cabinOrderDetail.OrderDetailStatus = "已完成";
                    _cabinOrderDetailServices.Repository.DeleteAndMoveIntoHty(cabinOrderDetail, OperateTypeEnum.自动完成);
                }
                else
                {
                    _cabinOrderDetailServices.Repository.UpdateData(cabinOrderDetail);
                }
                var cabinOrder1 = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == cabinOrder.Order_no).Includes(x => x.Details).First();
                if (cabinOrder1.Details == null || cabinOrder1.Details.Count < 1) cabinOrder.OdrderStatus = "已完成";
                Repository.UpdateData(cabinOrder);
                #endregion
 
                #region 货位
                var location = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == LocationCode);
                if (location == null) return WebResponseContent.Instance.Error($"请维护货位编号【{LocationCode}】的货位信息");
                if (location.EnableStatus == EnableStatusEnum.Disable.ObjToInt())
                    return WebResponseContent.Instance.Error($"货位编号【{LocationCode}】已禁用,请恢复正常再使用");
                if (location.LocationStatus != LocationStatusEnum.InStock.ObjToInt())
                {
                    location.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                    _basicService.LocationInfoService.UpdateData(location);
                }
                #endregion
 
                #region 库存
                Dt_InventoryInfo inventoryInfo = _inventoryInfoService.Repository.QueryFirst(x => x.BatchNo == cabinOrderDetail.Batch_num && x.MaterielCode == cabinOrderDetail.Goods_no && x.LocationCode == LocationCode);
                if (inventoryInfo != null)
                {
                    inventoryInfo.StockQuantity += Inqty;
                    _inventoryInfoService.UpdateData(inventoryInfo);
                }
                else
                {
                    inventoryInfo = new Dt_InventoryInfo()
                    {
                        LocationCode = LocationCode,
                        MaterielCode = materielInfo.MaterielCode,
                        MaterielName = materielInfo.MaterielName,
                        MaterielSpec = materielInfo.MaterielSpec,
                        OutboundQuantity = 0,
                        StockQuantity = Inqty,
                        StockStatus = StockStatusEmun.入库完成.ObjToInt(),
                        ValidityPeriod = cabinOrderDetail.Exp_date,
                        WarehouseCode = cabinOrderDetail.Reservoirarea,
                        SupplyQuantity = 0,
                        InDate = DateTime.Now,
                        BatchNo = cabinOrderDetail.Batch_num,
                        Creater = App.User.UserName,
                        CreateDate = DateTime.Now,
                    };
                    _inventoryInfoService.AddData(inventoryInfo);
                }
                #endregion
 
                #region 任务记录
                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                {
                    WarehouseCode = cabinOrderDetail.Reservoirarea,
                    TaskNum = cabinOrderDetail.Id,
                    TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                    BatchNo = inventoryInfo.BatchNo,
                    MaterielName = inventoryInfo.MaterielName,
                    MaterielCode = inventoryInfo.MaterielCode,
                    MaterielSpec = inventoryInfo.MaterielSpec,
                    TaskType = TaskTypeEnum.InPick.ObjToInt(),
                    CreateDate = DateTime.Now,
                    Creater = App.User.UserName,
                    LocationCode = location.LocationCode,
                    OrderNo = cabinOrder.Order_no,
                    StockQuantity = Inqty,
                    SupplyQuantity = 0,
                    Remark = "入库"
                };
                _supplyTaskService.AddData(supplyTask);
                #endregion
 
                #region 库存批次
                Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.BatchNo == inventoryInfo.BatchNo && x.MaterielCode == inventoryInfo.MaterielCode);
                if (inventory_Batch != null)
                {
                    inventory_Batch.StockQuantity += Inqty;
                    _inventory_BatchServices.UpdateData(inventory_Batch);
                }
                else
                {
                    inventory_Batch = new Dt_Inventory_Batch()
                    {
                        BatchNo = inventoryInfo.BatchNo,
                        CreateDate = inventoryInfo.CreateDate,
                        Creater = inventoryInfo.Creater,
                        MaterielCode = inventoryInfo.MaterielCode,
                        ERPStockQuantity = 0,
                        MaterielName = inventoryInfo.MaterielName,
                        MaterielSpec = inventoryInfo.MaterielSpec,
                        OutboundQuantity = inventoryInfo.OutboundQuantity,
                        ProductionDate = inventoryInfo.ProductionDate,
                        Status = false,
                        StockQuantity = inventoryInfo.StockQuantity,
                        ValidityPeriod = inventoryInfo.ValidityPeriod,
                        SupplyQuantity = inventoryInfo.SupplyQuantity,
                    };
                    _inventory_BatchServices.AddData(inventory_Batch);
                }
                #endregion
 
                _unitOfWorkManage.CommitTran();
                #endregion
 
                content.OK(cabinOrderDetail.Order_Inqty.ToString());
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;
        }
 
        public WebResponseContent GetUpstreamOrder()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 请求地址
                var url = "http://121.37.118.63:80/GYZ2/95fck/inOrder";
                //if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// 请求参数
                var requestData = new
                {
                    //searchDate = SearchDate
                    searchDate = "2022-10-10 20:45:16"  // 正确的格式
                };
                //SearchDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
                // 发起请求
                var result = HttpHelper.Post(url, requestData.ToJsonString());
 
                // 反序列化
                var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstreamOrderInfo>>(result);
 
                if (response.resultCode != "0")
                {
                    // 调用异常接口
                    SendErrorToUpstream(1, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
 
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新入库单数据");
                }
                // 获取所有已存在的入库单号
                var existingOrderNos = BaseDal.Db.Queryable<Dt_CabinOrder>()
                    .Select(x => x.Order_no)
                    .ToList();
 
                // 过滤掉已存在的入库单
                var newOrders = response.data
                    .Where(order => !existingOrderNos.Contains(order.order_no))
                    .ToList();
 
                if (!newOrders.Any())
                {
                    return responseContent.OK("所有入库单已存在,无需新增");
                }
 
                Db.Ado.BeginTran();
                try
                {
                    List<Dt_CabinOrder> _CabinOrders = new List<Dt_CabinOrder>();
                    //存储入库单号
                    List<string> orderNos = new List<string>();
 
                    foreach (var order in newOrders)
                    {
                        var entityOrder = new Dt_CabinOrder
                        {
                            Order_no = order.order_no,
                            //入库单类型
                            Order_type = order.order_type,
                            Supplier_no = order.supplier_no,
                            Account_tiem = order.account_time,
                            OdrderStatus = "新建",
                            Supplier_name = order.supplier_name,
                            Warehouse_no = order.warehouse_no,
                            Details = new List<Dt_CabinOrderDetail>()
                            //Details = order.details.Select(d => new Dt_CabinOrderDetail
                            //{
                            //    //OrderId 要拿到入库单表中的id,如何拿不到就将这个字段改了,改成入库单号
                            //    // SqlSugar InsertNav工作原理先插入主表 (Dt_CabinOrder)//获取生成的主键ID//自动设置子表的关联字段 (OrderId)//再插入(Dt_CabinOrderDetail)
                            //    Goods_no = d.goods_no,
                            //    Order_qty = d.order_qty,
                            //    Batch_num = d.batch_num,
                            //    Exp_date = d.exp_date,
                            //    OrderDetailStatus = "新建",
                            //    Status = order.warehouse_no == "001" ? 0 : 2, //如果是001房那么就是未同步状态,如果不是001房那么就是无需同步状态
                            //}).ToList()
                        };
                        foreach (var item in order.details)
                        {
                            // 将上游入库数量转为正数
                            item.order_qty = Math.Abs(item.order_qty);
                            #region 根据物料编码查询物料信息
                            //Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == item.goods_no);
                            Dt_MedicineGoods materielInfo = BaseDal.Db.Queryable<Dt_MedicineGoods>().Where(x => x.Goods_no == item.goods_no).First();
                            ///根据物料信息大小件属性区分是否入立库 //大件入平库
                            if (materielInfo.MaterielSourceType == MaterielSourceTypeEnum.PurchasePart)
                            {
                                Dt_CabinOrderDetail orderDetail = new Dt_CabinOrderDetail()
                                {
                                    Reservoirarea = order.warehouse_no,
                                    Goods_no = item.goods_no,
                                    Order_qty = item.order_qty,
                                    Batch_num = item.batch_num,
                                    Exp_date = item.exp_date,
                                    OrderDetailStatus = "新建",
                                    Status = 2
                                };
                                entityOrder.Details.Add(orderDetail);
                            }
                            else
                            {
                                Dt_CabinOrderDetail orderDetail = null;
                                var ys = item.order_qty % materielInfo.BoxQty; //不能整除箱规的散件数
                                var xs = item.order_qty / materielInfo.BoxQty;//整箱数量
                                #region 生成立库入库单
 
                                #region 判断是否有散件
                                if (ys > 0)
                                {
                                    orderDetail = new Dt_CabinOrderDetail()
                                    {
                                        Reservoirarea = order.warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = ys,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 0
                                    };
                                    materielInfo.Business_qty += ys;
                                }
                                #endregion
 
                                #region 判断立库库存是否大于立库最低库存数
                                while (materielInfo.Business_qty < materielInfo.MinQty && xs > 0)
                                {
                                    xs--;
                                    if (orderDetail == null)
                                    {
                                        orderDetail = new Dt_CabinOrderDetail()
                                        {
                                            Reservoirarea = order.warehouse_no,
                                            Goods_no = item.goods_no,
                                            Order_qty = materielInfo.BoxQty,
                                            Batch_num = item.batch_num,
                                            Exp_date = item.exp_date,
                                            OrderDetailStatus = "新建",
                                            Status = 0
                                        };
                                        materielInfo.Business_qty += materielInfo.BoxQty;
                                    }
                                    else
                                    {
                                        orderDetail.Order_qty += materielInfo.BoxQty;
                                        materielInfo.Business_qty += materielInfo.BoxQty;
                                    }
                                }
                                #endregion 
 
                                if (orderDetail != null) entityOrder.Details.Add(orderDetail);
                                #endregion
 
                                #region 剩余整件入平库
                                if (xs > 0)
                                {
                                    orderDetail = new Dt_CabinOrderDetail()
                                    {
                                        Reservoirarea = order.warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = materielInfo.BoxQty * xs,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 2
                                    };
                                    entityOrder.Details.Add(orderDetail);
                                }
                                #endregion
                            }
                            //_basicService.MaterielInfoService.Repository.UpdateData(materielInfo);
                            _medicineGoodsServices.Db.Updateable(materielInfo).ExecuteCommand();
                            #endregion
                        }
                        _CabinOrders.Add(entityOrder);
                        orderNos.Add(order.order_no);
                    };
                    BaseDal.Db.InsertNav(_CabinOrders).Include(x => x.Details).ExecuteCommand();
 
                    //在下发给wcs 
                    //var reslut=  EdiIn(); //发给下游
                    //如果这个方法成功了,那么就调用CompleteOrder接口,然后改变
                    Db.Ado.CommitTran();
                    return responseContent.OK("同步入库单成功");
                }
                catch (Exception ex)
                {
                    Db.Ado.RollbackTran();
                    SendErrorToUpstream(1, "", ex.Message, "");
                    return responseContent.Error("同步失败: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                // 全局异常时,也推送异常给上游
                SendErrorToUpstream(1, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
            }
        }
 
        /// <summary>
        /// 传给wcs
        /// </summary>
        public WebResponseContent EdiIn()
        {
            try
            {
                //2.查询符合条件的订单(表头 = 新建 && 包含有效明细)
                //var orders = BaseDal.Db.Queryable<Dt_CabinOrder>()
                //    .Where(o => o.OdrderStatus == "新建")
                //    .Includes(o => o.Details, d => d.MedicineGoods)
                //    .ToList();
                //查出包含全部的入库单,包含全部明细+一个明细对应一个商品
                var orders = BaseDal.Db.CopyNew()
                .Queryable<Dt_CabinOrder>()
                .Where(o => o.OdrderStatus == "新建")
                .Includes(o => o.Details, d => d.MedicineGoods)
                .ToList();
                // 3. 再过滤掉不符合条件的明细(只保留 Status=0)
                foreach (var order in orders)
                {
                    order.Details = order.Details.Where(d => d.Status == 0).ToList();
                }
 
                if (orders == null || !orders.Any())
                {
                    Console.WriteLine("没有符合条件的订单需要推送");
                    return WebResponseContent.Instance.Error("没有符合条件的订单需要推送");
                }
 
 
                // 4. 遍历订单,组装 DTO 并推送
                foreach (var order in orders)
                {
                    string materialCode = "YY";//默认值
                    //获取当前订单的第一个明细项
                    var firstDetail = order.Details.FirstOrDefault();
                    if (firstDetail?.MedicineGoods != null && !string.IsNullOrEmpty(firstDetail.MedicineGoods.MaterialCode))
                    {
                        //如果条件满足,将物料代码设置为第一个明细项对应的药品物料代码
                        materialCode = firstDetail.MedicineGoods.MaterialCode;
                    }
 
                    var ediDto = new ToediInInfo
                    {
 
                        //客户代码
                        customerCode = "905",
                        //物料类型
                        materialCode = materialCode,
                        //入库单号
                        externalOrderNo = order.Order_no,
                        //入库单类型
                        inOrderType = order.Order_type == "1" ? "10" : "20",
                        //优先级
                        priority = 0,
                        //是否取消
                        Is_cancel = 0,
                        details = order.Details.Select(d => new ToediInDetail
                        {
                            //批号
                            batchNo = d.Batch_num,
                            //产品
                            productCode = d.Goods_no,
                            //sku名称
                            productName = d.MedicineGoods?.Goods_spm,
                            //sku规格
                            productSpecifications = d.MedicineGoods?.Model,
                            //数量
                            quantity = (int)d.Order_qty,
                            //效期
                            validityPeriod = d.Exp_date,
                            //生产厂家
                            manufacturer = d.MedicineGoods?.Factory,
                            //房号
                            libraryNo = order.Warehouse_no,
                            //盘盈入库
                            //stocktakingDetails = new List<ToediInStock>()
                            //stocktakingDetails = new List<ToediInStock>()
                            //{
                            //    new ToediInStock
                            //    {
                            //         //料箱号
                            //        palletCode = "PDA001", 
                            //        //数量
                            //        quantity = d.Order_qty.ToString()
                            //    }
                            // }
                        }).ToList()
                    };
 
                    var url = "http://172.16.1.2:9357/file-admin/api/in/ediIn";
                    var result = HttpHelper.Post(url, ediDto.ToJsonString());
                    var resp = JsonConvert.DeserializeObject<TowcsResponse<object>>(result);
 
                    if (resp != null && resp.code == "0")
                    {
                        // 更新表头状态
                        BaseDal.Db.Updateable<Dt_CabinOrder>()
                           .SetColumns(o => new Dt_CabinOrder { OdrderStatus = "开始" })
                           .Where(o => o.Id == order.Id)
                           .ExecuteCommand();
 
                        // 更新明细状态为已同步
                        BaseDal.Db.Updateable<Dt_CabinOrderDetail>()
                          .SetColumns(d => new Dt_CabinOrderDetail { Status = 1, OrderDetailStatus = "已完成" })
                          .Where(d => d.OrderId == order.Id && d.Status == 0)
                          .ExecuteCommand();
 
                        Console.WriteLine($"订单 {order.Order_no} 推送成功");
                    }
                    else
                    {
                        SendErrorToUpstream(3, order.Order_no, resp?.msg ?? "WCS 推送失败", "");
                        Console.WriteLine($"订单 {order.Order_no} 推送失败:{resp?.msg}");
                        return new WebResponseContent { Status = false, Message = "订单推送失败" };
                    }
                }
                return new WebResponseContent { Status = true, Message = "推送成功" };
            }
            catch (Exception ex)
            {
 
                Console.WriteLine("EdiIn 异常:" + ex.Message);
                return new WebResponseContent { Status = false, Message = ex.Message };
            }
        }
 
 
        /// <summary>
        /// 入库报完成接口
        /// </summary>
        /// <param name="order_no">入库单号</param> //先检查是否所有明细都已完成,如果是,那么更新表头状态为已完成
        /// <returns></returns>
        public WebResponseContent CompleteAllOrders()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 查找所有“开始”状态的入库单
                var orders = BaseDal.Db.Queryable<Dt_CabinOrder>()
                    .Where(o => o.OdrderStatus == "开始")
                    .ToList();
 
                if (orders == null || !orders.Any())
                {
                    return responseContent.OK("暂无需要处理的入库单");
                }
 
                int successCount = 0;
                int failCount = 0;
 
                foreach (var order in orders)
                {
                    try
                    {
                        BaseDal.Db.Ado.BeginTran();
 
                        // 查询该单的明细
                        var details = BaseDal.Db.Queryable<Dt_CabinOrderDetail>()
                            .Where(d => d.OrderId == order.Id)
                            .ToList();
 
                        // 判断是否全部完成
                        var totalCount = details.Count;
                        var completedCount = details.Count(d => d.OrderDetailStatus == "已完成");
 
                        if (totalCount > 0 && completedCount == totalCount)
                        {
                            // 更新表头状态
                            order.OdrderStatus = "已完成";
                            BaseDal.Db.Updateable(order).ExecuteCommand();
 
                            // 调用上游接口
                            var url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";
                            var result = HttpHelper.Post(url, new { order_no = order.Order_no }.ToJsonString());
                            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
 
                            if (response.resultCode == "0")
                            {
                                // === 步骤 1:插入历史表 ===
 
                                // 1.1 插入表头历史
                                var orderHistory = new Dt_CabinOrder_Hty
                                {
                                    Id = order.Id,
                                    Order_no = order.Order_no,
                                    Order_type = order.Order_type,
                                    Supplier_no = order.Supplier_no,
                                    Supplier_name = order.Supplier_name,
                                    Account_tiem = order.Account_tiem,
                                    Warehouse_no = order.Warehouse_no,
                                    OdrderStatus = order.OdrderStatus,
 
                                };
                                var historyId = BaseDal.Db.Insertable(orderHistory).ExecuteReturnIdentity();
 
                                // 1.2 插入明细历史
                                var detailsHistory = details.Select(d => new Dt_CabinOrderDetail_Hty
                                {
                                    Id = d.Id,
                                    Reservoirarea = d.Reservoirarea,
                                    Goods_no = d.Goods_no,
                                    Order_qty = d.Order_qty,
                                    Order_Inqty = d.Order_Inqty,
                                    Batch_num = d.Batch_num,
                                    Exp_date = d.Exp_date,
                                    OrderDetailStatus = d.OrderDetailStatus,
                                    Status = d.Status,
 
                                }).ToList();
 
                                BaseDal.Db.Insertable(detailsHistory).ExecuteCommand();
 
                                // === 步骤 2:删除原始表 ===
                                BaseDal.Db.Deleteable<Dt_CabinOrderDetail>().Where(d => d.OrderId == order.Id).ExecuteCommand();
                                BaseDal.Db.Deleteable<Dt_CabinOrder>().Where(o => o.Id == order.Id).ExecuteCommand();
 
                                // 提交事务
                                BaseDal.Db.Ado.CommitTran();
                                successCount++;
                            }
                            else
                            {
                                BaseDal.Db.Ado.RollbackTran();
                                failCount++;
                                SendErrorToUpstream(2, "", $"上游接口返回失败: {response.resultMsg}", order.Order_no);
                            }
                        }
                        else
                        {
                            BaseDal.Db.Ado.RollbackTran();
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseDal.Db.Ado.RollbackTran();
                        failCount++;
                        SendErrorToUpstream(1, "", ex.Message, order.Order_no);
                    }
                }
 
                return responseContent.OK($"批量处理完成:成功 {successCount} 单,失败 {failCount} 单。");
            }
            catch (Exception ex)
            {
                return responseContent.Error("批量处理失败:" + ex.Message);
            }
        }
 
 
 
 
 
        /// <summary>
        /// 推送异常信息给上游系统1.入库单接口;2.入库单报完成接口;3.出库单接口;4.出库报完成接口;5.药品基础信息同步接口;6.供应商信息接口;7.客户信息接口;8.库存
        /// </summary>
        public void SendErrorToUpstream(int type, string code, string message, string remark)
        {
            try
            {
                var url = "http://121.37.118.63:80/GYZ2/95fck/lexceptionLogog";
 
                var requestData = new
                {
                    type = type.ToString(),
                    code = code,
                    message = message,
                    remark = remark
                };
 
                var result = HttpHelper.Post(url, requestData.ToJsonString());
                // 可以反序列化检查 resultCode 是否为0
            }
            catch (Exception e)
            {
                // 这里不要再抛异常了,避免死循环
                Console.WriteLine("异常接口推送失败:" + e.Message);
            }
        }
 
 
 
 
 
 
    }
}