using System.Net;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using WmsMobileServe.Annotation;
using WmsMobileServe.Utils.HttpUtils;
using WmsMobileServe.Utils.HttpUtils.Entity;

namespace WmsMobileServe.ApiClient.Mes;

/// <summary>
/// 访问 Mes 的 api 客户端
/// </summary>
[Component]
public class MesApiClient : WebApiClient
{
    public MesApiClient()
    {
        SetBaseUrl("http://10.50.220.1:8099");
        SetResponseAction(ApiClientResponseEvent.ApiResponse);
    }


    /// <summary>
    /// 获取箱子信息
    /// </summary>
    /// <param name="boxNo"></param>
    /// <returns></returns>
    public ApiResponseInfo GetOutBoxInfo(string boxNo)
    {
        Dictionary<string, object> request = [];
        request.Add("pSN", boxNo);
        return HttpGet(request, "/Camstar/PackStock.asmx/getOutBoxInf");
    }



    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;

    public MesApiClient(string baseUrl)
    {
        _baseUrl = baseUrl.TrimEnd('/');
        _httpClient = new HttpClient
        {
            Timeout = TimeSpan.FromSeconds(30)
        };
    }

    public async Task<ApiResponseInfo> HttpGetAsync(Dictionary<string, object> parameters, string apiPath)
    {
        var responseInfo = new ApiResponseInfo
        {
            RequestTime = DateTime.Now,
            RequestMethod = "GET"
        };

        try
        {
            // 构建查询字符串
            var queryString = new StringBuilder();
            foreach (var param in parameters)
            {
                if (queryString.Length > 0)
                    queryString.Append('&');

                queryString.Append($"{WebUtility.UrlEncode(param.Key)}={WebUtility.UrlEncode(param.Value?.ToString() ?? "")}");
            }

            // 构建完整URL
            var requestUrl = $"{_baseUrl}{apiPath}?{queryString}";
            responseInfo.RequestUrl = requestUrl;
            responseInfo.RequestMsg = queryString.ToString();

            // 发送请求
            var response = await _httpClient.GetAsync(requestUrl);
            var responseContent = await response.Content.ReadAsStringAsync();

            responseInfo.ResponseTime = DateTime.Now;
            responseInfo.ResponseMsg = responseContent;
            responseInfo.IsSend = response.IsSuccessStatusCode;
            responseInfo.UseTime = (responseInfo.ResponseTime - responseInfo.RequestTime).Value.TotalMilliseconds;

            if (!response.IsSuccessStatusCode)
            {
                responseInfo.Exception = new HttpRequestException($"HTTP请求失败，状态码: {response.StatusCode}");
            }

            return responseInfo;
        }
        catch (Exception ex)
        {
            responseInfo.ResponseTime = DateTime.Now;
            responseInfo.IsSend = false;
            responseInfo.Exception = ex;
            responseInfo.UseTime = (responseInfo.ResponseTime - responseInfo.RequestTime).Value.TotalMilliseconds;
            return responseInfo;
        }
    }



}
