dengjunjie
2025-10-15 6c7a356b784efde61e2babc17fa6e05047dcc5a7
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
using HslCommunication;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.SquareCabin;
using WIDESEA_ISquareCabinServices;
using WIDESEA_Model.Models;
using static WIDESEA_DTO.SquareCabin.OrderDto;
 
 
 
namespace WIDESEA_SquareCabinServices
{
    public class DeliveryOrderServices : ServiceBase<Dt_DeliveryOrder, IRepository<Dt_DeliveryOrder>>, IDeliveryOrderServices
    {
        static string SearchDate = "";
 
        public DeliveryOrderServices(IRepository<Dt_DeliveryOrder> BaseDal) : base(BaseDal)
        {
        }
 
        /// <summary>
        /// 获取上游出库单 0成功1失败
        /// </summary>
        /// <param name="searchDate"></param>
        /// <returns></returns>
        //public WebResponseContent GetUpstreamOutOrder()
        //{
        //    var responseContent = new WebResponseContent();
        //    try
        //    {
        //        // 请求地址
        //        var url = "http://127.0.0.1:9000/GYZ2/95fck/outOrder";
 
        //        if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //        //// 请求参数
        //        var requestData = new
        //        {
        //            searchDate = SearchDate
        //        };
        //        SearchDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
        //        // 发起请求
        //        var result = HttpHelper.Post(url, requestData.ToJsonString());
 
        //        // 反序列化
        //        var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstramOutOrderInfo>>(result);
 
        //        if (response.resultCode != "0")
        //        {
        //            SendErrorToUpstream(3, "", response.resultMsg ?? "上游接口返回失败", "");
        //            return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
        //        }
 
        //        if (response.data == null || !response.data.Any())
        //        {
        //            return responseContent.OK("无新出库单数据");
        //        }
 
        //        Db.Ado.BeginTran();
 
        //        foreach (var outorder in response.data)
        //        {
        //            try
        //            {
        //                // 插入出库单
        //                var entityOrder = new Dt_DeliveryOrder
        //                {
        //                    Out_no = outorder.out_no,
        //                    Out_type = outorder.out_type,
        //                    Client_no = outorder.client_no,
        //                    Client_name=outorder.client_name,
        //                    Account_time = outorder.account_time,
        //                    OutStatus= "未完成",
        //                };
        //                var outorderId = BaseDal.Db.Insertable(entityOrder).ExecuteReturnIdentity();
 
        //                // 插入出库单明细
        //                var detailEntities = outorder.details.Select(d => new Dt_DeliveryOrderDetail
        //                {
        //                    DeliveryOrderId = outorderId,
        //                    Goods_no = d.goods_no,
        //                    Order_qty = d.out_qty,
        //                    Batch_num = d.batch_num,
        //                    Exp_date = d.exp_date,
        //                    OotDetailStatus="新建"
        //                }).ToList();
        //                BaseDal.Db.Insertable(detailEntities).ExecuteCommand();
        //            }
        //            catch (Exception ex)
        //            {
        //                SendErrorToUpstream(3, outorder.out_no, ex.Message, "");
        //                throw; // 让外层捕获并回滚
        //            }
        //        }
 
        //        Db.Ado.CommitTran();
        //        return responseContent.OK("同步出库单成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        SendErrorToUpstream(3, "", ex.Message, "");
        //        Db.Ado.RollbackTran();
        //        return responseContent.Error("同步失败: " + ex.Message);
        //    }
        //}
 
        public WebResponseContent GetUpstreamOutOrder()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 请求地址
                var url = "http://121.37.118.63:80/GYZ2/95fck/outOrder";
 
                //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<UpstramOutOrderInfo>>(result);
 
