using Magicodes.ExporterAndImporter.Core.Models; using Magicodes.ExporterAndImporter.Excel; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Configuration; using OfficeOpenXml.FormulaParsing.Excel.Functions.Math; using OfficeOpenXml.FormulaParsing.Excel.Functions.Text; using Omu.ValueInjecter; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Transactions; using TaskManager.Entity; using TaskManager.EntityFramework; using TaskManager.EntityFramework.Repository; using Wood.Service.Controllers; using Wood.Util; using static Dapper.SqlMapper; namespace Wood.Service.Datas { public class SupplierEmployeeDtService : NormalBaseController { const string _taskName = "人员资质信息"; private readonly IRepository _taskSubRepository; private readonly IRepository _supplierEmployeeRepository; private readonly IRepository _taskConfigureRepository; private readonly CommonService _commonService; public SupplierEmployeeDtService(JobDbContext context, IServiceProvider builder, IConfiguration configuration, IRepository repository, IRepository taskSubRepository, IRepository supplierEmployeeRepository, IRepository taskConfigureRepository, CommonService commonService) : base(context, builder, configuration, repository) { _taskSubRepository = taskSubRepository; _supplierEmployeeRepository = supplierEmployeeRepository; _taskConfigureRepository = taskConfigureRepository; _taskSubRepository.SetDbContext(_context); _supplierEmployeeRepository.SetDbContext(_context); _taskConfigureRepository.SetDbContext(_context); _commonService = commonService; } [HttpPost] [Route("import")] public override async Task Import(IFormFile file) { if (file == null || file.Length == 0) { return NotFound(); } MemoryStream memStream = new MemoryStream(); await file.CopyToAsync(memStream); var importer = new ExcelImporter(); ImportResult impResult = await importer.Import(memStream); if (impResult.HasError) { StringBuilder sb = new StringBuilder(); foreach (var rowErr in impResult.RowErrors) { string temp = string.Join(";", rowErr.FieldErrors.Select(itm => $"第{rowErr.RowIndex}行:{itm.Key}-{itm.Value}")); sb.AppendLine(temp); } foreach (var templateErr in impResult.TemplateErrors) { string temp = $"列名:{templateErr.RequireColumnName},错误信息:{templateErr.Message}"; sb.AppendLine(temp); } throw new Exception(sb.ToString()); } var entityLst = impResult.Data.ToList(); // 校验数据长度 var validationErrors = ValidationHelper.ValidateDataLength(entityLst, _context); if (validationErrors.Any()) { throw new Exception("数据校验失败:" + string.Join(", ", validationErrors)); } using var transaction = _context.Database.BeginTransaction(); var tran = transaction.GetDbTransaction(); try { #region 数据库操作 //添加任务 TaskSub taskSubObj = _commonService.BuildTaskSub(entityLst.Count, _taskName); await _context.TaskSub.AddAsync(taskSubObj); //添加任务明细 List emps = new List(); foreach (var empDtObj in entityLst) { empDtObj.SupplierCode = VendCode; SUPPLIER_EMPLOYEE empObj = new SUPPLIER_EMPLOYEE(); empObj.InjectFrom(empDtObj); //SUPPLIER_EMPLOYEE empObj = EntityMapper.Trans(empDtObj); empObj.TaskId = taskSubObj.TaskId; //await _supplierEmployeeRepository.AddAsync(empObj); emps.Add(empObj); } _context.BulkInsert(emps); _context.BulkMerge(entityLst, options => { options.ColumnPrimaryKeyExpression = itm => new { itm.SupplierCode, itm.PlantId, itm.WorkshopId, itm.ProductionLineId, itm.StationId }; options.Transaction = tran; } ); //foreach (var empDtObj in entityLst) //{ // empDtObj.SupplierCode = VendCode; // //以“供应商代码+工厂代码+车间代码+产线代码+工位代码+操作人员账号”为唯一标识,做新增或者更新存储 // var firstObj = _context.Set().FirstOrDefault( // itm => itm.SupplierCode == empDtObj.SupplierCode // && itm.PlantId == empDtObj.PlantId // && itm.WorkshopId == empDtObj.WorkshopId // && itm.ProductionLineId == empDtObj.ProductionLineId // && itm.StationId == empDtObj.StationId // && itm.OperatorId == empDtObj.OperatorId // ); // if (firstObj == null) // { // var ret = await base.Create(empDtObj); // } // else // { // empDtObj.UId = firstObj.UId; // empDtObj.CreationTime = CommonHelper.CurrentTime; // var ret = await base.Update(empDtObj); // } //} #endregion transaction.Commit(); return Ok(true); } catch (Exception ex) { transaction.Rollback(); throw new Exception("方法体执行报错,事务回滚:" + ex.Message); } } public override async Task> Create(SUPPLIER_EMPLOYEE_DT entity) { using var transaction = _context.Database.BeginTransaction(); var tran = transaction.GetDbTransaction(); try { #region 数据库操作 //添加任务 TaskSub taskSubObj = _commonService.BuildTaskSub(1, _taskName); await _context.TaskSub.AddAsync(taskSubObj); //添加任务明细 SUPPLIER_EMPLOYEE empObj = new SUPPLIER_EMPLOYEE(); empObj.InjectFrom(entity); //EntityMapper.Trans(entity); empObj.TaskId = taskSubObj.TaskId; await _context.AddAsync(empObj); await _context.BulkMergeAsync(new List { entity }, options => { options.ColumnPrimaryKeyExpression = itm => new { itm.SupplierCode, itm.PlantId, itm.WorkshopId, itm.ProductionLineId, itm.StationId,itm.OperatorId }; options.Transaction = tran; } ); _context.SaveChanges(); ////添加任务明细 //SUPPLIER_EMPLOYEE empObj = EntityMapper.Trans(entity); //empObj.TaskId = taskSubObj.TaskId; //await _supplierEmployeeRepository.AddAsync(empObj); //var firstObj = _context.Set().FirstOrDefault( // itm => itm.SupplierCode == entity.SupplierCode // && itm.PlantId == entity.PlantId // && itm.WorkshopId == entity.WorkshopId // && itm.ProductionLineId == entity.ProductionLineId // && itm.StationId == entity.StationId // && itm.OperatorId == entity.OperatorId // ); //if (firstObj == null) //{ // var ret = await base.Create(entity); //} //else //{ // throw new Exception("数据库已经存在,不能重复插入"); //} #endregion transaction.Commit(); return Ok(true); } catch (Exception ex) { transaction.Rollback(); throw new Exception("方法体执行报错,事务回滚:" + ex.Message); } } public override async Task Update(SUPPLIER_EMPLOYEE_DT entity) { using var transaction = _context.Database.BeginTransaction(); var tran = transaction.GetDbTransaction(); try { #region 数据库操作 //添加任务 TaskSub taskSubObj = _commonService.BuildTaskSub(1, _taskName); await _context.TaskSub.AddAsync(taskSubObj); //添加任务明细 SUPPLIER_EMPLOYEE empObj = new SUPPLIER_EMPLOYEE(); empObj.InjectFrom(entity); //EntityMapper.Trans(entity); empObj.TaskId = taskSubObj.TaskId; await _context.AddAsync(empObj); await _context.BulkMergeAsync(new List { entity }, options => { options.ColumnPrimaryKeyExpression = itm => new { itm.SupplierCode, itm.PlantId, itm.WorkshopId, itm.ProductionLineId, itm.StationId, itm.OperatorId }; options.Transaction = tran; } ); _context.SaveChanges(); //TaskSub taskSubObj = _commonService.BuildTaskSub(1, _taskName); //await _taskSubRepository.AddAsync(taskSubObj); ////添加任务明细 //SUPPLIER_EMPLOYEE empObj = EntityMapper.Trans(entity); //empObj.TaskId = taskSubObj.TaskId; //await _supplierEmployeeRepository.AddAsync(empObj); //var firstObj = _context.Set().FirstOrDefault( // itm => itm.SupplierCode == entity.SupplierCode // && itm.PlantId == entity.PlantId // && itm.WorkshopId == entity.WorkshopId // && itm.ProductionLineId == entity.ProductionLineId // && itm.StationId == entity.StationId // && itm.OperatorId == entity.OperatorId // ); //if (firstObj == null) //{ // throw new Exception("数据库不存在,不能更新"); //} //else //{ // var ret = await base.Update(entity); //} #endregion transaction.Commit(); return Ok(true); } catch (Exception ex) { transaction.Rollback(); throw new Exception("方法体执行报错,事务回滚:" + ex.Message); } } } }