using System;
using System.IO;
using System.Threading.Tasks;
using AI.AgentIntegration;
using GeoSigmaDrawLib;
namespace PcgDrawR.Services
{
///
/// 负责各种“从文件导入”相关的业务逻辑(井点 / 井曲线等)。
///
public class ImportService
{
private readonly IAppEnvironment env;
public ImportService(IAppEnvironment env)
{
this.env = env ?? throw new ArgumentNullException(nameof(env));
}
///
/// 从指定文件导入井点数据。
/// 要求文件内容为 GeoSigma 井点导入所需的 XML 文本(与界面导入生成的 XML 格式一致)。
///
public Task ImportWellPointsAsync(AppAction action)
{
return ImportAsync(action, StreamImportType.Points, "井点");
}
///
/// 从指定文件导入井曲线数据。
/// 要求文件内容为 GeoSigma 曲线导入所需的 XML 文本。
///
public Task ImportWellCurvesAsync(AppAction action)
{
return ImportAsync(action, StreamImportType.Curves, "井曲线");
}
private Task ImportAsync(AppAction action, StreamImportType type, string entityName)
{
if (!action.Parameters.TryGetValue("path", out var pathObj))
{
return Task.FromResult(AppActionResult.Fail("缺少 'path' 参数"));
}
var path = pathObj.ToString();
if (string.IsNullOrWhiteSpace(path))
{
return Task.FromResult(AppActionResult.Fail("参数 'path' 不能为空"));
}
if (!File.Exists(path))
{
return Task.FromResult(AppActionResult.Fail($"文件不存在: {path}"));
}
if (env.ActiveGeo == null)
{
return Task.FromResult(AppActionResult.Fail($"当前没有打开任何图件,无法导入{entityName}"));
}
try
{
ImportFile(path, type);
return Task.FromResult(AppActionResult.Sucess($"{entityName}导入成功"));
}
catch (Exception ex)
{
return Task.FromResult(AppActionResult.Fail($"{entityName}导入失败: {ex.Message}"));
}
}
private void ImportFile(string path, StreamImportType type)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
using var importer = env.ActiveGeo?.CreateStreamImporter(type);
if (importer == null)
{
return;
}
byte[] buffer = new byte[4096];
int n = 0;
while ((n = stream.Read(buffer, 0, buffer.Length)) > 0)
{
importer.Write(buffer, n);
}
}
}
}