dengjunjie
3 天以前 4d58609275685b1b5deaace933697dcf3f01359e
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
using HslCommunication;
using Newtonsoft.Json;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_IBasicService;
using WIDESEA_ISquareCabinServices;
using WIDESEA_IWMsInfoServices;
using static WIDESEA_DTO.SquareCabin.OrderDto;
using WIDESEA_Model.Models;
using WIDESEA_SquareCabinServices;
using static WIDESEA_DTO.SquareCabin.TowcsDto;
using WIDESEA_Common.WareHouseEnum;
using WIDESEA_DTO.SquareCabin;
using WIDESEA_Common;
using System.Xml.Linq;
using WIDESEA_Common.OrderEnum;
using static WIDESEA_DTO.SquareCabin.AlarmDto;
using OfficeOpenXml.Style;
using System.Security.Policy;
 
namespace WIDESEA_SquareCabinServices
{
    public partial class Business : IBusiness
    {
        private readonly ICabinOrderServices _cabinOrderServices;
        private readonly ICabinOrderDetailServices _cabinDetailServices;
        private readonly IDeliveryOrderServices _deliveryOrderServices;
        private readonly IDeliveryOrderDetailServices _deliveryOrderDetailServices;
        private readonly IMaterielInfoService _materielInfoService;
        private readonly IMessageInfoService _messageInfoService;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        public Business(IDeliveryOrderServices deliveryOrderServices, IUnitOfWorkManage unitOfWorkManage, IDeliveryOrderDetailServices deliveryOrderDetailServices, ICabinOrderServices cabinOrderServices, ICabinOrderDetailServices cabinDetailServices, IMaterielInfoService materielInfoService, IMessageInfoService messageInfoService)
        {
            _deliveryOrderServices = deliveryOrderServices;
            _unitOfWorkManage = unitOfWorkManage;
            _deliveryOrderDetailServices = deliveryOrderDetailServices;
            _cabinOrderServices = cabinOrderServices;
            _cabinDetailServices = cabinDetailServices;
            _materielInfoService = materielInfoService;
            _messageInfoService = messageInfoService;
        }
        #region 获取ERP入库单
        static string SearchInDate = "2025-10-30 00:00:00";
        /// <summary>
        /// 获取上游系统的入库单
        /// </summary>
        /// <param name="SearchInDate"></param>
        /// <returns></returns>
        public WebResponseContent GetUpstreamOrder()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 请求地址
                var url = "http://121.37.118.63:80/GYZ2/95fck/inOrder";
                //var url = "http://127.0.0.1:4523/m2/5660322-5340849-default/363009261";
 
                if (string.IsNullOrEmpty(SearchInDate)) SearchInDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// 请求参数
                var requestData = new
                {
                    searchDate = SearchInDate
                    //searchDate = "2022-10-10 20:45:16"  // 正确的格式
                };
                SearchInDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                // 发起请求
                var result = HttpHelper.Post(url, requestData.ToJsonString());
 
                // 反序列化
                var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstreamOrderInfo>>(result);
 
                if (response == null || response.resultCode != "0")
                {
                    // 调用异常接口
                    //SendErrorToUpstream(1, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
 
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新入库单数据");
                }
                var ordernos = response.data.Select(x => x.order_no).ToList();
                // 获取所有已存在的入库单号
                var existingOrderNos = _cabinOrderServices.Db.CopyNew().Queryable<Dt_CabinOrder>()
                    .Where(x => ordernos.Contains(x.Order_no))
                    .Select(x => x.Order_no)
                    .Distinct().ToList();
 
                // 过滤掉已存在的入库单
                var newOrders = response.data
                    .Where(order => !existingOrderNos.Contains(order.order_no))
                    .ToList();
 
                if (newOrders.Count < 1)
                {
                    return responseContent.OK("所有入库单已存在,无需新增");
                }
 
