schangxiang@126.com
2025-05-10 fdf4cdbf9723d9d05938fe56d2014769dd7ece4c
PipeLineLems/server/src/CMS.Plugin.PipeLineLems.Application/Implements/MesAppService.cs
@@ -1,308 +1,164 @@
using CMS.Plugin.PipeLineLems.Application.Contracts.Dtos.MyTestEntityNames;
using CMS.Plugin.PipeLineLems.Application.Contracts.Services;
using CMS.Plugin.PipeLineLems.Domain.MyTestEntityNames;
using CMS.Plugin.PipeLineLems.Domain.Shared;
using CMS.Plugin.PipeLineLems.Domain.Shared.MyTestEntityNames;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Data;
using Volo.Abp.ObjectExtending;
//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.PipeLineLems.Application.Contracts.Services;
//using CMS.Plugin.PipeLineLems.Domain.WorkPlan;
//using CMS.Plugin.ProductManagement.Abstractions;
//using Microsoft.Extensions.DependencyInjection;
//using Volo.Abp;
namespace CMS.Plugin.PipeLineLems.Application.Implements;
//namespace CMS.Plugin.PipeLineLems.Application.Implements;
/// <inheritdoc />
public class MesAppService : CMSPluginAppService, IMesAppService
{
    private readonly IMyTestEntityNameRepository _mytestentitynameRepository;
//public class MesAppService : CMSPluginAppService, IMesAppService
//{
//    private readonly IServiceProvider _serviceProvider;
//    private readonly IWorkPlanAppService _workPlanAppService;
    /// <summary>
    /// Initializes a new instance of the <see cref="MyTestEntityNameAppService"/> class.
    /// </summary>
    /// <param name="mytestentitynameRepository">The task job repository.</param>
    public MesAppService(IMyTestEntityNameRepository mytestentitynameRepository)
    {
        _mytestentitynameRepository = mytestentitynameRepository;
    }
//    //private readonly IEventBus _eventBus;
    /// <inheritdoc />
    public virtual async Task<MyTestEntityNameDto> GetAsync(Guid id)
    {
        return ObjectMapper.Map<MyTestEntityName, MyTestEntityNameDto>(await _mytestentitynameRepository.GetAsync(id));
    }
//    public MesAppService(IServiceProvider serviceProvider
//        , IWorkPlanAppService workPlanAppService
//        //, IEventBus eventBus
//        )
//    {
//        _serviceProvider = serviceProvider;
//        // _eventBus = eventBus;
//        _workPlanAppService = workPlanAppService;
//    }
    /// <inheritdoc />
    public virtual async Task<PagedResultDto<MyTestEntityNameDto>> GetListAsync(GetMyTestEntityNamesInput input)
    {
        Check.NotNull(input, nameof(input));
//    public async Task<MesOrderResponse> CreateAsync(List<WorkPlanInput> input)
//    {
//        if (input == null)
//        {
//            throw new UserFriendlyException("输入参数不能为空");
//        }
        if (input.Sorting.IsNullOrWhiteSpace())
        {
            input.Sorting = nameof(MyTestEntityName.Sort);
        }
//        if (input.Count == 0)
//        {
//            throw new UserFriendlyException("输入参数Data不能为空");
//        }
        var specification = new MyTestEntityNameSpecification(input.Name);
        var count = await _mytestentitynameRepository.GetCountAsync(input.Filter, specification);
        var list = await _mytestentitynameRepository.GetListAsync(input.Sorting, input.MaxResultCount,  input.SkipCount, input.Filter, specification);
//        var orderManager = _serviceProvider.GetRequiredService<IOrderManager>();
//        var productProvider = _serviceProvider.GetRequiredService<IProductProvider>();
//        var formulaProvider = _serviceProvider.GetRequiredService<IFormulaProvider>();
//        List<OrderModel> orderModels = new List<OrderModel>();
//        //按照任务编号分组
//        var groupTask = input.GroupBy(x => x.TaskCode);
//        foreach (var gTask in groupTask)
//        {
//            var taskCode = gTask.Key;
//            var order = await orderManager.GetByCodeAsync(taskCode);
//            if (order != null)
//            {
//                throw new UserFriendlyException($"任务编号[{taskCode}]已存在");
//            }
        return new PagedResultDto<MyTestEntityNameDto>(count, ObjectMapper.Map<List<MyTestEntityName>, List<MyTestEntityNameDto>>(list));
    }
    /// <inheritdoc />
    public virtual async Task<MyTestEntityNameDto> CreateAsync(MyTestEntityNameCreateDto input)
    {
        await CheckCreateOrUpdateDtoAsync(input);
//            //var product = await productProvider.FindByNameAsync(orderItem.PipeSectionName);
//            //if (product == null)
//            //{
//            //    throw new UserFriendlyException($"产品名称[{orderItem.PipeSectionName}]不存在");
//            //}
        var exist = await _mytestentitynameRepository.NameExistAsync(input.Name);
        if (exist)
        {
            throw new UserFriendlyException(L[CMSPluginDomainErrorCodes.NameAlreadyExists, input.Name]);
        }
//            //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.DataIdentifier);
//            foreach (var item in group)
//            {
//                OrderModel orderModelForCut = new OrderModel()
//                {
//                    Id = Guid.NewGuid(),
//                    Code = "Cut_" + taskCode,
//                    Source = "APS推送",
//                    PlanStartTime = gTask.ToList().First().PlannedStartTime,
//                    PlanFinishTime = gTask.ToList().First().PlannedEndTime,
//                    PlanQty = (ulong)item.ToList().Count,
//                    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;//长度
        var maxSort = await _mytestentitynameRepository.GetMaxSortAsync();
        var sort = input.Sort ?? maxSort;
        var mytestentityname = new MyTestEntityName(GuidGenerator.Create(), input.Code, input.Name, sort, input.Remark);
        input.MapExtraPropertiesTo(mytestentityname, MappingPropertyDefinitionChecks.None);
//                var orderForCut = await orderManager.GetByCodeAsync(orderModelForCut.Code);
//                if (orderForCut != null)
//                {
//                    //throw new UserFriendlyException($"工单[{orderModelForCut.Code}]已存在");
//                    //不再抛异常,直接跳过
//                    break;
//                }
        await _mytestentitynameRepository.InsertAsync(mytestentityname);
//                var orderModelResultForCut = await orderManager.CreateAsync(orderModelForCut);
//                if (orderModelResultForCut == null)
//                {
//                    throw new UserFriendlyException($"工单[{orderModelForCut.Code}]创建失败");
//                }
//                orderModels.Add(orderModelResultForCut);
        if (input.Sort.HasValue && mytestentityname.Sort != maxSort)
        {
            await AdjustSortAsync(mytestentityname.Id, mytestentityname.Sort);
        }
        return ObjectMapper.Map<MyTestEntityName, MyTestEntityNameDto>(mytestentityname);
    }
//                //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);
//            }
    /// <inheritdoc />
    public virtual async Task<MyTestEntityNameDto> UpdateAsync(Guid id, MyTestEntityNameUpdateDto input)
    {
        await CheckCreateOrUpdateDtoAsync(input);
//        }
        var mytestentityname = await _mytestentitynameRepository.GetAsync(id);
        var exist = await _mytestentitynameRepository.NameExistAsync(input.Name, mytestentityname.Id);
        if (exist)
        {
            throw new UserFriendlyException(L[CMSPluginDomainErrorCodes.NameAlreadyExists, input.Name]);
        }
        mytestentityname.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);
        input.MapExtraPropertiesTo(mytestentityname, MappingPropertyDefinitionChecks.None);
//        //保存到表中
//        foreach (var item in input)
//        {
//            var insertObj = ObjectMapper.Map<WorkPlanInput, WorkPlanCreateDto>(item);
//            insertObj.OrgMaterialCode = "1111";
//            insertObj.Sort = 1;
//            await _workPlanAppService.CreateAsync(insertObj);
//        }
        mytestentityname.Update(input.Code, input.Name, input.Remark);
        await _mytestentitynameRepository.UpdateAsync(mytestentityname);
//        // 发布事件
//        //await _eventBus.PublishAsync(new EntityChangedEto("MESCREATE", input, null, EntityChangeType.Add, true));
        return ObjectMapper.Map<MyTestEntityName, MyTestEntityNameDto>(mytestentityname);
    }
    /// <inheritdoc />
    public async Task<List<MyTestEntityNameDto>> CloneAsync(IEnumerable<Guid> ids)
    {
        var mytestentitynames = new List<MyTestEntityName>();
        if (ids != null)
        {
            var sort = await _mytestentitynameRepository.GetMaxSortAsync();
            foreach (var id in ids)
            {
                var mytestentityname = await _mytestentitynameRepository.FindAsync(id);
                if (mytestentityname != null)
                {
                    var name = mytestentityname.Name + MyTestEntityNameConsts.CloneTag;
                    var notExist = false;
                    while (!notExist)
                    {
                        var exist = await _mytestentitynameRepository.NameExistAsync(name);
                        if (exist || mytestentitynames.Any(x => x.Name == name))
                        {
                            name += MyTestEntityNameConsts.CloneTag;
                            continue;
                        }
                        notExist = true;
                    }
                    mytestentityname = await _mytestentitynameRepository.InsertAsync(mytestentityname.Clone(GuidGenerator.Create(), name, sort++));
                    mytestentitynames.Add(mytestentityname);
                }
            }
        }
        return ObjectMapper.Map<List<MyTestEntityName>, List<MyTestEntityNameDto>>(mytestentitynames);
    }
    /// <inheritdoc />
    public virtual Task DeleteAsync(Guid id)
    {
        return _mytestentitynameRepository.DeleteAsync(id);
    }
    /// <inheritdoc />
    public async Task DeleteManyAsync(IEnumerable<Guid> ids)
    {
        foreach (var id in ids)
        {
            await DeleteAsync(id);
        }
    }
    /// <inheritdoc />
    public virtual async Task AdjustSortAsync(Guid id, int sort)
    {
        var list = await _mytestentitynameRepository.GetListAsync(nameof(MyTestEntityName.Sort));
        if (list != null && list.Any())
        {
            var initSort = 1;
            list.ForEach(x => x.AdjustSort(initSort++));
            var entity = list.FirstOrDefault(x => x.Id == id);
            if (entity != null)
            {
                if (sort == 1)
                {
                    list.Where(x => x.Id != id).ToList()?.ForEach(x => x.AdjustSort(x.Sort + 1));
                }
                else if (entity.Sort > sort)
                {
                    list.Where(x => x.Id != id && x.Sort >= sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort + 1));
                    list.Where(x => x.Id != id && x.Sort < sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort - 1));
                }
                else if (entity.Sort < sort)
                {
                    list.Where(x => x.Id != id && x.Sort > sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort + 1));
                    list.Where(x => x.Id != id && x.Sort <= sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort - 1));
                }
                entity.AdjustSort(sort);
            }
        }
        await _mytestentitynameRepository.UpdateManyAsync(list);
    }
    /// <inheritdoc />
    public async Task ImportAsync(MyTestEntityNamesImportModel input)
    {
        Check.NotNull(input, nameof(input));
        var mytestentitynameCreateDtos = new List<(int RowIndex, MyTestEntityNameCreateDto Item)>();
        var mytestentitynameUpdateDtos = new List<(int RowIndex, Guid Id, MyTestEntityNameUpdateDto Item)>();
        var mytestentitynames = input.MyTestEntityNames;
        if (mytestentitynames != null && mytestentitynames.Any())
        {
            #region 导入校验
            // 判断名称是否重复,并输出第几行重复
            var duplicateMyTestEntityNames = mytestentitynames.GroupBy(x => x.Name).Where(x => x.Count() > 1).ToList();
            if (duplicateMyTestEntityNames?.Any() == true)
            {
                var duplicateMyTestEntityNameMsgs = duplicateMyTestEntityNames.Select(x => $"第 {string.Join(",", x.Select(x => x.RowIndex))} 行:{x.Key}  名称重复");
                var errorMsg = $"导入失败!配置, {string.Join(",", duplicateMyTestEntityNameMsgs)},终止导入";
                throw new UserFriendlyException(errorMsg);
            }
            #endregion
            foreach (var mytestentityname in mytestentitynames)
            {
                if (mytestentityname.Code.IsNullOrWhiteSpace() && mytestentityname.Name.IsNullOrWhiteSpace())
                {
                    continue;
                }
                if (mytestentityname.Name.IsNullOrWhiteSpace())
                {
                    var errorMsg = $"导入失败!配置,第{mytestentityname.RowIndex}行:MyTestEntityName名称不能为空";
                    throw new UserFriendlyException(errorMsg);
                }
                var oldMyTestEntityName = await _mytestentitynameRepository.FindByNameAsync(mytestentityname.Name);
                if (oldMyTestEntityName != null)
                {
                    var mytestentitynameUpdateDto = new MyTestEntityNameUpdateDto
                    {
                        Code = mytestentityname.Code,
                        Name = mytestentityname.Name,
                        Remark = mytestentityname.Remark,
                    };
                    mytestentitynameUpdateDtos.Add((mytestentityname.RowIndex, oldMyTestEntityName.Id, mytestentitynameUpdateDto));
                }
                else
                {
                    var mytestentitynameCreateDto = new MyTestEntityNameCreateDto
                    {
                        Code = mytestentityname.Code,
                        Name = mytestentityname.Name,
                        Remark = mytestentityname.Remark,
                    };
                    mytestentitynameCreateDtos.Add((mytestentityname.RowIndex, mytestentitynameCreateDto));
                }
            }
        }
        // 新增
        foreach (var mytestentitynameDto in mytestentitynameCreateDtos)
        {
            try
            {
                await CreateAsync(mytestentitynameDto.Item);
            }
            catch (Exception e)
            {
                var errorMsg = $"导入失败!配置,第{mytestentitynameDto.RowIndex}行:{e.Message},终止导入";
                throw new UserFriendlyException(errorMsg);
            }
        }
        // 更新
        foreach (var mytestentitynameDto in mytestentitynameUpdateDtos)
        {
            try
            {
                await UpdateAsync(mytestentitynameDto.Id, mytestentitynameDto.Item);
            }
            catch (Exception e)
            {
                var errorMsg = $"导入失败!配置,第{mytestentitynameDto.RowIndex}行:{e.Message},终止导入";
                throw new UserFriendlyException(errorMsg);
            }
        }
    }
    /// <inheritdoc />
    public async Task<(Dictionary<string, object> Sheets, string FileName)> ExportAsync(GetMyTestEntityNamesInput input)
    {
        Check.NotNull(input, nameof(input));
        if (input.Sorting.IsNullOrWhiteSpace())
        {
            input.Sorting = nameof(MyTestEntityName.Sort);
        }
        var specification = new MyTestEntityNameSpecification(input.Name);
        var list = await _mytestentitynameRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter, specification, includeDetails: true);
        var result = ObjectMapper.Map<List<MyTestEntityName>, List<MyTestEntityNameDto>>(list);
        var sheets = new Dictionary<string, object>
        {
            ["配置"] = result.Select(x => x.GetExportData()).ToList(),
        };
        var fileName = result.Count > 1 ? "MyTestEntityName列表" : result.Count == 1 ? result.First()?.Name : "MyTestEntityName模版";
        return (sheets, fileName);
    }
    /// <summary>
    /// Checks the create or update dto asynchronous.
    /// </summary>
    /// <param name="input">The input.</param>
    protected Task CheckCreateOrUpdateDtoAsync(MyTestEntityNameCreateOrUpdateDtoBase input)
    {
        Check.NotNull(input, nameof(input));
        Check.NotNullOrWhiteSpace(input.Code, "编号", MyTestEntityNameConsts.MaxCodeLength);
        Check.NotNullOrWhiteSpace(input.Name, "名称", MyTestEntityNameConsts.MaxNameLength);
        Check.Length(input.Remark, "备注", MyTestEntityNameConsts.MaxRemarkLength);
        return Task.CompletedTask;
    }
}
//        var response = new MesOrderResponse
//        {
//            Code = "000000",
//            Data = orderModels,
//            Fail = false,
//            Mesg = "处理成功",
//            Success = true,
//            Time = DateTime.UtcNow
//        };
//        return response;
//    }
//}