647556386
2025-11-22 68628c6cc163cddfcc745c225a9f3f34767261ef
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
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_DTO.Allocate;
using WIDESEA_DTO.Basic;
using WIDESEA_DTO.Inbound;
using WIDESEA_DTO.Outbound;
using WIDESEA_IBasicService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_BasicService
{
    public class InvokeMESService : IInvokeMESService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<InvokeMESService> _logger;
        private string UserName = "12312";
        private string Password = "1";
 
        private readonly IRepository<Dt_FeedbackToMes> _feedbacktomesRepository;
        private readonly IRepository<Dt_StockInfoDetail> _stockInfoDetailRepository;
        private readonly IRepository<Dt_StockInfo> _stockInfoRepository;
        private readonly IRepository<Dt_InboundOrder> _inboundOrderRepository;
        public InvokeMESService(IHttpClientFactory httpClientFactory, ILogger<InvokeMESService> logger, IRepository<Dt_FeedbackToMes> feedbacktomesRepository, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IRepository<Dt_StockInfo> stockInfoRepository, IRepository<Dt_InboundOrder> inboundOrderRepository)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
            _feedbacktomesRepository = feedbacktomesRepository;
            _stockInfoDetailRepository = stockInfoDetailRepository;
            _stockInfoRepository = stockInfoRepository;
            _inboundOrderRepository = inboundOrderRepository;
        }
 
        /// <summary>
        /// 入库反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="HttpRequestException"></exception>
        public async Task<ResponseModel> FeedbackInbound(FeedbackInboundRequestModel model)
        {
            string json =JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {           
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var _client = _httpClientFactory.CreateClient("MESUrl");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            _logger.LogInformation("InvokeMESService  FeedbackInbound :  " + json);
            var response = await _client.PostAsync("AldMaterialWarehousing/MaterialWarehousing", content);
            string body = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("InvokeMESService  FeedbackInbound  body:  " + body);
            if (!response.IsSuccessStatusCode)
            {
 
                throw new HttpRequestException(body);
            }
 
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
             
        /// <summary>
        /// 出库反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="HttpRequestException"></exception>
        public async Task<ResponseModel> FeedbackOutbound(FeedbackOutboundRequestModel model)
        {
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var _client = _httpClientFactory.CreateClient("MESUrl");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
 
            _logger.LogInformation("InvokeMESService  FeedbackOutbound :  " + json);
 
            var response = await _client.PostAsync("AldMaterialOutbound/MaterialOutbound", content);
            string body = await response.Content.ReadAsStringAsync();
 
            if (!response.IsSuccessStatusCode)
            {
 
                throw new HttpRequestException(body);
            }
 
 
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
 
        public async Task<ResponseModel> FeedbackAllocate(AllocateDto model)
        {
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var _client = _httpClientFactory.CreateClient("MESUrl");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            _logger.LogInformation("InvokeMESService  FeedbackAllocate :  " + json);
            var response = await _client.PostAsync("AldAllocationOperation/AllocationOperation", content);
            string body = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("InvokeMESService  FeedbackAllocate  body:  " + body);
            if (!response.IsSuccessStatusCode)
            {
 
                throw new HttpRequestException(body);
            }
 
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
 
        public async Task<ResponseModel> NewMaterielToMes(MaterielToMesDTO model)
        {
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
 
 
            //string userDataEncoded = Uri.EscapeDataString(json);
            ////string baseUrl = "http://mestest.ald.com//OrBitWCFServiceR15/orbitwebapi.ashx?"; 
            //string userTicket = await GetToken(UserName, Password);
            //string api = "WMS_BarcodeInformation";
 
 
            var client = _httpClientFactory.CreateClient("MESUrl");
            // 拼接 URL 参数
            // string url = $"{client.BaseAddress}UserTicket={userTicket}&API={api}&UserData={userDataEncoded}";
 
 
            client.DefaultRequestHeaders.Clear();
 
            client.DefaultRequestHeaders.Add("Accept", "application/json");
 
 
            var content = new StringContent(json, Encoding.UTF8, "application/json");
 
            _logger.LogInformation("InvokeMESService  NewMaterielToMes :  " + json);
 
            using var response = await client.PostAsync("AldBarcodeInformation/BarcodeInformation", content);
            var responseText = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("InvokeMESService  NewMaterielToMes  body:  " + responseText);
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpRequestException(responseText);
            }
 
            return JsonConvert.DeserializeObject<ResponseModel>(responseText);
        }
 
        public async Task<string> GetToken(String username, string password)
        {
 
            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            //var client = new HttpClient(clientHandler);
            var client = _httpClientFactory.CreateClient("MESUrl");
            client.DefaultRequestHeaders.Clear();
 
 
 
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri($"{client.BaseAddress}UserName={username}&UserPassword={password}"),
                Headers ={
                    { "Accept", "*/*" },
                    { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
                    { "Connection", "keep-alive" },
                },
                Content = new MultipartFormDataContent
                {
                },
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                if (!response.IsSuccessStatusCode)
                {
 
                    throw new HttpRequestException(body);
                }
 
                return body;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderNos"></param>
        /// <param name="inout">入库传1  出库传2</param>
        /// <returns></returns>
        public async Task<WebResponseContent> BatchOrderFeedbackToMes(List<string> orderNos, int inout)
        {
            if (inout == 1)
            {
                foreach (var orderNo in orderNos)
                {
                    try
                    {
                        var stockinfos = _stockInfoRepository.Db.Queryable<Dt_StockInfo>("info").Where(info => info.StockStatus == 6)
                                        .Where(it => SqlFunc.Subqueryable<Dt_StockInfoDetail>().Where(s => s.StockId == it.Id && s.OrderNo == orderNo).Any())
                                        .ToList();
                        var feeds = _feedbacktomesRepository.Db.Queryable<Dt_FeedbackToMes>().Where(x => x.OrderNo == orderNo && x.ReportStatus == 1).Select(o => o.PalletCode).ToList();
                        var unreports = stockinfos.Where(x => !feeds.Contains(x.PalletCode)).ToList();
                        if (unreports!=null && !unreports.Any()) {
                            return WebResponseContent.Instance.Error("没有需要回传的数据");
                        }
                        foreach (var item in unreports)
                        {
                            var lists = _stockInfoDetailRepository.Db.Queryable<Dt_StockInfoDetail>().Where(x => x.StockId == item.Id).ToList();
                            if (lists.Any())
                            {
                                var inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().First(x => x.InboundOrderNo == lists.FirstOrDefault().OrderNo);
                                if (inboundOrder != null)
                                {
                                    var feedmodel = new FeedbackInboundRequestModel
                                    {
                                        reqCode = Guid.NewGuid().ToString(),
                                        reqTime = DateTime.Now.ToString(),
                                        business_type = inboundOrder.BusinessType,
                                        factoryArea = inboundOrder.FactoryArea,
                                        operationType=1,
                                        Operator= inboundOrder.Operator,
                                        orderNo = inboundOrder.UpperOrderNo,
                                        status = inboundOrder.OrderStatus,
                                        details = new List<FeedbackInboundDetailsModel>()
 
                                    };
                                    
                                    var groupedData = lists.GroupBy(item => new { item.MaterielCode, item.SupplyCode, item.BatchNo, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
                                       .Select(group => new FeedbackInboundDetailsModel
                                       {
                                           materialCode = group.Key.MaterielCode,
                                           supplyCode = group.Key.SupplyCode,
                                           batchNo = group.Key.BatchNo,
                                           lineNo = group.Key.InboundOrderRowNo,
                                           qty = group.Sum(x=>x.BarcodeQty),
                                           // warehouseCode = group.Key.WarehouseCode=="0"?"1072": group.Key.WarehouseCode,
                                           warehouseCode =group.Key.WarehouseCode,
                                           unit = group.Key.BarcodeUnit,
                                           barcodes = group.Select(row => new FeedbackBarcodesModel
                                           {
                                               barcode = row.Barcode,
                                               qty = row.BarcodeQty
                                           }).ToList()
                                       }).ToList();
                                    feedmodel.details = groupedData;
                                    var result = await FeedbackInbound(feedmodel);
                                    if (result != null && result.code == 200)
                                    {
                                        _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogInformation("InvokeMESService  BatchOrderFeedbackToMes 回写MES失败:  " + ex.Message);
                        return WebResponseContent.Instance.Error(ex.Message);
                    }
 
                }
            }
            return WebResponseContent.Instance.OK();
        }
    }
}