                //存储入库单号
                List<string> orderNos = new List<string>();
                string name = string.Empty;
                MessageGroupByEnum messageGroupBy = MessageGroupByEnum.InOrderAlarm;
                MessageStatusEnum messageStatus = MessageStatusEnum.Emergency;
                foreach (var order in newOrders)
                {
                    try
                    {
                        if (order.order_type == "1") //正常入库
                        {
                            name = "创建正常入库单";
                            responseContent = _cabinOrderServices.CreateInboundOrder(order);
                            if (!responseContent.Status) throw new Exception(responseContent.Message);
                            List<Dt_CabinOrder>? dt_CabinOrders = responseContent.Data as List<Dt_CabinOrder>;
                            if (dt_CabinOrders != null)
                                _cabinOrderServices.Db.InsertNav(dt_CabinOrders).Include(x => x.Details).ExecuteCommand();
                        }
                        else if (order.order_type == "3")//入库退料
                        {
                            messageGroupBy = MessageGroupByEnum.OutOrderAlarm;
                            name = "创建入库退货单";
                            //创建出库单
                            #region 转换为出库单
                            UpstramOutOrderInfo upstramOutOrderInfo = new UpstramOutOrderInfo()
                            {
                                order_no = order.order_no,
                                order_type = order.order_type,
                                warehouse_no = order.warehouse_no,
                                details = new List<UpstreamOutOrderDetail>()
                            };
                            foreach (var item in order.details)
                            {
                                UpstreamOutOrderDetail detail = new UpstreamOutOrderDetail()
                                {
                                    batch_num = item.batch_num,
                                    goods_no = item.goods_no,
                                    order_qty = item.order_qty,
                                    exp_date = item.exp_date,
                                };
                                upstramOutOrderInfo.details.Add(detail);
                            }
                            var content = _deliveryOrderServices.CreateOutboundOrder(upstramOutOrderInfo);
                            if (!content.Status) throw new Exception(content.Message);
                            #endregion
                        }
                        else if (order.order_type == "5")//报溢入库
                        {
                            name = "创建盘盈入库单";
                            messageStatus = MessageStatusEnum.Undisposed;
                            var content = _cabinOrderServices.CreateCheckInOrder(order);
                            if (!content.Status) throw new Exception(content.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        _messageInfoService.AddMessageInfo(messageGroupBy, name, ex.Message, messageStatus);
                        //SendErrorToUpstream(1, "", ex.Message, "");
                        //return responseContent.Error("同步失败: " + ex.Message);
                    }
                };
                return responseContent.OK("同步入库单成功");
 
            }
            catch (Exception ex)
            {
                // 全局异常时,也推送异常给上游
                //SendErrorToUpstream(1, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
            }
        }
        #endregion
 
