using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using FootwearTest.Models;
using FootwearTest.Services;
using Microsoft.Extensions.Logging;

namespace FootwearTest.ViewModels;

public partial class ReportViewModel : ViewModelBase
{
    private readonly TestRunRepository _repository;
    private readonly ReportService _reportService;
    private readonly ExcelReportService _excelReportService;
    private readonly ILogger<ReportViewModel> _logger;

    public ReportViewModel(
        TestRunRepository repository,
        ReportService reportService,
        ExcelReportService excelReportService,
        ILogger<ReportViewModel> logger)
    {
        _repository = repository;
        _reportService = reportService;
        _excelReportService = excelReportService;
        _logger = logger;
        LoadLatestCommand = new AsyncRelayCommand(LoadLatestAsync);
        ExportLatestExcelCommand = new AsyncRelayCommand(ExportLatestExcelAsync);
        _ = LoadLatestAsync();
    }

    public IAsyncRelayCommand LoadLatestCommand { get; }
    public IAsyncRelayCommand ExportLatestExcelCommand { get; }

    private string _reportText = "暂无报告。完成一次试验后会自动生成报告文本。";
    private string _exportStatusText = "Excel 报告将导出到桌面“整鞋试验报告”文件夹。";
    private TestRunRecord? _latestRecord;

    public string ReportText
    {
        get => _reportText;
        set => SetProperty(ref _reportText, value);
    }

    public string ExportStatusText
    {
        get => _exportStatusText;
        set => SetProperty(ref _exportStatusText, value);
    }

    private async Task LoadLatestAsync()
    {
        try
        {
            var record = await _repository.GetLatestAsync();
            _latestRecord = record;
            ReportText = record is null ? "暂无报告。完成一次试验后会自动生成报告文本。" : _reportService.CreateTextReport(record);
            ExportStatusText = record is null ? "暂无可导出的报告。" : "Excel 报告将导出到桌面“整鞋试验报告”文件夹。";
            _logger.LogInformation("Latest report loaded. RecordId={RecordId}", record?.Id);
        }
        catch (Exception ex)
        {
            ReportText = $"报告加载失败: {ex.Message}";
            ExportStatusText = "报告加载失败，无法导出。";
            _logger.LogError(ex, "Failed to load latest report");
        }
    }

    private async Task ExportLatestExcelAsync()
    {
        var record = _latestRecord ?? await _repository.GetLatestAsync();
        if (record is null)
        {
            ExportStatusText = "暂无可导出的报告。";
            return;
        }

        try
        {
            var path = await _excelReportService.ExportAsync(record);
            ExportStatusText = $"已导出 Excel: {path}";
            _logger.LogInformation("Latest report exported. RecordId={RecordId}, Path={Path}", record.Id, path);
        }
        catch (Exception ex)
        {
            ExportStatusText = $"导出失败: {ex.Message}";
            _logger.LogError(ex, "Failed to export latest report. RecordId={RecordId}", record.Id);
        }
    }
}