                if (response.resultCode != "0")
                {
                    SendErrorToUpstream(3, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
 
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新出库单数据");
                }
                // 获取所有已存在的出库单号
                var existingOutOrderNos = BaseDal.Db.Queryable<Dt_DeliveryOrder>()
                    .Select(x => x.Out_no)
                    .ToList();
 
                // 过滤掉已存在的出库单
                var newOutOrders = response.data
                    .Where(outorder => !existingOutOrderNos.Contains(outorder.order_no))//order_no出库单号
                    .ToList();
 
                if (!newOutOrders.Any())
                {
                    return responseContent.OK("所有出库单已存在,无需新增");
                }
                Db.Ado.BeginTran();
                try
                {
                    List<Dt_DeliveryOrder> _DeliveryOrders = new List<Dt_DeliveryOrder>();
                    ////存储出库单号
                    //List<string> orderNos = new List<string>();
 
                    foreach (var outorder in newOutOrders)
                    {
                        var entityOrder = new Dt_DeliveryOrder
                        {
                            Out_no = outorder.order_no,
                            Out_type = outorder.order_type,
                            Client_no = outorder.client_no,
                            Client_name = outorder.client_name,
                            Account_time = outorder.account_time,
                            Warehouse_no=outorder.warehouse_no,
                            OutStatus = "未完成",
                            Details = outorder.details.Select(d => new Dt_DeliveryOrderDetail
                            {
                                // InsertNav 会自动设置关联字段 DeliveryOrderId
                                Goods_no = d.goods_no,
                                Order_qty = d.out_qty,
                                Batch_num = d.batch_num,
                                Exp_date = d.exp_date,
                                OotDetailStatus = "新建",
                                Status = outorder.warehouse_no == "001" ? 0 : 2, //如果是001房那么将状态设置为0,2为人工处理
                            }).ToList()
                        };
                        #region 根据出库单详情查找物料名称、批次的库存信息(Dt_InventoryInfo);根据先入先出,CreateDate
                        //根据物料名称查找物料信息
 
                        //根据箱规判断是否有散件,计算出散件数量和整件数
 
                        //根据入库时间分组,有散件就优先分配立库数量,整件优先分配平库数量
 
 
                        #endregion
                        _DeliveryOrders.Add(entityOrder);
                        //orderNos.Add(outorder.out_no);
                    };
 
                    // 使用 InsertNav 一次性插入主表和子表数据
                    BaseDal.Db.InsertNav(_DeliveryOrders).Include(x => x.Details).ExecuteCommand();
 
                    // 这里可以添加下发到 WCS 的逻辑
                    // var result = EdiOut(); // 发给下游
 
                    Db.Ado.CommitTran();
                    return responseContent.OK("同步出库单成功");
                }
                catch (Exception ex)
                {
                    Db.Ado.RollbackTran();
                    SendErrorToUpstream(3, "", ex.Message, "");
                    return responseContent.Error("同步失败: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                // 全局异常时,也推送异常给上游
                SendErrorToUpstream(3, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
            }
        }
 
 
        /// <summary>
        /// 出库单推送给 WCS
        /// </summary>
        /// <returns></returns>
        public WebResponseContent EdiOut()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 1. 查询符合条件的订单(表头=新建 && 包含有效明细)
                var outOrders = BaseDal.Db.CopyNew().Queryable<Dt_DeliveryOrder>()
                    .Where(o => o.OutStatus == "新建")
                    .Includes(o => o.Details, d => d.MedicineGoods)
                    .ToList();
 
                // 2. 再过滤掉不符合条件的明细(只保留 Status=0 )
                foreach (var order in outOrders)
                {
                    order.Details = order.Details.Where(d => d.Status == 0).ToList();
                }
 
                if (outOrders == null || !outOrders.Any())
                {
                    Console.WriteLine("没有符合条件的订单需要推送");
                    return responseContent.Error("没有符合条件的订单需要推送");
                }
 
                foreach (var order in outOrders)
                {
                    try
                    {
                        string materialCode = "YY";//默认值
                                                   //获取当前订单的第一个明细项
                        var firstDetail = order.Details.FirstOrDefault();
                        if (firstDetail?.MedicineGoods != null && !string.IsNullOrEmpty(firstDetail.MedicineGoods.MaterialCode))
                        {
                            //如果条件满足,将物料代码设置为第一个明细项对应的药品物料代码
                            materialCode = firstDetail.MedicineGoods.MaterialCode;
                        }
                        // 3. 组装 DTO
                        var ediDto = new TowcsDto.ToediOutInfo
                        {
                            customerCode = "905",
                            materialCode = materialCode,
                            externalOrderNo = order.Out_no,
                            outOrderType = order.Out_type == "1" ? "10" : order.Out_type == "2" ? "20" : "30",
                            priority = 1,
                            Is_cancel = 0,
                            details = order.Details.Select(d => new TowcsDto.ToeOutdiInDetail
                            {
                                batchNo = d.Batch_num,
                                productCode = d.Goods_no,
                                productName = d.MedicineGoods?.Goods_spm,
                                productSpecifications = d.MedicineGoods?.Model,
                                quantity = (int)d.Order_qty,
                                //stocktakingDetails = order.Out_type == "3"
                                //    ? new List<ToOutediInStock>
                                //      {
                                //  new ToOutediInStock { palletCode = "FC00001", quantity = d.Order_qty.ToString() }
                                //      }
                                //    : null
                            }).ToList()
                        };
 
                        // 4. 调用接口
                        var url = "http://172.16.1.2:9357/file-admin/api/out/ediOut";
                        var result = HttpHelper.Post(url, ediDto.ToJsonString());
                        var resp = JsonConvert.DeserializeObject<TowcsDto.TowcsResponse<object>>(result);
 
                        if (resp != null && resp.code == "0")
                        {
                            // 更新表头状态
                            BaseDal.Db.Updateable<Dt_DeliveryOrder>()
                              .SetColumns(o => new Dt_DeliveryOrder { OutStatus = "开始" })
                              .Where(o => o.Id == order.Id)
                              .ExecuteCommand();
 
                            // 更新明细状态
                            BaseDal.Db.Updateable<Dt_DeliveryOrderDetail>()
                              .SetColumns(d => new Dt_DeliveryOrderDetail { Status = 1,OotDetailStatus="已完成" })
                              .Where(d => d.DeliveryOrderId == order.Id && d.Status == 0)
                              .ExecuteCommand();
 
                            Console.WriteLine($"订单 {order.Out_no} 推送成功");
                        }
                        else
                        {
                            SendErrorToUpstream(3, order.Out_no, resp?.msg ?? "WCS 推送失败", "");
                            Console.WriteLine($"订单 {order.Out_no} 推送失败:{resp?.msg}");
                        }
                        //删除全部状为已完成的明细和表头,移入历史表
                    }
                    catch (Exception ex)
                    {
                        SendErrorToUpstream(3, order.Out_no, ex.Message, "");
                        Console.WriteLine($"订单 {order.Out_no} 推送异常:{ex.Message}");
                    }
                }
 
                return responseContent.OK("出库订单推送完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine("EdiOut 异常:" + ex.Message);
                return responseContent.Error("出库订单推送失败:" + ex.Message);
            }
        }
 
 
        /// <summary>
        /// 出库报完成接口
        /// </summary>
        /// <param name="out_no">出库单号</param>
        /// <returns></returns>
        //public WebResponseContent CompleteOutOrder(string out_no)
        //{
        //    var responseContent = new WebResponseContent();
        //    try
        //    {
        //        if (string.IsNullOrWhiteSpace(out_no))
        //        {
        //            return responseContent.Error("入库单号不可以为空");
        //        }
 
        //        Db.Ado.BeginTran();
        //        //先查头表
        //        var outOerd= BaseDal.Db.Queryable<Dt_DeliveryOrder>()
        //            .Where(o => o.Out_no == out_no)
        //            .First();
        //        if (outOerd == null)
        //        {
        //            return responseContent.Error($"没有找到该出库单号{out_no}");
        //        }
        //        //查找所有明细表是否都已完成
        //        var incompleteDetails = BaseDal.Db.Queryable<Dt_DeliveryOrderDetail>()
        //            .Where(d => d.DeliveryOrderId == outOerd.Id && d.OotDetailStatus == "已完成")
        //            .Count();
        //        if (incompleteDetails>0)
        //        {
        //            // 更新出库单状态
        //            BaseDal.Db.Updateable<Dt_DeliveryOrder>()
        //              .SetColumns(o => new Dt_DeliveryOrder { OutStatus = "开始" })
        //              .Where(o => o.Out_no == out_no)
        //              .ExecuteCommand();
        //            var url = " http://127.0.0.1:9090/GYZ2/95fck/outOrderOk";
        //            var reslut = HttpHelper.Post(url, new { out_no }.ToJsonString());
        //            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(reslut);
        //            if (response.resultCode != "0")
        //            {
        //                SendErrorToUpstream(4, "", "上游接口返回失败", "");
        //                return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
        //            }
        //            Db.Ado.CommitTran();
        //            return responseContent.OK("操作成功,出库单以及明细全部完成");
        //        }
        //        else
        //        {
        //            return responseContent.OK("操作成功,但任有为完成的明细");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Db.Ado.RollbackTran();
        //        SendErrorToUpstream(1, "", ex.Message, "");
        //        return responseContent.Error("同步失败: " + ex.Message);
        //    }
        //}
 
 
        /// <summary>
        ///盘点出库单推送给 WCS
        /// </summary>
        /// <param name="externalOrderNo">出库单号</param>
        /// <returns></returns>
        //public WebResponseContent InventoryGood(string externalOrderNo)
        //{
        //    try
        //    {
        //        // 查询出库单及明细
        //        var orders = BaseDal.Db.CopyNew().Queryable<Dt_DeliveryOrder>()
        //            .Where(x => x.Out_no == externalOrderNo)
        //            .Includes(o => o.Details, d => d.MedicineGoods)
        //            .ToList();
 
 
        //        if (orders == null || orders.Count == 0)
        //        {
        //            return new WebResponseContent().Error("没有找到该出库单");
        //        }
 
        //        var url = "http://172.16.1.2:9357/file-admin/api/out/ediOut"; 
        //        bool allSuccess = true;
 
        //        foreach (var order in orders)
        //        {
        //            //查找给商品的库存
        //            var Invert = BaseDal.Db.Queryable<Dt_Inventory>()
        //                .Where(i => i.Goods_no == order.Out_no).First();
        //            var ediDto = new TowcsDto.ToediOutInfo
        //            {
        //                customerCode = "905",
        //                materialCode = "YY",
        //                externalOrderNo = order.Out_no,
        //                outOrderType = "20", // 盘点出库单
        //                priority = 1,
        //                Is_cancel = 0,
        //                details = order.Details.Select(d => new TowcsDto.ToeOutdiInDetail
        //                {
        //                    batchNo = d.Batch_num,
        //                    productCode = d.Goods_no,
        //                    productName = d.MedicineGoods?.Goods_spm,
        //                    productSpecifications = d.MedicineGoods?.Model,
        //                    quantity = (int)d.Order_qty,
        //                    stocktakingDetails = new List<TowcsDto.ToOutediInStock>
        //            {
        //                new TowcsDto.ToOutediInStock
        //                {
        //                    palletCode = Invert.PalletCode,  // 实际从系统取
        //                    quantity = d.Order_qty.ToString()
        //                }
        //            }
        //                }).ToList()
        //            };
 
        //            var result = HttpHelper.Post(url, ediDto.ToJsonString());
        //            var resp = JsonConvert.DeserializeObject<TowcsDto.TowcsResponse<object>>(result);
 
        //            if (resp == null || resp.code != "0")
        //            {
        //                allSuccess = false;
        //                break;
        //            }
        //        }
 
        //        return allSuccess
        //            ? new WebResponseContent { Status = true, Message = "盘点成功" }
        //            : new WebResponseContent { Status = false, Message = "盘点失败" };
        //    }
        //    catch (Exception ex)
        //    {
        //        return new WebResponseContent { Status = false, Message = ex.Message };
        //    }
        //}
        public WebResponseContent InventoryGood(string externalOrderNo)
        {
            try
            {
                // 1. 查出出库单及明细
                var orders = BaseDal.Db.CopyNew().Queryable<Dt_DeliveryOrder>()
                    .Where(x => x.Out_no == externalOrderNo)
                    .Includes(o => o.Details, d => d.MedicineGoods)
                    .ToList();
 
                if (orders == null || orders.Count == 0)
                    return new WebResponseContent().Error("没有找到该出库单");
 
                // 2. 获取所有商品编号
                var allGoodsNos = orders
                    .SelectMany(o => o.Details.Select(d => d.Goods_no))
                    .Distinct()
                    .ToList();
 
                // 3. 一次性查询库存信息
                var inventoryList = BaseDal.Db.Queryable<Dt_Inventory>()
                    .Where(i => allGoodsNos.Contains(i.Goods_no))
                    .ToList();
 
                var inventoryDict = inventoryList.ToDictionary(i => i.Goods_no, i => i);
 
                string url = "http://172.16.1.2:9357/file-admin/api/out/ediOut";
                bool allSuccess = true;
 
                // 4. 构造盘点出库请求
                foreach (var order in orders)
                {
                    var ediDto = new TowcsDto.ToediOutInfo
                    {
                        customerCode = "905",
                        materialCode = "YY",
                        externalOrderNo = order.Out_no,
                        outOrderType = "20", // 盘点出库单
                        priority = 1,
                        Is_cancel = 0,
                        details = order.Details.Select(d =>
                        {
                            inventoryDict.TryGetValue(d.Goods_no, out var invert);
 
                            return new TowcsDto.ToeOutdiInDetail
                            {
                                batchNo = d.Batch_num,
                                productCode = d.Goods_no,
                                productName = d.MedicineGoods?.Goods_spm,
                                productSpecifications = d.MedicineGoods?.Model,
                                quantity = (int)d.Order_qty,
                                stocktakingDetails = new List<TowcsDto.ToOutediInStock>
                        {
                            new TowcsDto.ToOutediInStock
                            {
                                palletCode = invert?.PalletCode ?? string.Empty,
                                quantity = d.Order_qty.ToString()
                            }
                        }
                            };
                        }).ToList()
                    };
 
                    var result = HttpHelper.Post(url, ediDto.ToJsonString());
                    var resp = JsonConvert.DeserializeObject<TowcsDto.TowcsResponse<object>>(result);
 
                    if (resp == null || resp.code != "0")
                    {
                        allSuccess = false;
                        break;
                    }
                }
 
                return allSuccess
                    ? new WebResponseContent { Status = true, Message = "盘点成功" }
                    : new WebResponseContent { Status = false, Message = "盘点失败" };
            }
            catch (Exception ex)
            {
                return new WebResponseContent { Status = false, Message = ex.Message };
            }
        }
 
 
 
 
        /// <summary>
        /// 出库报完成接口
        /// </summary>
        /// <param name="out_no">出库单号</param>
        /// <returns></returns>
        public WebResponseContent CompleteAllOutOrders()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 查找所有“开始”状态的出库单
                var orders = BaseDal.Db.Queryable<Dt_DeliveryOrder>()
                    .Where(o => o.OutStatus == "开始")
                    .ToList();
 
                if (orders == null || !orders.Any())
                {
                    return responseContent.OK("暂无需要处理的出库单");
                }
 
                int successCount = 0;
                int failCount = 0;
 
                foreach (var order in orders)
                {
                    try
                    {
                        Db.Ado.BeginTran();
 
                        // 查询该单的明细
                        var details = BaseDal.Db.Queryable<Dt_DeliveryOrderDetail>()
                            .Where(d => d.DeliveryOrderId == order.Id)
                            .ToList();
 
                        // 判断明细是否全部完成
                        var completedCount = details.Count(d => d.OotDetailStatus == "已完成");
                        var totalCount = details.Count;
 
                        if (totalCount > 0 && completedCount == totalCount)
                        {
                            // 更新状态为已完成
                            BaseDal.Db.Updateable<Dt_DeliveryOrder>()
                                .SetColumns(o => o.OutStatus == "已完成")
                                .Where(o => o.Id == order.Id)
                                .ExecuteCommand();
 
                            // 调用上游接口
                            var url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";
                            var requestDate = new
                            {
                                order_no = order.Out_no
                            };
                            var result = HttpHelper.Post(url, requestDate.ToJsonString());
                            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
 
                            if (response.resultCode == "0")
                            {
                                // ✅ 插入历史表(表头 + 明细)
                                var orderHistory = new Dt_DeliveryOrder_Hty
                                {
                                    Id = order.Id,
                                    Out_no = order.Out_no,
                                    Out_type = order.Out_type,
                                    Client_no = order.Client_no,
                                    Client_name = order.Client_name,
                                    Account_time = order.Account_time,
                                    Warehouse_no = order.Warehouse_no,
                                    OutStatus = "已完成",
                                    Details = details.Select(d => new Dt_DeliveryOrderDetail
                                    {
                                        Id = d.Id,
                                        DeliveryOrderId = d.DeliveryOrderId,
                                        Reservoirarea = d.Reservoirarea,
                                        Goods_no = d.Goods_no,
                                        Order_qty = d.Order_qty,
                                        Batch_num = d.Batch_num,
                                        Exp_date = d.Exp_date,
                                        OotDetailStatus = d.OotDetailStatus,
                                        Status = d.Status
                                    }).ToList()
                                };
 
                                // 插入表头历史
                                var historyId = BaseDal.Db.Insertable(orderHistory).ExecuteReturnIdentity();
 
                                // 插入明细历史(带新外键)
                                var detailHistories = details.Select(d => new Dt_DeliveryOrderDetail_Hty
                                {
                                    Id = d.Id,
                                    DeliveryOrderId = order.Id,
                                    Reservoirarea = d.Reservoirarea,
                                    Goods_no = d.Goods_no,
                                    Order_qty = d.Order_qty,
                                    Batch_num = d.Batch_num,
                                    Exp_date = d.Exp_date,
                                    OotDetailStatus = d.OotDetailStatus,
                                    Status = d.Status
                                }).ToList();
 
                                BaseDal.Db.Insertable(detailHistories).ExecuteCommand();
 
                                // 删除原始数据(明细 → 表头)
                                BaseDal.Db.Deleteable<Dt_DeliveryOrderDetail>().Where(d => d.DeliveryOrderId == order.Id).ExecuteCommand();
                                BaseDal.Db.Deleteable<Dt_DeliveryOrder>().Where(o => o.Id == order.Id).ExecuteCommand();
 
                                Db.Ado.CommitTran();
                                successCount++;
                            }
                            else
                            {
                                Db.Ado.RollbackTran();
                                failCount++;
                                SendErrorToUpstream(4, "", $"上游接口返回失败: {response.resultMsg}", order.Out_no);
                            }
                        }
                        else
                        {
                            // 有未完成明细,不更新
                            Db.Ado.RollbackTran();
                        }
                    }
                    catch (Exception ex)
                    {
                        Db.Ado.RollbackTran();
                        failCount++;
                        SendErrorToUpstream(1, "", ex.Message, order.Out_no);
                    }
                }
 
                return responseContent.OK($"批量处理完成:成功 {successCount} 单,失败 {failCount} 单。");
            }
            catch (Exception ex)
            {
                return responseContent.Error("批量处理失败:" + ex.Message);
            }
        }
 
 
        //public WebResponseContent CompleteAllOutOrders()
        //{
        //    var responseContent = new WebResponseContent();
        //    try
        //    {
        //        var orders = BaseDal.Db.Queryable<Dt_DeliveryOrder>()
        //            .Where(o => o.OutStatus == "开始")
        //            .ToList();
 
