using System.Text.Json;
using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Models.Order;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Core.Services;

/// <summary>
/// 物流查询服务实现
/// </summary>
public class LogisticsService : ILogisticsService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly HttpClient _httpClient;
    private readonly ILogger<LogisticsService> _logger;

    // 阿里云物流API地址
    private const string LogisticsApiHost = "https://wuliu.market.alicloudapi.com";
    private const string LogisticsApiPath = "/kdi";

    public LogisticsService(
        HoneyBoxDbContext dbContext,
        HttpClient httpClient,
        ILogger<LogisticsService> logger)
    {
        _dbContext = dbContext;
        _httpClient = httpClient;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task<LogisticsQueryResult> QueryLogisticsAsync(string trackingNo, string courierCode)
    {
        try
        {
            // 获取物流API AppCode
            var appCode = await GetLogisticsAppCodeAsync();
            if (string.IsNullOrEmpty(appCode))
            {
                return new LogisticsQueryResult
                {
                    Success = false,
                    ErrorMessage = "物流查询服务未配置"
                };
            }

            // 构建请求URL
            var url = $"{LogisticsApiHost}{LogisticsApiPath}?no={trackingNo}&type={courierCode}";

            // 创建HTTP请求
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Add("Authorization", $"APPCODE {appCode}");

            // 发送请求
            var response = await _httpClient.SendAsync(request);
            var content = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("物流查询API返回错误: StatusCode={StatusCode}, Content={Content}", 
                    response.StatusCode, content);
                return new LogisticsQueryResult
                {
                    Success = false,
                    ErrorMessage = GetErrorMessage(response.StatusCode, content)
                };
            }

            // 解析响应
            var apiResponse = JsonSerializer.Deserialize<LogisticsApiResponse>(content);
            if (apiResponse == null || apiResponse.Status != 0 || apiResponse.Msg != "ok")
            {
                return new LogisticsQueryResult
                {
                    Success = false,
                    ErrorMessage = apiResponse?.Msg ?? "物流查询失败"
                };
            }

            // 转换物流轨迹
            var traceList = apiResponse.Result?.List?.Select(t => new LogisticsTraceDto
            {
                Time = t.Time ?? string.Empty,
                Status = t.Status ?? string.Empty
            }).ToList();

            return new LogisticsQueryResult
            {
                Success = true,
                DeliveryStatus = apiResponse.Result?.DeliveryStatus ?? 0,
                TraceList = traceList
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "物流查询异常: TrackingNo={TrackingNo}, CourierCode={CourierCode}", 
                trackingNo, courierCode);
            return new LogisticsQueryResult
            {
                Success = false,
                ErrorMessage = "物流查询服务异常"
            };
        }
    }

    /// <summary>
    /// 获取物流API AppCode
    /// </summary>
    private async Task<string?> GetLogisticsAppCodeAsync()
    {
        var config = await _dbContext.Configs
            .Where(c => c.ConfigKey == "base")
            .Select(c => c.ConfigValue)
            .FirstOrDefaultAsync();

        if (string.IsNullOrEmpty(config))
            return null;

        try
        {
            var settings = JsonSerializer.Deserialize<Dictionary<string, object>>(config);
            if (settings != null && settings.TryGetValue("logistics_code", out var codeObj))
            {
                return codeObj?.ToString();
            }
        }
        catch
        {
            // 配置解析失败
        }

        return null;
    }

    /// <summary>
    /// 获取错误消息
    /// </summary>
    private static string GetErrorMessage(System.Net.HttpStatusCode statusCode, string content)
    {
        return statusCode switch
        {
            System.Net.HttpStatusCode.BadRequest when content.Contains("Invalid Param Location") => "参数错误",
            System.Net.HttpStatusCode.BadRequest when content.Contains("Invalid AppCode") => "AppCode错误",
            System.Net.HttpStatusCode.BadRequest when content.Contains("Invalid Url") => "请求的 Method、Path 或者环境错误",
            System.Net.HttpStatusCode.Forbidden when content.Contains("Unauthorized") => "服务未被授权",
            System.Net.HttpStatusCode.Forbidden when content.Contains("Quota Exhausted") => "套餐包次数用完",
            System.Net.HttpStatusCode.InternalServerError => "API网关错误",
            _ => "物流查询失败"
        };
    }
}

/// <summary>
/// 物流API响应
/// </summary>
internal class LogisticsApiResponse
{
    public int Status { get; set; }
    public string? Msg { get; set; }
    public LogisticsApiResult? Result { get; set; }
}

/// <summary>
/// 物流API结果
/// </summary>
internal class LogisticsApiResult
{
    public int DeliveryStatus { get; set; }
    public List<LogisticsApiTrace>? List { get; set; }
}

/// <summary>
/// 物流API轨迹
/// </summary>
internal class LogisticsApiTrace
{
    public string? Time { get; set; }
    public string? Status { get; set; }
}
