using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using ASTM_D7896_Tester.Models;
using ASTM_D7896_Tester.ViewModels;

namespace ASTM_D7896_Tester.Services;

public class ReportService
{
    private readonly string _outputDirectory;

    public ReportService(string outputDirectory)
    {
        _outputDirectory = outputDirectory;
        if (!Directory.Exists(_outputDirectory))
            Directory.CreateDirectory(_outputDirectory);
    }

    public async Task<string> GenerateReportAsync(
        string sampleId,
        double testTemperature,
        List<MeasurementResult> measurements,
        double avgLambda,
        double avgAlpha,
        double avgVhc,
        TestParameters parameters,
        Dictionary<string, object> extraParams = null)
    {
        var sb = new StringBuilder();
        sb.AppendLine("=".PadRight(80, '='));
        sb.AppendLine("ASTM D7896-19 瞬态热线法热导率测试报告");
        sb.AppendLine("=".PadRight(80, '='));
        sb.AppendLine($"样品ID: {sampleId}");
        sb.AppendLine($"测试日期: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        sb.AppendLine($"测试温度: {testTemperature:F2} °C");
        sb.AppendLine($"铂丝参数: 长度={parameters.PlatinumWireLength * 1000:F1} mm, 直径={parameters.PlatinumWireDiameter * 1000:F3} mm");
        sb.AppendLine($"重复测量次数: {parameters.MeasurementCount}");
        sb.AppendLine($"测量间隔: {parameters.IntervalSeconds} 秒");


        if (extraParams != null)
        {
            sb.AppendLine();
            sb.AppendLine("----- 测试条件与合规性确认 (依据ASTM D7896-19) -----");
            if (extraParams.ContainsKey("SampleVolume"))
                sb.AppendLine($"样品体积 (章节7.5): {extraParams["SampleVolume"]} mL");
            if (extraParams.ContainsKey("BubbleRemoved"))
                sb.AppendLine($"气泡清除确认 (章节7.6): {((bool)extraParams["BubbleRemoved"] ? "是" : "否")}");
            if (extraParams.ContainsKey("UsePressure") && (bool)extraParams["UsePressure"])
                sb.AppendLine($"加压测试 (附录A2): 压力 = {extraParams["PressureValue"]} kPa");
            else if (extraParams.ContainsKey("UsePressure"))
                sb.AppendLine($"加压测试 (附录A2): 未加压（液体蒸气压≤33.8kPa）");

            if (extraParams.ContainsKey("IsCleanConfirmed"))
            {
                string cleaner = extraParams.ContainsKey("CleanerName") ? extraParams["CleanerName"]?.ToString() ?? "" : "";
                sb.AppendLine($"采样池清洁确认 (章节7.1): {((bool)extraParams["IsCleanConfirmed"] ? "是" : "否")}，清洁人: {cleaner}");
            }
            if (extraParams.ContainsKey("AmbientCalibrated"))
                sb.AppendLine($"环境温度校准 (章节8.1): {((bool)extraParams["AmbientCalibrated"] ? $"是，温度 {extraParams["AmbientTemperature"]} °C" : "否")}");
            if (extraParams.ContainsKey("PlatinumCompatible"))
                sb.AppendLine($"铂反应性确认 (章节1.4): {((bool)extraParams["PlatinumCompatible"] ? "液体与铂兼容" : "未确认")}");
            if (extraParams.ContainsKey("LiquidReactivityNote") && !string.IsNullOrWhiteSpace(extraParams["LiquidReactivityNote"]?.ToString()))
                sb.AppendLine($"备注: {extraParams["LiquidReactivityNote"]}");
        }



        sb.AppendLine();
        sb.AppendLine("序号\t热导率 (W/m·K)\t热扩散率 (×10⁻⁶ m²/s)\t体积热容 (kJ/m³·K)");
        sb.AppendLine("----\t----------------\t------------------------\t-------------------");

        foreach (var m in measurements)
        {
            sb.AppendLine($"{m.Index}\t{m.ThermalConductivity:F5}\t\t{m.ThermalDiffusivity:F5}\t\t\t{m.VolumetricHeatCapacity:F2}");
        }

        sb.AppendLine();
        sb.AppendLine("平均值:");
        sb.AppendLine($"  热导率 λ: {avgLambda:F5} W/m·K");
        sb.AppendLine($"  热扩散率 α: {avgAlpha:F5} ×10⁻⁶ m²/s");
        sb.AppendLine($"  体积热容 VHC: {avgVhc:F2} kJ/m³·K");

        // 章节10：精密度声明
        sb.AppendLine();
        sb.AppendLine("----- 精密度与偏倚声明 (章节10) -----");
        sb.AppendLine("本测量结果可参考ASTM D7896-19标准中给出的重复性限值进行评定。");
        sb.AppendLine("例如：对于热导率，重复性限值(r)约为平均值的2-5%（依样品而定）。");
        sb.AppendLine("本软件不对测量结果的符合性做出直接判定，用户应参考标准原文进行评估。");

        sb.AppendLine();
        sb.AppendLine("备注：本报告依据ASTM D7896-19标准生成，数据由瞬态热线法测量系统自动采集。");
        sb.AppendLine("=".PadRight(80, '='));

        string fileName = $"D7896_Report_{sampleId}_{DateTime.Now:yyyyMMdd_HHmmss}.txt";
        string fullPath = Path.Combine(_outputDirectory, fileName);
        await File.WriteAllTextAsync(fullPath, sb.ToString(), Encoding.UTF8);
        return fullPath;
    }
}