2
schangxiang@126.com
2025-05-11 4d916744ba1ba9066d1ecf809f43ddddb817b26b
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
using CMS.Plugin.FormulaManagement.Abstractions;
using CMS.Plugin.OrderManagement.Abstractions;
using CMS.Plugin.OrderManagement.Abstractions.Enums;
using CMS.Plugin.OrderManagement.Abstractions.Models;
using CMS.Plugin.PipeLineLems.Application.Contracts.Dtos.WorkPlan;
using CMS.Plugin.ProductManagement.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Microsoft.Extensions.DependencyInjection;
using NPOI.Util;
using CMS.Plugin.PipeLineLems.Domain.CallMaterialOrder;
using CMS.Plugin.PipeLineLems.Application.Contracts.Services;
using CMS.Plugin.PipeLineLems.Application.Contracts.Dtos.CallMaterialOrder;
using Volo.Abp.Uow;
 
namespace CMS.Plugin.PipeLineLems.Application.Implements;
 
/// <summary> 
/// 作业计划表应用服务 
/// </summary> 
public class SharedService : CMSPluginAppService
{
 
    public async Task<MesOrderResponse> CommonCreatebyApsAsync(List<WorkPlanInput> input, IServiceProvider _serviceProvider,
        WorkPlanAppService workPlanAppService
        )
    {
        if (input == null)
        {
            throw new UserFriendlyException("输入参数不能为空");
        }
 
        if (input.Count == 0)
        {
            throw new UserFriendlyException("输入参数Data不能为空");
        }
 
        //校验数据
        //1、原料标识相同的不能存在于两个 管段编号中
        //var validationResult = ValidateUniqueDataIdentifierPerPipeSection(input);
        //if (!validationResult.isValid)
        //{
        //    处理验证失败的情况
        //    throw new UserFriendlyException($"验证失败: {validationResult.errorMessage}");
        //    返回错误信息给客户端或进行其他处理
        //}
 
 
        var callMaterialOrderAppService = _serviceProvider.GetRequiredService<ICallMaterialOrderAppService>();
 
        var orderManager = _serviceProvider.GetRequiredService<IOrderManager>();
        var productProvider = _serviceProvider.GetRequiredService<IProductProvider>();
        var formulaProvider = _serviceProvider.GetRequiredService<IFormulaProvider>();
        List<OrderModel> orderModels = new List<OrderModel>();
 
        #region 事务
 
        using var scope = _serviceProvider.CreateScope();
        var unitOfWorkManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
        using var uow = unitOfWorkManager.Begin(requiresNew: true);
 
        try
        {
            #region 数据处理
 
            //按照 原料标识 分组
            var groupTask = input.GroupBy(x => x.DataIdentifier);
            foreach (var gTask in groupTask)
            {
 
 
 
                //var product = await productProvider.FindByNameAsync(orderItem.PipeSectionName);
                //if (product == null)
                //{
                //    throw new UserFriendlyException($"产品名称[{orderItem.PipeSectionName}]不存在");
                //}
 
                //var formula = await formulaProvider.GetFormulaAsync(product.Id);
                //if (formula == null)
                //{
                //    throw new UserFriendlyException($"产品型号[{orderItem.MaterialCode}]无关联配方");
                //}
                //首先要创建 打码切割的工单 
                var productForCut = await productProvider.FindByNameAsync("切割原料管");
                if (productForCut == null)
                {
                    throw new UserFriendlyException($"产品名称[切割原料管]不存在");
                }
                var formulaForCut = await formulaProvider.GetFormulaAsync(productForCut.Id);
                if (formulaForCut == null)
                {
                    throw new UserFriendlyException($"产品名称[切割原料管]无关联配方");
                }
                //按照 管段编号 分组
                var group = gTask.ToList().GroupBy(x => x.PipeSpecCode);
                foreach (var item in group)
                {
                    var prodOrderNo = "Order_" + item.Key;
                    var order = await orderManager.GetByCodeAsync(prodOrderNo);
                    if (order != null)
                    {
                        throw new UserFriendlyException($"生产工单[{prodOrderNo}]已存在");
                    }
 
                    OrderModel orderModelForCut = new OrderModel()
                    {
                        Id = Guid.NewGuid(),
                        Code = prodOrderNo,
                        Source = "APS推送",
                        PlanStartTime = gTask.ToList().First().PlannedStartTime,
                        PlanFinishTime = gTask.ToList().First().PlannedEndTime,
                        PlanQty = 1,
                        Status = OrderStatus.NotActive,
                        Product = new AssociationProductModel() { Id = productForCut.Id, Name = productForCut.Name, Model = productForCut.Model, ShortNumber = productForCut.ShortNumber },
                        Formula = new AssociationFormulaModel() { Id = formulaForCut.Id, Code = formulaForCut.Code, Name = formulaForCut.Name }
                    };
                    orderModelForCut.ExtraProperties["OuterDiameter"] = gTask.ToList().First().OuterDiameter;//外径
                    orderModelForCut.ExtraProperties["Material"] = gTask.ToList().First().Material;//材质
                    orderModelForCut.ExtraProperties["Length"] = gTask.ToList().First().Length;//长度
                    orderModelForCut.ExtraProperties["DataIdentifier"] = gTask.ToList().First().DataIdentifier;//原料标识
                    orderModelForCut.ExtraProperties["MaterialMode"] = gTask.ToList().First().MaterialMode;//原料类型
                    orderModelForCut.ExtraProperties["PipeFittingCode"] = gTask.ToList().First().PipeFittingCode;//管段编号
 
                    var orderForCut = await orderManager.GetByCodeAsync(orderModelForCut.Code);
                    if (orderForCut != null)
                    {
                        //throw new UserFriendlyException($"工单[{orderModelForCut.Code}]已存在");
                        //不再抛异常,直接跳过
                        break;
                    }
 
                    var orderModelResultForCut = await orderManager.CreateAsync(orderModelForCut);
                    if (orderModelResultForCut == null)
                    {
                        throw new UserFriendlyException($"工单[{orderModelForCut.Code}]创建失败");
                    }
                    orderModels.Add(orderModelResultForCut);
 
 
                    //OrderModel orderModel = new OrderModel();
                    //orderModel.Id = Guid.NewGuid();
                    //orderModel.Code = orderItem.TaskCode;
                    //orderModel.Source = "APS推送";
                    //orderModel.Product = new AssociationProductModel() { Id = product.Id, Name = product.Name, Model = product.Model, ShortNumber = product.ShortNumber };
                    ////orderModel.Formula = new AssociationFormulaModel() { Id = formula.Id, Code = formula.Code, Name = formula.Name };
                    //orderModel.PlanStartTime = orderItem.PlannedStartTime;
                    //orderModel.PlanFinishTime = orderItem.PlannedEndTime;
                    //orderModel.PlanQty = (ulong?)orderItem.OrderQty;
                    //orderModel.Status = OrderStatus.NotActive;
                    //orderModel.ExtraProperties["Source"] = "ddd";
                    //var source = orderModel.ExtraProperties["Source"];
                    //var orderModelResult = await orderManager.CreateAsync(orderModel);
                    //if (orderModelResult == null)
                    //{
                    //    throw new UserFriendlyException($"工单[{orderItem.TaskCode}]创建失败");
                    //}
                    //orderModels.Add(orderModelResult);
                }
 
 
                //保存到 scms_callmaterialorders 表中
                CallMaterialOrderCreateDto insertObjForOrder = new CallMaterialOrderCreateDto()
                {
                    CallMaterialStatus = Domain.Shared.Enums.CallMaterialStatusEnum.未执行,
                    DataIdentifier = gTask.Key,
                    MaterialMode = gTask.ToList().First().MaterialMode,
                    Quantity = 1
                };
 
                await callMaterialOrderAppService.CreateAsync(insertObjForOrder);
            }
 
 
 
 
            //保存到  scms_workplans 表中
            foreach (var item in input)
            {
                var insertObj = ObjectMapper.Map<WorkPlanInput, WorkPlanCreateDto>(item);
                //insertObj.OrgMaterialCode = "1111";
                insertObj.CallMaterialStatus = Domain.Shared.Enums.CallMaterialStatusEnum.未执行;
                insertObj.WorkPlanStatus = Domain.Shared.Enums.WorkPlanStatusEnum.未执行;
                insertObj.Sort = 1;
                await workPlanAppService.CreateAsync(insertObj);
            }
 
            #endregion
 
            await uow.CompleteAsync();
        }
        catch (Exception)
        {
 
            throw;
        }
        finally
        {
            await uow.RollbackAsync();
        }
 
 
 
        #endregion
 
 
 
        // 发布事件
        //await _eventBus.PublishAsync(new EntityChangedEto("MESCREATE", input, null, EntityChangeType.Add, true));
 
        var response = new MesOrderResponse
        {
            Code = "000000",
            Data = orderModels,
            Fail = false,
            Mesg = "处理成功",
            Success = true,
            Time = DateTime.UtcNow
        };
        return response;
    }
 
