using Microsoft.AspNetCore.Http;
using System.Net.Http.Json;
using System.Text.Json;
namespace OASystem.API.OAMethodLib.AMapApi
{
    /// 
    /// 高德地图API Service
    /// 
    public class GeocodeService
    {
        private readonly string _apiKey = "2f5a9ef15f598df3170811f50787166a"; // 高德API Key
        private readonly HttpClient _httpClient;
        /// 
        /// 初始化
        /// 
        /// 
        public GeocodeService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
        /// 
        /// 获取单个地址的经纬度
        /// 
        /// 
        /// 
        public async Task GetGeocodeAsync(string address)
        {
            if (string.IsNullOrEmpty(address)) return new GeocodeResult { Address = address, Status = "Failed", Info = "地址为空!" };
            string url = $"https://restapi.amap.com/v3/geocode/geo?key={_apiKey}&address={Uri.EscapeDataString(address)}";
            var response = await _httpClient.GetFromJsonAsync(url);
            if (response.GetProperty("status").GetString() == "1" && response.GetProperty("geocodes").GetArrayLength() > 0)
            {
                var location = response.GetProperty("geocodes")[0].GetProperty("location").GetString();
                var coordinates = location.Split(',');
                return new GeocodeResult
                {
                    Address = address,
                    Longitude = double.Parse(coordinates[0]),
                    Latitude = double.Parse(coordinates[1]),
                    Status = "Success",
                    Info = "OK"
                };
            }
            else
            {
                return new GeocodeResult
                {
                    Address = address,
                    Status = "Failed",
                    Info = response.GetProperty("info").GetString()
                };
            }
        }
        /// 
        /// 批量获取多个地址的经纬度
        /// 
        /// 
        /// 
        /// 
        public async Task> GetGeocodesAsync(IEnumerable addresses, int qpsLimit = 3)
        {
            var results = new List();
            for (int i = 0; i < addresses.Count(); i += qpsLimit)
            {
                // 每次处理 qpsLimit 个地址
                var batch = addresses.Skip(i).Take(qpsLimit);
                // 创建并启动任务
                var tasks = batch.Select(GetGeocodeAsync).ToList();
                var batchResults = await Task.WhenAll(tasks);
                // 收集结果
                results.AddRange(batchResults);
                // 如果还有剩余请求,延迟一秒
                if (i + qpsLimit < addresses.Count())
                {
                    await Task.Delay(1000);
                }
            }
            return results;
        }
        public class GeocodeResult
        {
            public string Address { get; set; }
            public double Latitude { get; set; }
            public double Longitude { get; set; }
            public string Status { get; set; }
            public string Info { get; set; }
        }
    }
}