using Fake.Application;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Shared;
using Oms.Application.Dtos.System;
using Oms.Domain.SystemAggregate.Entities;
using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.System;
///
/// 国家州省/城市主数据 API(地址下拉与经营地图发件省归一)。
///
[ApiExplorerSettings(GroupName = "OMS-System")]
public class CountryRegionService : ApplicationService
{
private ICountryRepository CountryRepository => LazyServiceProvider.GetRequiredService();
private ICountryProvinceRepository ProvinceRepository => LazyServiceProvider.GetRequiredService();
private ICountryCityRepository CityRepository => LazyServiceProvider.GetRequiredService();
///
/// 按国家查询州省列表(维护页)。
///
/// 国家主键。
/// 州省列表,含下属城市数。
[HttpGet("/system/country/province/list")]
public async Task> GetProvinceListAsync([FromQuery] int countryId)
{
if (countryId <= 0)
{
throw new BusinessException("请指定国家");
}
var country = await GetCountryOrThrowAsync(countryId);
var provinces = await ProvinceRepository.ListByCountryIdAsync(countryId);
var cityCounts = await LoadCityCountMapAsync(provinces.Select(x => x.Id));
return provinces.Select(x => ToProvinceOutput(x, country.CountryCode, cityCounts)).ToList();
}
///
/// 地址下拉:按国家二字码返回州省选项(value=中文名)。
///
/// ISO 二字码,如 CN。
/// 州省选项;国家不存在时返回空列表。
[HttpGet("/system/country/province/options")]
public async Task> GetProvinceOptionsAsync([FromQuery] string countryCode)
{
var code = (countryCode ?? string.Empty).Trim().ToUpperInvariant();
if (string.IsNullOrWhiteSpace(code))
{
return [];
}
var country = await CountryRepository.GetByCountryCodeAsync(code);
if (country == null)
{
return [];
}
var provinces = await ProvinceRepository.ListByCountryIdAsync(country.Id);
return provinces.Select(x => new CountryProvinceOptionOutput
{
Id = x.Id,
Label = BuildLabel(x.ChineseName, x.EnglishName),
Value = x.ChineseName
}).ToList();
}
///
/// 新增州省。同一国家下中文名业务唯一。
///
[HttpPost("/system/country/province/create")]
public async Task CreateProvinceAsync([FromBody] CreateCountryProvinceInput input)
{
await GetCountryOrThrowAsync(input.CountryId);
var name = NormalizeRequiredName(input.ChineseName, "州省中文名不能为空");
await EnsureProvinceNameUniqueAsync(input.CountryId, name, excludeId: null);
await ProvinceRepository.InsertAsync(new CountryProvince
{
CountryId = input.CountryId,
ChineseName = name,
EnglishName = (input.EnglishName ?? string.Empty).Trim(),
ShortName = NullIfWhiteSpace(input.ShortName),
Lng = input.Lng,
Lat = input.Lat,
SortOrder = input.SortOrder
});
}
///
/// 更新州省。
///
[HttpPost("/system/country/province/update")]
public async Task UpdateProvinceAsync([FromBody] UpdateCountryProvinceInput input)
{
var entity = await GetProvinceOrThrowAsync(input.Id);
if (input.CountryId != entity.CountryId)
{
await GetCountryOrThrowAsync(input.CountryId);
entity.CountryId = input.CountryId;
}
var name = NormalizeRequiredName(input.ChineseName, "州省中文名不能为空");
await EnsureProvinceNameUniqueAsync(entity.CountryId, name, excludeId: entity.Id);
entity.ChineseName = name;
entity.EnglishName = (input.EnglishName ?? string.Empty).Trim();
entity.ShortName = NullIfWhiteSpace(input.ShortName);
entity.Lng = input.Lng;
entity.Lat = input.Lat;
entity.SortOrder = input.SortOrder;
await ProvinceRepository.UpdateAsync(entity);
}
///
/// 删除州省(软删除);同时软删除其下城市。
///
[HttpPost("/system/country/province/delete")]
public async Task DeleteProvinceAsync([FromBody] IdInput input)
{
var entity = await GetProvinceOrThrowAsync(input.Id);
var cities = await CityRepository.ListByProvinceIdAsync(entity.Id);
foreach (var city in cities)
{
await CityRepository.DeleteAsync(city);
}
await ProvinceRepository.DeleteAsync(entity);
}
///
/// 按州省查询城市列表(维护页)。
///
[HttpGet("/system/country/city/list")]
public async Task> GetCityListAsync([FromQuery] int provinceId)
{
if (provinceId <= 0)
{
throw new BusinessException("请指定州省");
}
await GetProvinceOrThrowAsync(provinceId);
var cities = await CityRepository.ListByProvinceIdAsync(provinceId);
return cities.Select(ToCityOutput).ToList();
}
///
/// 地址下拉:按州省 Id 返回城市选项(value=中文名)。
///
[HttpGet("/system/country/city/options")]
public async Task> GetCityOptionsAsync([FromQuery] int provinceId)
{
if (provinceId <= 0)
{
return [];
}
var cities = await CityRepository.ListByProvinceIdAsync(provinceId);
return cities.Select(x => new CountryCityOptionOutput
{
Id = x.Id,
Label = BuildLabel(x.ChineseName, x.EnglishName),
Value = x.ChineseName
}).ToList();
}
///
/// 新增城市。同一州省下中文名业务唯一。
///
[HttpPost("/system/country/city/create")]
public async Task CreateCityAsync([FromBody] CreateCountryCityInput input)
{
await GetProvinceOrThrowAsync(input.ProvinceId);
var name = NormalizeRequiredName(input.ChineseName, "城市中文名不能为空");
await EnsureCityNameUniqueAsync(input.ProvinceId, name, excludeId: null);
await CityRepository.InsertAsync(new CountryCity
{
ProvinceId = input.ProvinceId,
ChineseName = name,
EnglishName = (input.EnglishName ?? string.Empty).Trim(),
SortOrder = input.SortOrder
});
}
///
/// 更新城市。
///
[HttpPost("/system/country/city/update")]
public async Task UpdateCityAsync([FromBody] UpdateCountryCityInput input)
{
var entity = await GetCityOrThrowAsync(input.Id);
if (input.ProvinceId != entity.ProvinceId)
{
await GetProvinceOrThrowAsync(input.ProvinceId);
entity.ProvinceId = input.ProvinceId;
}
var name = NormalizeRequiredName(input.ChineseName, "城市中文名不能为空");
await EnsureCityNameUniqueAsync(entity.ProvinceId, name, excludeId: entity.Id);
entity.ChineseName = name;
entity.EnglishName = (input.EnglishName ?? string.Empty).Trim();
entity.SortOrder = input.SortOrder;
await CityRepository.UpdateAsync(entity);
}
///
/// 删除城市(软删除)。
///
[HttpPost("/system/country/city/delete")]
public async Task DeleteCityAsync([FromBody] IdInput input)
{
var entity = await GetCityOrThrowAsync(input.Id);
await CityRepository.DeleteAsync(entity);
}
private async Task GetCountryOrThrowAsync(int id)
{
var entity = await CountryRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("国家不存在");
}
return entity;
}
private async Task GetProvinceOrThrowAsync(int id)
{
var entity = await ProvinceRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("州省不存在");
}
return entity;
}
private async Task GetCityOrThrowAsync(int id)
{
var entity = await CityRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("城市不存在");
}
return entity;
}
private async Task EnsureProvinceNameUniqueAsync(int countryId, string chineseName, int? excludeId)
{
var hit = await ProvinceRepository.FindByCountryAndChineseNameAsync(countryId, chineseName);
if (hit != null && hit.Id != excludeId)
{
throw new BusinessException("该国家下州省中文名已存在");
}
}
private async Task EnsureCityNameUniqueAsync(int provinceId, string chineseName, int? excludeId)
{
var hit = await CityRepository.FindByProvinceAndChineseNameAsync(provinceId, chineseName);
if (hit != null && hit.Id != excludeId)
{
throw new BusinessException("该州省下城市中文名已存在");
}
}
private async Task> LoadCityCountMapAsync(IEnumerable provinceIds)
{
var ids = provinceIds.Distinct().ToArray();
if (ids.Length == 0)
{
return new Dictionary();
}
var cities = await CityRepository.GetListAsync(x => ids.Contains(x.ProvinceId));
return cities
.GroupBy(x => x.ProvinceId)
.ToDictionary(g => g.Key, g => g.Count());
}
private static CountryProvinceOutput ToProvinceOutput(
CountryProvince x,
string countryCode,
IReadOnlyDictionary cityCounts) =>
new()
{
Id = x.Id,
CountryId = x.CountryId,
CountryCode = countryCode,
ChineseName = x.ChineseName,
EnglishName = x.EnglishName,
ShortName = x.ShortName,
Lng = x.Lng,
Lat = x.Lat,
SortOrder = x.SortOrder,
CityCount = cityCounts.TryGetValue(x.Id, out var count) ? count : 0
};
private static CountryCityOutput ToCityOutput(CountryCity x) => new()
{
Id = x.Id,
ProvinceId = x.ProvinceId,
ChineseName = x.ChineseName,
EnglishName = x.EnglishName,
SortOrder = x.SortOrder
};
private static string NormalizeRequiredName(string? value, string emptyMessage)
{
var name = (value ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new BusinessException(emptyMessage);
}
return name;
}
private static string? NullIfWhiteSpace(string? value)
{
var trimmed = value?.Trim();
return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed;
}
private static string BuildLabel(string chineseName, string englishName)
{
if (string.IsNullOrWhiteSpace(englishName) || string.Equals(chineseName, englishName, StringComparison.OrdinalIgnoreCase))
{
return chineseName;
}
return $"{chineseName} / {englishName}";
}
}