forked from ddrilling/AsbCloudServer
81 lines
2.8 KiB
C#
81 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using AsbCloudApp.Data;
|
|
using AsbCloudApp.Services;
|
|
using AsbCloudDb.Model;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using NPOI.SS.UserModel;
|
|
using NPOI.XSSF.UserModel;
|
|
|
|
namespace AsbCloudInfrastructure.Services
|
|
{
|
|
public class DrillingProgramService : IDrillingProgramService
|
|
{
|
|
private readonly IFileService fileService;
|
|
private readonly WellService wellService;
|
|
private const int idFileCategoryPlan = 13;
|
|
|
|
public DrillingProgramService(IFileService fileService, WellService wellService)
|
|
{
|
|
this.fileService = fileService;
|
|
this.wellService = wellService;
|
|
}
|
|
|
|
public async Task<FileInfoDto> GetAsync(int idWell, CancellationToken token = default)
|
|
{
|
|
var filesInfos = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryPlan, token)
|
|
.ConfigureAwait(false);
|
|
|
|
var well = await wellService.GetAsync(idWell, token)
|
|
.ConfigureAwait(false);
|
|
|
|
var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx";
|
|
|
|
var matchFile = filesInfos.FirstOrDefault(f=>f.Name == resultFileName);
|
|
if (matchFile is not null) {
|
|
if (filesInfos.All(f => f.UploadDate <= matchFile.UploadDate))
|
|
return matchFile;
|
|
else
|
|
await fileService.DeletedAsync(matchFile.Id, token);
|
|
}
|
|
|
|
var fileNames = filesInfos
|
|
.Where(f => f.Name != resultFileName)
|
|
.Select(f => fileService.GetFileName(f));
|
|
|
|
var stream = new MemoryStream(1024 * 1024);
|
|
UniteExcelFiles(fileNames, stream);
|
|
stream.Seek(0, SeekOrigin.Begin);
|
|
return await fileService.SaveAsync(idWell, 0, idFileCategoryPlan, resultFileName, stream, token)
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
private static void UniteExcelFiles(IEnumerable<string> excelFilesNames, Stream stream)
|
|
{
|
|
IWorkbook product = new XSSFWorkbook();
|
|
|
|
foreach (var excelFileName in excelFilesNames)
|
|
{
|
|
IWorkbook book = new XSSFWorkbook(new FileStream(excelFileName, FileMode.Open));
|
|
|
|
for (int i = 0; i < book.NumberOfSheets; i++)
|
|
{
|
|
ISheet sheet = book.GetSheetAt(i);
|
|
try
|
|
{
|
|
sheet.CopyTo(product, sheet.SheetName, true, true);
|
|
}
|
|
catch
|
|
{
|
|
//what can't be done - can't be done. ignore it.
|
|
}
|
|
}
|
|
}
|
|
product.Write(stream);
|
|
}
|
|
}
|
|
} |