        //        if (orders == null || !orders.Any())
        //        {
        //            return responseContent.OK("暂无需要处理的出库单");
        //        }
 
        //        int successCount = 0;
        //        int failCount = 0;
        //        int serverErrorCount = 0;
 
        //        foreach (var order in orders)
        //        {
        //            try
        //            {
        //                Db.Ado.BeginTran();
 
        //                var details = BaseDal.Db.Queryable<Dt_DeliveryOrderDetail>()
        //                    .Where(d => d.DeliveryOrderId == order.Id)
        //                    .ToList();
 
        //                var completedCount = details.Count(d => d.OotDetailStatus == "已完成");
        //                var totalCount = details.Count;
 
        //                if (totalCount > 0 && completedCount == totalCount)
        //                {
        //                    // 更新状态为已完成
        //                    BaseDal.Db.Updateable<Dt_DeliveryOrder>()
        //                        .SetColumns(o => o.OutStatus == "已完成")
        //                        .Where(o => o.Id == order.Id)
        //                        .ExecuteCommand();
 
        //                    // 调用上游接口
        //                    var url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";
        //                    var requestDate = new
        //                    {
        //                        order_no = order.Out_no
        //                    };
 
        //                    string result;
        //                    try
        //                    {
        //                        result = HttpHelper.Post(url, requestDate.ToJsonString());
        //                    }
        //                    catch (Exception httpEx)
        //                    {
        //                        // HTTP请求异常(网络问题等)
        //                        Db.Ado.RollbackTran();
        //                        failCount++;
        //                        SendErrorToUpstream(3, "", $"网络请求失败: {httpEx.Message}", order.Out_no);
        //                        continue;
        //                    }
 