        #region 获取ERP出库单
        static string SearchOutDate = "2025-10-30 00:00:00";
        public WebResponseContent GetUpstreamOutOrder()
        {
            var responseContent = new WebResponseContent();
            try
            {
                var url = "http://121.37.118.63:80/GYZ2/95fck/outOrder";
                //var url = "http://127.0.0.1:4523/m1/5660322-5340849-default/GYZ2/95fck/outOrder";
                if (string.IsNullOrEmpty(SearchOutDate)) SearchOutDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// 请求参数
                var requestData = new
                {
                    searchDate = SearchOutDate
                    //searchDate = "2022-10-10 20:45:16"  // 正确的格式
                };
                SearchOutDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 
                var result = HttpHelper.Post(url, requestData.ToJsonString());
                var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstramOutOrderInfo>>(result);
 
                if (response == null || response.resultCode != "0")
                {
                    //SendErrorToUpstream(3, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response?.resultMsg ?? "上游接口返回失败");
                }
 
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新出库单数据");
                }
                var ordernos = response.data.Select(x => x.order_no).ToList();
                // 已存在出库单号
                var existingOutOrderNos = _deliveryOrderServices.Db.CopyNew().Queryable<Dt_DeliveryOrder>()
                    .Where(x => ordernos.Contains(x.Out_no))
                    .Select(x => x.Out_no)
                    .Distinct().ToList();
 
                // 新出库单
                var newOutOrders = response.data
                    .Where(outorder => !existingOutOrderNos.Contains(outorder.order_no))
                    .ToList();
 
                List<string> order_no = newOutOrders.Select(x => x.order_no).ToList();
 
                if (newOutOrders.Count < 1)
                {
                    return responseContent.OK("所有出库单已存在,无需新增");
                }
 
                List<Dt_DeliveryOrder> _DeliveryOrders = new List<Dt_DeliveryOrder>();
                List<string> orderNos = new List<string>();
                string name = string.Empty;
                MessageGroupByEnum messageGroupBy = MessageGroupByEnum.OutOrderAlarm;
                MessageStatusEnum messageStatus = MessageStatusEnum.Emergency;
                foreach (var outorder in newOutOrders)
                {
                    try
                    {
                        if (outorder.order_type == "1") // 正常出库单
                        {
                            name = "创建正常出库单";
                            var content = _deliveryOrderServices.CreateOutboundOrder(outorder);
                            if (!content.Status) throw new Exception(content.Message);
                        }
                        else if (outorder.order_type == "2")//出库退货
                        {
                            name = "创建出库退货单";
                            messageGroupBy = MessageGroupByEnum.InOrderAlarm;
                            // 创建出库退货单 - 这里需要根据业务逻辑实现
                            // 暂时跳过或实现退货逻辑
                            //continue;
                            #region 转换成入库单
                            UpstreamOrderInfo order = new UpstreamOrderInfo()
                            {
                                order_no = outorder.order_no,
                                order_type = outorder.order_type,
                                warehouse_no = outorder.warehouse_no,
                                details = new List<UpstreamOrderDetail>()
                            };
                            foreach (var item in outorder.details)
                            {
                                UpstreamOrderDetail detail = new UpstreamOrderDetail()
                                {
                                    batch_num = item.batch_num,
                                    goods_no = item.goods_no,
                                    order_qty = item.order_qty,
                                    exp_date = item.exp_date,
                                };
                                order.details.Add(detail);
                            }
                            responseContent = _cabinOrderServices.CreateInboundOrder(order);
                            if (!responseContent.Status) throw new Exception(responseContent.Message);
                            List<Dt_CabinOrder>? dt_CabinOrders = responseContent.Data as List<Dt_CabinOrder>;
                            if (dt_CabinOrders != null && dt_CabinOrders.Count > 0)
                                _cabinOrderServices.Db.CopyNew().InsertNav(dt_CabinOrders).Include(x => x.Details).ExecuteCommand();
                            #endregion
                        }
                        else if (outorder.order_type == "6")//报损出库
                        {
                            name = "创建盘损出库单";
                            messageStatus = MessageStatusEnum.Undisposed;
                            var content = _deliveryOrderServices.CreateCheckOutOrder(outorder);
                            if (!content.Status) throw new Exception(content.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        _messageInfoService.AddMessageInfo(messageGroupBy, name, ex.Message, messageStatus);
                        //SendErrorToUpstream(3, "", ex.Message, "");
                        //return responseContent.Error("同步失败: " + ex.Message);
                    }
                }
                return responseContent.OK($"同步出库单成功,共{_DeliveryOrders.Count}条");
            }
            catch (Exception ex)
            {
                //SendErrorToUpstream(3, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
            }
        }
        #endregion
 
        #region 下发立库入库单
        public WebResponseContent EdiIn()
        {
            try
            {
                var reslut = WarehouseEnum.立库.ObjToInt().ToString("000");
                var orders = _cabinOrderServices.Repository.QueryData(x => x.OdrderStatus == "新建" && x.Warehouse_no == reslut);
                if (orders.Count < 1) return WebResponseContent.Instance.OK();
                string url = "http://172.16.1.2:9357/file-admin/api/in/ediIn";
                var cabinOrderDetails = _cabinDetailServices.Repository.QueryData(x => orders.Select(x => x.Id).ToList().Contains(x.OrderId));
                var materielInfos = _materielInfoService.Repository.QueryData(x => cabinOrderDetails.Select(x => x.Goods_no).Contains(x.MaterielCode));
                foreach (var order in orders)
                {
                    order.Details = cabinOrderDetails.Where(x => x.OrderId == order.Id).ToList();
                    foreach (var item in order.Details)
                    {
                        item.MedicineGoods = materielInfos.Where(x => x.MaterielCode == item.Goods_no).First();
                    }
                    #region 下发WCS
                    string materialCode = order.Details.FirstOrDefault()?.MedicineGoods?.MaterielErpType ?? "YY";
                    var ediDto = new ToediInInfo
                    {
                        //客户代码
                        customerCode = "905",
                        //物料类型
                        materialCode = materialCode,
                        //入库单号
                        externalOrderNo = order.Order_no,
                        //入库单类型
                        inOrderType = order.Order_type == "5" ? "20" : "10",
                        //优先级
                        priority = 0,
                        //是否取消
                        Is_cancel = 0,
                        details = order.Details.Select(d => new ToediInDetail
                        {
                            //批号
                            batchNo = d.Batch_num,
                            //产品
                            productCode = d.Goods_no,
                            //sku名称
                            productName = d.MedicineGoods.MaterielName,
                            //sku规格
                            productSpecifications = d.MedicineGoods.MaterielSpec,
                            //数量
                            quantity = (int)d.Order_qty,
                            //效期
                            validityPeriod = d.Exp_date,
                            //生产厂家
                            manufacturer = d.MedicineGoods.Factory,
                            //房号
                            libraryNo = order.Warehouse_no,
                        }).ToList()
                    };
                    var result = HttpHelper.Post(url, ediDto.ToJsonString());
                    var resp = JsonConvert.DeserializeObject<TowcsResponse<object>>(result);
                    if (resp != null && resp.code == "0")
                    {
                        order.OdrderStatus = "开始";
                        foreach (var item in cabinOrderDetails.Where(x => x.OrderId == order.Id))
                        {
                            item.Status = 1;
                            item.OrderDetailStatus = "开始";
                        }
                    }
                    #endregion
                }
                _cabinOrderServices.UpdateData(orders);
                _cabinDetailServices.UpdateData(cabinOrderDetails);
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                Console.WriteLine("下发WCS入库单异常:" + ex.Message);
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        #region MyRegion
 
        //public WebResponseContent EdiIn1()
        //{
        //    try
        //    {
        //        //2.查询符合条件的订单(表头 = 新建 && 包含有效明细)
        //        //var orders = BaseDal.Db.Queryable<Dt_CabinOrder>()
        //        //    .Where(o => o.OdrderStatus == "新建")
        //        //    .Includes(o => o.Details, d => d.MedicineGoods)
        //        //    .ToList();
        //        //查出包含全部的入库单,包含全部明细+一个明细对应一个商品
        //        var reslut = WarehouseEnum.立库.ObjToInt().ToString("000");
        //        var orders = _cabinOrderServices.Db.CopyNew()
        //        .Queryable<Dt_CabinOrder>()
        //        .Where(o => o.OdrderStatus == "新建" && o.Warehouse_no == reslut)
        //        .Includes(o => o.Details, d => d.MedicineGoods)
        //        .ToList();
        //        // 3. 再过滤掉不符合条件的明细(只保留 Status=0)
        //        foreach (var order in orders)
        //        {
        //            //Console.WriteLine($"订单 {order.Order_no} 原明细数:{order.Details.Count}");
        //            order.Details = order.Details.Where(d => d.Status == 0).ToList();
        //            //Console.WriteLine($"订单 {order.Order_no} 过滤后明细数:{order.Details.Count}");
        //        }
 
 
        //        if (orders.Count < 1)
        //        {
        //            //Console.WriteLine("没有符合条件的订单需要推送");
        //            return WebResponseContent.Instance.Error("没有符合条件的订单需要推送");
        //        }
        //        List<Dt_CabinOrderDetail> cabinOrderDetails = new List<Dt_CabinOrderDetail>();
        //        var url = "http://172.16.1.2:9357/file-admin/api/in/ediIn";
        //        // 4. 遍历订单,组装 DTO 并推送
        //        foreach (var order in orders)
        //        {
        //            // 从第一个有 MedicineGoods 的明细中取出 MaterielErpType
        //            string materialCode = order.Details
        //                .Select(d => d.MedicineGoods?.MaterielErpType)
        //                .FirstOrDefault(x => !string.IsNullOrEmpty(x)) ?? "YY"; // 默认值YY
 
        //            var ediDto = new ToediInInfo
        //            {
 
        //                //客户代码
        //                customerCode = "905",
        //                //物料类型
        //                materialCode = materialCode,
        //                //入库单号
        //                externalOrderNo = order.Order_no,
        //                //入库单类型
        //                inOrderType = order.Order_type == "5" ? "20" : "10",
        //                //优先级
        //                priority = 0,
        //                //是否取消
        //                Is_cancel = 0,
        //                details = order.Details.Select(d => new ToediInDetail
        //                {
        //                    //批号
        //                    batchNo = d.Batch_num,
        //                    //产品
        //                    productCode = d.Goods_no,
        //                    //sku名称
        //                    productName = d.MedicineGoods?.MaterielName,
        //                    //sku规格
        //                    productSpecifications = d.MedicineGoods?.MaterielSpec,
        //                    //数量
        //                    quantity = (int)d.Order_qty,
        //                    //效期
        //                    validityPeriod = d.Exp_date,
        //                    //生产厂家
        //                    manufacturer = d.MedicineGoods?.Factory,
        //                    //房号
        //                    libraryNo = order.Warehouse_no,
        //                }).ToList()
        //            };
 
        //            //var url = "http://127.0.0.1:4523/m2/5660322-5340849-default/363019549";
        //            var result = HttpHelper.Post(url, ediDto.ToJsonString());
        //            var resp = JsonConvert.DeserializeObject<TowcsResponse<object>>(result);
 
        //            if (resp != null && resp.code == "0")
        //            {
        //                order.OdrderStatus = "开始";
        //                foreach (var item in order.Details)
        //                {
        //                    item.Status = 1;
        //                    item.OrderDetailStatus = "开始";
        //                }
        //                cabinOrderDetails.AddRange(order.Details);
        //                // 更新表头状态
        //                //_cabinOrderServices.Db.Updateable<Dt_CabinOrder>()
        //                //   .SetColumns(o => new Dt_CabinOrder { OdrderStatus = "开始" })
        //                //   .Where(o => o.Id == order.Id)
        //                //   .ExecuteCommand();
 
        //                // 更新明细状态为已同步  //这里要是将新建--》开始状态,在后端接口返回我们的时候在返回已完成
        //                //_cabinDetailServices.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
        //            {
        //                continue;
        //                //SendErrorToUpstream(3, order.Order_no, resp?.msg ?? "WCS 推送失败", "");
        //                //Console.WriteLine($"订单 {order.Order_no} 推送失败:{resp?.msg}");
        //                //return new WebResponseContent { Status = false, Message = "订单推送失败" };
        //            }
        //        }
        //        _cabinOrderServices.UpdateData(orders);
        //        _cabinDetailServices.UpdateData(cabinOrderDetails);
        //        return new WebResponseContent { Status = true, Message = "推送成功" };
        //    }
        //    catch (Exception ex)
        //    {
 
        //        Console.WriteLine("EdiIn 异常:" + ex.Message);
        //        return new WebResponseContent { Status = false, Message = ex.Message };
        //    }
        //} 
        #endregion
        #endregion
 
        #region 下发立库出库单
        public WebResponseContent EdiOut()
        {
            try
            {
                var reslut = WarehouseEnum.立库.ObjToInt().ToString("000");
                var orders = _deliveryOrderServices.Repository.QueryData(x => x.OutStatus == "新建" && x.Warehouse_no == reslut);
                if (orders.Count < 1) return WebResponseContent.Instance.OK();
                string url = "http://172.16.1.2:9357/file-admin/api/out/ediOut";
                var deliveryOrderDetails = _deliveryOrderDetailServices.Repository.QueryData(x => orders.Select(x => x.Id).ToList().Contains(x.DeliveryOrderId));
                var materielInfos = _materielInfoService.Repository.QueryData(x => deliveryOrderDetails.Select(x => x.Goods_no).Contains(x.MaterielCode));
                foreach (var order in orders)
                {
                    order.Details = deliveryOrderDetails.Where(x => x.DeliveryOrderId == order.Id).ToList();
                    foreach (var item in order.Details)
                    {
                        item.MedicineGoods = materielInfos.Where(x => x.MaterielCode == item.Goods_no).First();
                    }
                    #region 下发WCS
                    string materialCode = order.Details.FirstOrDefault()?.MedicineGoods?.MaterielErpType ?? "YY";
                    var ediDto = new ToediOutInfo
                    {
                        //客户代码
                        customerCode = "905",
                        //物料类型
                        materialCode = materialCode,
                        externalOrderNo = order.Out_no,
                        outOrderType = order.Out_type,
                        priority = 1,
                        Is_cancel = 0,
                        details = order.Details.Select(d => new ToeOutdiInDetail
                        {
                            batchNo = d.Batch_num,
                            productCode = d.Goods_no,
                            productName = d.MedicineGoods.MaterielName,
                            productSpecifications = d.MedicineGoods.MaterielModel,
                            quantity = (int)d.Order_qty,
                        }).ToList()
                    };
                    switch (order.Out_type)
                    {
                        case "1"://正常出库
                        case "3"://入库退货
                            ediDto.outOrderType = "10";//一般交易出库单
                            break;
                        case "6"://盘亏出库
                            ediDto.outOrderType = "30";//盘亏出库单
                            break;
                    }
                    var result = HttpHelper.Post(url, ediDto.ToJsonString());
                    var resp = JsonConvert.DeserializeObject<TowcsResponse<object>>(result);
                    if (resp != null && resp.code == "0")
                    {
                        order.OutStatus = "开始";
                        foreach (var item in deliveryOrderDetails.Where(x => x.DeliveryOrderId == order.Id))
                        {
                            item.Status = 1;
                            item.OotDetailStatus = "开始";
                        }
                    }
                    #endregion
                }
                _deliveryOrderServices.UpdateData(orders);
                _deliveryOrderDetailServices.UpdateData(deliveryOrderDetails);
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                Console.WriteLine("下发WCS出库单异常:" + ex.Message);
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        #region MyRegion
        public WebResponseContent EdiOut1()
        {
            var responseContent = new WebResponseContent();
            var WarehouseLk = WarehouseEnum.立库.ObjToInt().ToString("000");
            try
            {
                // 1. 查询符合条件的订单(表头=新建 && 包含有效明细)
                var outOrders = _deliveryOrderServices.Db.CopyNew().Queryable<Dt_DeliveryOrder>()
                    .Where(o => o.OutStatus == "新建" && o.Warehouse_no == WarehouseLk)
                    .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.Count < 1)
                {
                    //Console.WriteLine("没有符合条件的订单需要推送");
                    return responseContent.Error("没有符合条件的订单需要推送");
                }
                List<Dt_DeliveryOrderDetail> deliveryOrderDetails = new List<Dt_DeliveryOrderDetail>();
                var url = "http://172.16.1.2:9357/file-admin/api/out/ediOut";
                foreach (var order in outOrders)
                {
                    try
                    {
                        string materialCode = "YY";//默认值
                                                   //获取当前订单的第一个明细项
                        var firstDetail = order.Details.FirstOrDefault();
                        if (firstDetail?.MedicineGoods != null && !string.IsNullOrEmpty(firstDetail.MedicineGoods.MaterielErpType))
                        {
                            //如果条件满足,将物料代码设置为第一个明细项对应的药品物料代码
                            materialCode = firstDetail.MedicineGoods.MaterielErpType;
                        }
                        switch (order.Out_type)
                        {
                            case "1"://正常出库
                            case "3"://入库退货
                                order.Out_type = "10";//一般交易出库单
                                break;
                            case "6"://盘亏出库
                                order.Out_type = "30";//盘亏出库单
                                break;
                        }
                        // 3. 组装 DTO
                        var ediDto = new TowcsDto.ToediOutInfo
                        {
                            customerCode = "905",
                            materialCode = materialCode,
                            externalOrderNo = order.Out_no,
                            outOrderType = order.Out_type,//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?.MaterielName,
                                productSpecifications = d.MedicineGoods?.MaterielModel,
                                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://127.0.0.1:4523/m2/5660322-5340849-default/363076920";
 
                        var result = HttpHelper.Post(url, ediDto.ToJsonString());
                        var resp = JsonConvert.DeserializeObject<TowcsDto.TowcsResponse<object>>(result);
 
                        if (resp != null && resp.code == "0")
                        {
                            order.OutStatus = "开始";
                            foreach (var item in order.Details)
                            {
                                item.Status = 1;
                                item.OotDetailStatus = "开始";
                            }
                            deliveryOrderDetails.AddRange(order.Details);
                            // 更新表头状态
                            //_cabinDetailServices.Db.CopyNew().Updateable<Dt_DeliveryOrder>()
                            //  .SetColumns(o => new Dt_DeliveryOrder { OutStatus = "开始" })
                            //  .Where(o => o.Id == order.Id)
                            //  .ExecuteCommand();
 
                            // 更新明细状态
                            //_deliveryOrderDetailServices.Db.CopyNew().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
                        {
                            continue;
                            //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}");
                    }
                }
                _deliveryOrderServices.UpdateData(outOrders);
                _deliveryOrderDetailServices.UpdateData(deliveryOrderDetails);
                return responseContent.OK("出库订单推送完成");
            }
            catch (Exception ex)
            {
                //Console.WriteLine("EdiOut 异常:" + ex.Message);
                return responseContent.Error("出库订单推送失败:" + ex.Message);
            }
        }
        #endregion
        #endregion
 
        #region 入库完成上报ERP
        /// <summary>
        /// 入库报完成接口
        /// </summary>
        /// <param name="order_no">入库单号</param> //先检查是否所有明细都已完成,如果是,那么更新表头状态为已完成
        /// <returns></returns>
        public WebResponseContent CompleteAllOrders()
        {
            var responseContent = new WebResponseContent();
            try
            {
                #region 查找所有已完成入库单
                var inorders = _cabinOrderServices.Repository.QueryData(x => x.OdrderStatus == "已完成").Select(x => x.Order_no).Distinct().ToList();
                var Orders = _cabinOrderServices.Db.Queryable<Dt_CabinOrder>().Where(x => inorders.Contains(x.Order_no)).Includes(x => x.Details).ToList();
                List<Dt_CabinOrder> cabinOrders = new List<Dt_CabinOrder>();
                List<Dt_CabinOrderDetail> cabinOrderDetails = new List<Dt_CabinOrderDetail>();
                var url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";
                foreach (var item in Orders.GroupBy(x => x.Order_no))
                {
                    if (!item.Where(x => x.OdrderStatus != "已完成").Any())
                    {
                        if (item.First().Order_type == InOrderTypeEnum.Allocat.ObjToInt().ToString())
                        {
                            foreach (var a in item)
                            {
                                if (a.Details != null) cabinOrderDetails.AddRange(a.Details);
                                a.Details = null;
                                cabinOrders.Add(a);
                            }
                        }
                        else
                        {
                            if (item.First().Order_type == "2") url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";//出库退货
                            var result = HttpHelper.Post(url, new { order_no = item.Key }.ToJsonString());
                            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                            if (response != null && response.resultCode == "0")
                            {
                                foreach (var a in item)
                                {
                                    if (a.Details != null) cabinOrderDetails.AddRange(a.Details);
                                    a.Details = null;
                                    cabinOrders.Add(a);
                                }
                            }
                            else
                            {
                                string mess = "上报ERP无响应";
                                if (response != null) mess = response.resultMsg;
                                _messageInfoService.AddMessageInfo(MessageGroupByEnum.InOrderAlarm, $"入库单号【{item.Key}】完成上报ERP失败", mess);
                                continue;
                            }
                        }
                    }
                }
                _cabinDetailServices.Repository.DeleteAndMoveIntoHty(cabinOrderDetails, OperateTypeEnum.自动完成);
                _cabinOrderServices.Repository.DeleteAndMoveIntoHty(cabinOrders, OperateTypeEnum.自动完成);
                #endregion
                return responseContent.OK();
            }
            catch (Exception ex)
            {
                return responseContent.Error("批量处理失败:" + ex.Message);
            }
        }
        #endregion
 
        #region 出库完成上报ERP
        /// <summary>
        /// 出库报完成接口
        /// </summary>
        /// <param name="out_no">出库单号</param>
        /// <returns></returns>
        public WebResponseContent CompleteAllOutOrders()
        {
            var responseContent = new WebResponseContent();
            try
            {
                #region 查找所有已完成出库单
                var outorders = _deliveryOrderServices.Repository.QueryData(x => x.OutStatus == "已完成").Select(x => x.Out_no).Distinct().ToList();
                var Orders = _deliveryOrderServices.Db.Queryable<Dt_DeliveryOrder>().Where(x => outorders.Contains(x.Out_no)).Includes(x => x.Details).ToList();
                List<Dt_DeliveryOrder> cabinOrders = new List<Dt_DeliveryOrder>();
                List<Dt_DeliveryOrderDetail> cabinOrderDetails = new List<Dt_DeliveryOrderDetail>();
                var url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";
                foreach (var item in Orders.GroupBy(x => x.Out_no))
                {
                    if (!item.Where(x => x.OutStatus != "已完成").Any())
                    {
                        if (item.First().Out_type == OutOrderTypeEnum.Allocate.ObjToInt().ToString())
                        {
                            foreach (var a in item)
                            {
                                if (a.Details != null) cabinOrderDetails.AddRange(a.Details);
                                a.Details = null;
                                cabinOrders.Add(a);
                            }
                        }
                        else
                        {
                            if (item.First().Out_type == "3") url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";//入库退货
                            var result = HttpHelper.Post(url, new { order_no = item.Key }.ToJsonString());
                            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                            if (response != null && response.resultCode == "0")
                            {
                                foreach (var a in item)
                                {
                                    if (a.Details != null) cabinOrderDetails.AddRange(a.Details);
                                    a.Details = null;
                                    cabinOrders.Add(a);
                                }
                            }
                            else
                            {
                                string mess = "上报ERP无响应";
                                if (response != null) mess = response.resultMsg;
                                _messageInfoService.AddMessageInfo(MessageGroupByEnum.InOrderAlarm, $"出库单号【{item.Key}】完成上报ERP失败", mess);
                                continue;
                            }
                        }
                    }
                }
                _deliveryOrderDetailServices.Repository.DeleteAndMoveIntoHty(cabinOrderDetails, OperateTypeEnum.自动完成);
                _deliveryOrderServices.Repository.DeleteAndMoveIntoHty(cabinOrders, OperateTypeEnum.自动完成);
 
                #endregion
                return responseContent.OK();
            }
            catch (Exception ex)
            {
                return responseContent.Error("批量处理失败:" + ex.Message);
            }
        }
        #endregion
 
        #region 推送异常上报ERP
        /// <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);
            }
        }
        #endregion
    }
}