    /// <summary>
    /// 验证原料标识相同的记录不能存在于两个不同的管段编号中
    /// </summary>
    /// <param name="inputs">作业计划输入参数列表</param>
    /// <returns>验证结果,包含是否通过验证及错误信息</returns>
    public static (bool isValid, string errorMessage) ValidateUniqueDataIdentifierPerPipeSection(List<WorkPlanInput> inputs)
    {
        if (inputs == null || !inputs.Any())
        {
            return (true, string.Empty);
        }
 
        // 使用Lookup分组,键为原料标识,值为对应的管段编号集合
        var dataIdentifierGroups = inputs.ToLookup(x => x.DataIdentifier, x => x.PipeSpecCode);
 
        foreach (var group in dataIdentifierGroups)
        {
            // 忽略空的原料标识
            if (string.IsNullOrEmpty(group.Key))
            {
                continue;
            }
 
            // 获取当前原料标识对应的唯一管段编号集合
            var uniquePipeSections = group.Distinct().ToList();
 
            // 如果存在多个不同的管段编号,则违反规则
            if (uniquePipeSections.Count > 1)
            {
                return (false, $"原料标识 '{group.Key}' 存在于多个不同的管段编号中: {string.Join(", ", uniquePipeSections)}");
            }
        }
 
        return (true, string.Empty);
    }
}