        //                    // ✅ 检查是否是500错误页面
        //                    if (!string.IsNullOrEmpty(result) && result.Contains("500错误页面"))
        //                    {
        //                        Db.Ado.RollbackTran();
        //                        serverErrorCount++;
        //                        SendErrorToUpstream(5, "", "上游接口服务器内部错误(500),请联系上游系统管理员", order.Out_no);
        //                        continue;
        //                    }
 
        //                    // ✅ 检查是否是HTML响应
        //                    if (!string.IsNullOrEmpty(result) && result.Trim().StartsWith("<"))
        //                    {
        //                        Db.Ado.RollbackTran();
        //                        failCount++;
        //                        SendErrorToUpstream(4, "", "上游接口返回非JSON格式响应", order.Out_no);
        //                        continue;
        //                    }
 
        //                    // ✅ 安全解析JSON
        //                    UpstreamOrderResponse response;
        //                    try
        //                    {
        //                        response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
        //                    }
        //                    catch (JsonReaderException jsonEx)
        //                    {
        //                        Db.Ado.RollbackTran();
        //                        failCount++;
        //                        SendErrorToUpstream(4, "", $"上游接口返回数据格式错误: {jsonEx.Message}", order.Out_no);
        //                        continue;
        //                    }
 
        //                    if (response.resultCode == "0")
        //                    {
        //                        // 成功处理逻辑...
        //                        var orderHistory = new Dt_DeliveryOrder_Hty
        //                        {
        //                            Id = order.Id,
        //                            Out_no = order.Out_no,
        //                            Out_type = order.Out_type,
        //                            Client_no = order.Client_no,
        //                            Client_name = order.Client_name,
        //                            Account_time = order.Account_time,
        //                            Warehouse_no = order.Warehouse_no,
        //                            OutStatus = "已完成",
        //                            Details = details.Select(d => new Dt_DeliveryOrderDetail
        //                            {
        //                                Id = d.Id,
        //                                DeliveryOrderId = d.DeliveryOrderId,
        //                                Reservoirarea = d.Reservoirarea,
        //                                Goods_no = d.Goods_no,
        //                                Order_qty = d.Order_qty,
        //                                Batch_num = d.Batch_num,
        //                                Exp_date = d.Exp_date,
        //                                OotDetailStatus = d.OotDetailStatus,
        //                                Status = d.Status
        //                            }).ToList()
        //                        };
 
