using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.TencentLocation;
using NCC.FriendlyException;
using Newtonsoft.Json.Linq;
namespace NCC.Extend
{
///
/// 腾讯位置服务(后端代理 WebService:IP 定位、地址解析、地点搜索、逆地址解析)
///
[ApiDescriptionSettings(Tag = "Extend", Name = "LqTencentLocation", Order = 210)]
[Route("api/Extend/[controller]")]
[ApiController]
public class LqTencentLocationService : IDynamicApiController, ITransient
{
private const string TencentWsBaseUrl = "https://apis.map.qq.com";
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
///
/// 初始化腾讯位置服务
///
/// 配置
/// HttpClient 工厂
/// 日志
public LqTencentLocationService(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
ILogger logger)
{
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_logger = logger;
}
///
/// 腾讯位置服务 IP 定位
///
///
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/location/v1/ip
/// - 用于门店资料页在无经纬度时获取大概中心点与城市
///
/// 示例请求:
/// ```json
/// {}
/// ```
///
/// 参数说明:
/// - 无必填参数,服务端按请求 IP 定位
///
/// 定位坐标与城市
/// 定位成功
/// Key 缺失 / 腾讯接口业务错误
/// 服务器内部错误
[HttpGet("IpLocate")]
public async Task IpLocate()
{
var json = await CallTencentWsAsync("/ws/location/v1/ip", "腾讯 IP 定位");
var lat = json["result"]?["location"]?["lat"]?.Value();
var lng = json["result"]?["location"]?["lng"]?.Value();
if (!lat.HasValue || !lng.HasValue)
{
_logger.LogWarning("腾讯 IP 定位返回无坐标 body={Body}", Truncate(json.ToString(), 1200));
throw NCCException.Oh("腾讯 IP 定位返回坐标为空");
}
var city = json["result"]?["ad_info"]?["city"]?.ToString();
return new TencentIpLocateOutput
{
location = new TencentLocationDto
{
latitude = lat.Value,
longitude = lng.Value
},
city = string.IsNullOrWhiteSpace(city) ? null : city
};
}
///
/// 腾讯位置服务地址解析(地址 → 坐标)
///
///
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/geocoder/v1/(地址解析)
/// - 适合完整地址检索,失败时前端可再调用 PlaceSearch
///
/// 示例请求:
/// ```json
/// {
/// "address": "成都市武侯区天府大道",
/// "region": "成都"
/// }
/// ```
///
/// 参数说明:
/// - address: 待解析地址(必填)
/// - region: 指定地址所属城市,可选,可提高解析准确度
///
/// 待解析地址
/// 城市范围,可选
/// 解析后的坐标
/// 解析成功
/// 参数错误 / Key 缺失 / 腾讯接口业务错误
/// 服务器内部错误
[HttpGet("GeocodeAddress")]
public async Task GeocodeAddress(
[FromQuery] string address,
[FromQuery] string region = null)
{
if (string.IsNullOrWhiteSpace(address))
throw NCCException.Oh("address 不能为空");
var path = $"/ws/geocoder/v1/?address={Uri.EscapeDataString(address.Trim())}";
if (!string.IsNullOrWhiteSpace(region))
path += $"®ion={Uri.EscapeDataString(region.Trim())}";
var json = await CallTencentWsAsync(path, "腾讯地址解析");
var lat = json["result"]?["location"]?["lat"]?.Value();
var lng = json["result"]?["location"]?["lng"]?.Value();
if (!lat.HasValue || !lng.HasValue)
{
_logger.LogWarning(
"腾讯地址解析返回无坐标 address={Address} body={Body}",
address,
Truncate(json.ToString(), 1200));
throw NCCException.Oh("腾讯地址解析返回坐标为空");
}
return new TencentGeocodeAddressOutput
{
location = new TencentLocationDto
{
latitude = lat.Value,
longitude = lng.Value
}
};
}
///
/// 腾讯位置服务地点搜索
///
///
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/place/v1/search
/// - boundary 与前端一致:region(cityName,1),page_size=10
/// - 无匹配结果时返回空 list,不抛业务错误
///
/// 示例请求:
/// ```json
/// {
/// "keyword": "绿纤美业",
/// "region": "成都"
/// }
/// ```
///
/// 参数说明:
/// - keyword: 搜索关键词(必填)
/// - region: 城市名称,可选,默认「全国」
///
/// 搜索关键词
/// 城市范围,可选,默认全国
/// 地点列表
/// 搜索成功(含空列表)
/// 参数错误 / Key 缺失
/// 服务器内部错误
[HttpGet("PlaceSearch")]
public async Task PlaceSearch(
[FromQuery] string keyword,
[FromQuery] string region = null)
{
if (string.IsNullOrWhiteSpace(keyword))
throw NCCException.Oh("keyword 不能为空");
var cityName = string.IsNullOrWhiteSpace(region) ? "全国" : region.Trim();
var boundary = $"region({cityName},1)";
var path = $"/ws/place/v1/search?keyword={Uri.EscapeDataString(keyword.Trim())}"
+ $"&boundary={Uri.EscapeDataString(boundary)}&page_size=10";
var json = await CallTencentWsAsync(path, "腾讯地点搜索", throwOnBusinessError: false);
var status = json["status"]?.Value() ?? -1;
if (status != 0)
return new TencentPlaceSearchOutput();
var data = json["data"] as JArray;
if (data == null || data.Count == 0)
return new TencentPlaceSearchOutput();
var list = new List();
foreach (var item in data)
{
var lat = item["location"]?["lat"]?.Value();
var lng = item["location"]?["lng"]?.Value();
if (!lat.HasValue || !lng.HasValue)
continue;
list.Add(new TencentPlaceSearchItemDto
{
title = item["title"]?.ToString(),
address = item["address"]?.ToString(),
location = new TencentLocationDto
{
latitude = lat.Value,
longitude = lng.Value
}
});
}
return new TencentPlaceSearchOutput { list = list };
}
///
/// 腾讯位置服务逆地址解析(经纬度 → 文字地址)
///
///
/// 说明:
/// - 后端从配置读取腾讯位置服务 Key,不下发到前端
/// - 调用腾讯接口:/ws/geocoder/v1/(逆地址解析)
///
/// 示例请求:
/// ```json
/// {
/// "latitude": 30.572269,
/// "longitude": 104.066541
/// }
/// ```
///
/// 参数说明:
/// - latitude: 纬度(-90~90)
/// - longitude: 经度(-180~180)
///
/// 纬度
/// 经度
/// 原始坐标与解析后的地址
/// 解析成功
/// 参数错误 / Key 缺失 / 腾讯接口业务错误
/// 服务器内部错误
[HttpGet("ReverseGeocode")]
public async Task ReverseGeocode(
[FromQuery] decimal? latitude,
[FromQuery] decimal? longitude)
{
if (!latitude.HasValue || !longitude.HasValue)
throw NCCException.Oh("latitude/longitude 不能为空");
if (latitude.Value < -90 || latitude.Value > 90)
throw NCCException.Oh("latitude 超出范围(-90~90)");
if (longitude.Value < -180 || longitude.Value > 180)
throw NCCException.Oh("longitude 超出范围(-180~180)");
var latStr = latitude.Value.ToString(CultureInfo.InvariantCulture);
var lngStr = longitude.Value.ToString(CultureInfo.InvariantCulture);
var path = $"/ws/geocoder/v1/?location={latStr},{lngStr}&get_poi=0";
var json = await CallTencentWsAsync(path, "腾讯逆地址解析", throwOnBusinessError: true, latStr, lngStr);
var address = json["result"]?["address"]?.ToString();
if (string.IsNullOrWhiteSpace(address))
{
_logger.LogWarning(
"腾讯逆地址解析返回无address lat={Lat} lng={Lng} body={Body}",
latStr,
lngStr,
Truncate(json.ToString(), 1200));
throw NCCException.Oh("腾讯逆地址解析返回地址为空");
}
return new TencentReverseGeocodeOutput
{
location = new TencentLocationDto
{
latitude = latitude.Value,
longitude = longitude.Value
},
address = address
};
}
///
/// 读取腾讯位置服务 Key
///
private string GetLbsKey()
{
var key = _configuration["NCC_App:TencentLbs:Key"]
?? _configuration["NCC_APP:TencentLbs:Key"];
if (string.IsNullOrWhiteSpace(key))
throw NCCException.Oh("腾讯位置服务 Key 未配置,请设置配置项 NCC_App:TencentLbs:Key(或环境变量映射)");
return key;
}
///
/// 读取腾讯 WebService 超时秒数,默认 5 秒
///
private int GetTimeoutSeconds()
{
var timeoutSecondsRaw = _configuration["NCC_App:TencentLbs:TimeoutSeconds"]
?? _configuration["NCC_APP:TencentLbs:TimeoutSeconds"];
var timeoutSeconds = 5;
if (!string.IsNullOrWhiteSpace(timeoutSecondsRaw)
&& int.TryParse(timeoutSecondsRaw, out var ts)
&& ts > 0)
{
timeoutSeconds = ts;
}
return timeoutSeconds;
}
///
/// 调用腾讯 WebService(自动附加 Key),校验 HTTP 与 status==0
///
/// 相对路径或不含 Key 的完整 URL
/// 日志中的操作名称
/// status!=0 时是否抛错;PlaceSearch 无结果场景传 false
/// 附加日志上下文
private async Task CallTencentWsAsync(
string relativeOrFullUrlWithoutKey,
string operationName,
bool throwOnBusinessError = true,
params string[] contextArgs)
{
var url = BuildTencentUrl(relativeOrFullUrlWithoutKey);
var timeoutSeconds = GetTimeoutSeconds();
var sw = Stopwatch.StartNew();
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
var client = _httpClientFactory.CreateClient();
using var req = new HttpRequestMessage(HttpMethod.Get, url);
using var resp = await client.SendAsync(req, HttpCompletionOption.ResponseContentRead, cts.Token);
var body = await resp.Content.ReadAsStringAsync(cts.Token);
if (!resp.IsSuccessStatusCode)
{
_logger.LogWarning(
"{Operation} HTTP失败 status={Status} context={Context} costMs={CostMs} body={Body}",
operationName,
(int)resp.StatusCode,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds,
Truncate(body, 1200));
throw NCCException.Oh($"{operationName} HTTP 请求失败:{(int)resp.StatusCode}");
}
var json = JObject.Parse(body);
var status = json["status"]?.Value() ?? -1;
var message = json["message"]?.ToString() ?? "";
if (status != 0)
{
_logger.LogWarning(
"{Operation} 业务失败 status={Status} msg={Msg} context={Context} costMs={CostMs} body={Body}",
operationName,
status,
message,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds,
Truncate(body, 1200));
if (throwOnBusinessError)
throw NCCException.Oh($"{operationName}失败:{(message.Length > 0 ? message : "未知错误")}");
return json;
}
_logger.LogInformation(
"{Operation} 成功 context={Context} costMs={CostMs}",
operationName,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds);
return json;
}
catch (OperationCanceledException ex)
{
_logger.LogWarning(
ex,
"{Operation} 超时 context={Context} costMs={CostMs} timeoutSeconds={TimeoutSeconds}",
operationName,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds,
timeoutSeconds);
throw NCCException.Oh($"{operationName}超时({timeoutSeconds}s)");
}
catch (AppFriendlyException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"{Operation} 异常 context={Context} costMs={CostMs}",
operationName,
string.Join(",", contextArgs),
sw.ElapsedMilliseconds);
throw NCCException.Oh($"{operationName}异常:{ex.Message}");
}
}
///
/// 拼接腾讯 WebService 完整 URL 并附加 Key
///
private string BuildTencentUrl(string relativeOrFullUrlWithoutKey)
{
var key = GetLbsKey();
var url = relativeOrFullUrlWithoutKey.StartsWith("http", StringComparison.OrdinalIgnoreCase)
? relativeOrFullUrlWithoutKey
: TencentWsBaseUrl + (relativeOrFullUrlWithoutKey.StartsWith("/")
? relativeOrFullUrlWithoutKey
: "/" + relativeOrFullUrlWithoutKey);
var separator = url.Contains("?", StringComparison.Ordinal) ? "&" : "?";
return url + separator + "key=" + Uri.EscapeDataString(key);
}
private static string Truncate(string text, int maxLen)
{
if (string.IsNullOrEmpty(text)) return text;
return text.Length <= maxLen ? text : text.Substring(0, maxLen) + "...";
}
}
}