        //                        var historyId = BaseDal.Db.Insertable(orderHistory).ExecuteReturnIdentity();
 
        //                        var detailHistories = details.Select(d => new Dt_DeliveryOrderDetail_Hty
        //                        {
        //                            Id = d.Id,
        //                            DeliveryOrderId = order.Id,
        //                            Reservoirarea = d.Reservoirarea,
        //                            Goods_no = d.Goods_no,
        //                            Order_qty = d.Order_qty,
        //                            Batch_num = d.Batch_num,
        //                            Exp_date = d.Exp_date,
        //                            OotDetailStatus = d.OotDetailStatus,
        //                            Status = d.Status
        //                        }).ToList();
 
        //                        BaseDal.Db.Insertable(detailHistories).ExecuteCommand();
 
        //                        BaseDal.Db.Deleteable<Dt_DeliveryOrderDetail>().Where(d => d.DeliveryOrderId == order.Id).ExecuteCommand();
        //                        BaseDal.Db.Deleteable<Dt_DeliveryOrder>().Where(o => o.Id == order.Id).ExecuteCommand();
 
        //                        Db.Ado.CommitTran();
        //                        successCount++;
        //                    }
        //                    else
        //                    {
        //                        Db.Ado.RollbackTran();
        //                        failCount++;
        //                        SendErrorToUpstream(4, "", $"上游接口返回失败: {response.resultMsg}", order.Out_no);
        //                    }
        //                }
        //                else
        //                {
        //                    Db.Ado.RollbackTran();
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                Db.Ado.RollbackTran();
        //                failCount++;
        //                SendErrorToUpstream(1, "", ex.Message, order.Out_no);
        //            }
        //        }
 
        //        return responseContent.OK($"批量处理完成:成功 {successCount} 单,失败 {failCount} 单,服务器错误 {serverErrorCount} 单。");
        //    }
        //    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/exceptionLog";
 
                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);
            }
        }
 
       
    }
}