SysRegionService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using NewLife.Http;
  7. using NewLife.Serialization;
  8. namespace Admin.NET.Core.Service;
  9. /// <summary>
  10. /// 系统行政区域服务 🧩
  11. /// </summary>
  12. [ApiDescriptionSettings(Order = 310)]
  13. public class SysRegionService : IDynamicApiController, ITransient
  14. {
  15. private readonly SqlSugarRepository<SysRegion> _sysRegionRep;
  16. private readonly SysConfigService _sysConfigService;
  17. // Url地址-国家统计局行政区域2023年
  18. private readonly string _url = "http://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/index.html";
  19. public SysRegionService(SqlSugarRepository<SysRegion> sysRegionRep, SysConfigService sysConfigService)
  20. {
  21. _sysRegionRep = sysRegionRep;
  22. _sysConfigService = sysConfigService;
  23. }
  24. /// <summary>
  25. /// 获取行政区域分页列表 🔖
  26. /// </summary>
  27. /// <param name="input"></param>
  28. /// <returns></returns>
  29. [DisplayName("获取行政区域分页列表")]
  30. public async Task<SqlSugarPagedList<SysRegion>> Page(PageRegionInput input)
  31. {
  32. return await _sysRegionRep.AsQueryable()
  33. .WhereIF(input.Pid > 0, u => u.Pid == input.Pid || u.Id == input.Pid)
  34. .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name))
  35. .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code))
  36. .ToPagedListAsync(input.Page, input.PageSize);
  37. }
  38. /// <summary>
  39. /// 获取行政区域列表 🔖
  40. /// </summary>
  41. /// <param name="input"></param>
  42. /// <returns></returns>
  43. [DisplayName("获取行政区域列表")]
  44. public async Task<List<SysRegion>> GetList([FromQuery] RegionInput input)
  45. {
  46. return await _sysRegionRep.GetListAsync(u => u.Pid == input.Id);
  47. }
  48. /// <summary>
  49. /// 增加行政区域 🔖
  50. /// </summary>
  51. /// <param name="input"></param>
  52. /// <returns></returns>
  53. [ApiDescriptionSettings(Name = "Add"), HttpPost]
  54. [DisplayName("增加行政区域")]
  55. public async Task<long> AddRegion(AddRegionInput input)
  56. {
  57. input.Code = input.Code?.Trim() ?? "";
  58. if (input.Code.Length != 12 && input.Code.Length != 9 && input.Code.Length != 6) throw Oops.Oh(ErrorCodeEnum.R2003);
  59. if (input.Pid != 0)
  60. {
  61. var pRegion = await _sysRegionRep.GetFirstAsync(u => u.Id == input.Pid);
  62. pRegion ??= await _sysRegionRep.GetFirstAsync(u => u.Code == input.Pid.ToString());
  63. if (pRegion == null) throw Oops.Oh(ErrorCodeEnum.D2000);
  64. input.Pid = pRegion.Id;
  65. }
  66. var isExist = await _sysRegionRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code);
  67. if (isExist) throw Oops.Oh(ErrorCodeEnum.R2002);
  68. var sysRegion = input.Adapt<SysRegion>();
  69. var newRegion = await _sysRegionRep.AsInsertable(sysRegion).ExecuteReturnEntityAsync();
  70. return newRegion.Id;
  71. }
  72. /// <summary>
  73. /// 更新行政区域 🔖
  74. /// </summary>
  75. /// <param name="input"></param>
  76. /// <returns></returns>
  77. [ApiDescriptionSettings(Name = "Update"), HttpPost]
  78. [DisplayName("更新行政区域")]
  79. public async Task UpdateRegion(UpdateRegionInput input)
  80. {
  81. input.Code = input.Code?.Trim() ?? "";
  82. if (input.Code.Length != 12 && input.Code.Length != 9 && input.Code.Length != 6) throw Oops.Oh(ErrorCodeEnum.R2003);
  83. var sysRegion = await _sysRegionRep.GetFirstAsync(u => u.Id == input.Id);
  84. if (sysRegion == null) throw Oops.Oh(ErrorCodeEnum.D1002);
  85. if (sysRegion.Pid != input.Pid && input.Pid != 0)
  86. {
  87. var pRegion = await _sysRegionRep.GetFirstAsync(u => u.Id == input.Pid);
  88. pRegion ??= await _sysRegionRep.GetFirstAsync(u => u.Code == input.Pid.ToString());
  89. if (pRegion == null) throw Oops.Oh(ErrorCodeEnum.D2000);
  90. input.Pid = pRegion.Id;
  91. var regionTreeList = await _sysRegionRep.AsQueryable().ToChildListAsync(u => u.Pid, input.Id, true);
  92. var childIdList = regionTreeList.Select(u => u.Id).ToList();
  93. if (childIdList.Contains(input.Pid)) throw Oops.Oh(ErrorCodeEnum.R2004);
  94. }
  95. if (input.Id == input.Pid) throw Oops.Oh(ErrorCodeEnum.R2001);
  96. var isExist = await _sysRegionRep.IsAnyAsync(u => (u.Name == input.Name && u.Code == input.Code) && u.Id != sysRegion.Id);
  97. if (isExist) throw Oops.Oh(ErrorCodeEnum.R2002);
  98. //// 父Id不能为自己的子节点
  99. //var regionTreeList = await _sysRegionRep.AsQueryable().ToChildListAsync(u => u.Pid, input.Id, true);
  100. //var childIdList = regionTreeList.Select(u => u.Id).ToList();
  101. //if (childIdList.Contains(input.Pid))
  102. // throw Oops.Oh(ErrorCodeEnum.R2001);
  103. await _sysRegionRep.AsUpdateable(input.Adapt<SysRegion>()).IgnoreColumns(true).ExecuteCommandAsync();
  104. }
  105. /// <summary>
  106. /// 删除行政区域 🔖
  107. /// </summary>
  108. /// <param name="input"></param>
  109. /// <returns></returns>
  110. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  111. [DisplayName("删除行政区域")]
  112. public async Task DeleteRegion(DeleteRegionInput input)
  113. {
  114. var regionTreeList = await _sysRegionRep.AsQueryable().ToChildListAsync(u => u.Pid, input.Id, true);
  115. var regionIdList = regionTreeList.Select(u => u.Id).ToList();
  116. await _sysRegionRep.DeleteAsync(u => regionIdList.Contains(u.Id));
  117. }
  118. /// <summary>
  119. /// 同步行政区域 🔖
  120. /// </summary>
  121. /// <returns></returns>
  122. [DisplayName("同步行政区域")]
  123. public async Task Sync()
  124. {
  125. var syncLevel = await _sysConfigService.GetConfigValue<int>(ConfigConst.SysRegionSyncLevel);
  126. if (syncLevel is < 1 or > 5) syncLevel = 3;//默认区县级
  127. await _sysRegionRep.DeleteAsync(u => u.Id > 0);
  128. await SyncByMap(syncLevel);
  129. // var context = BrowsingContext.New(AngleSharp.Configuration.Default.WithDefaultLoader());
  130. // var dom = await context.OpenAsync(_url);
  131. //
  132. // // 省级列表
  133. // var itemList = dom.QuerySelectorAll("table.provincetable tr.provincetr td a");
  134. // if (itemList.Length == 0) throw Oops.Oh(ErrorCodeEnum.R2005);
  135. //
  136. // await _sysRegionRep.DeleteAsync(u => u.Id > 0);
  137. //
  138. // foreach (var element in itemList)
  139. // {
  140. // var item = (IHtmlAnchorElement)element;
  141. // var list = new List<SysRegion>();
  142. //
  143. // var region = new SysRegion
  144. // {
  145. // Id = YitIdHelper.NextId(),
  146. // Pid = 0,
  147. // Name = item.TextContent,
  148. // Remark = item.Href,
  149. // Level = 1,
  150. // };
  151. // list.Add(region);
  152. //
  153. // // 市级
  154. // if (!string.IsNullOrEmpty(item.Href))
  155. // {
  156. // var dom1 = await context.OpenAsync(item.Href);
  157. // var itemList1 = dom1.QuerySelectorAll("table.citytable tr.citytr td a");
  158. // for (var i1 = 0; i1 < itemList1.Length; i1 += 2)
  159. // {
  160. // var item1 = (IHtmlAnchorElement)itemList1[i1 + 1];
  161. // var region1 = new SysRegion
  162. // {
  163. // Id = YitIdHelper.NextId(),
  164. // Pid = region.Id,
  165. // Name = item1.TextContent,
  166. // Code = itemList1[i1].TextContent,
  167. // Remark = item1.Href,
  168. // Level = 2,
  169. // };
  170. //
  171. // // 若URL中查询的一级行政区域缺少Code则通过二级区域填充
  172. // if (list.Count == 1 && !string.IsNullOrEmpty(region1.Code))
  173. // region.Code = region1.Code.Substring(0, 2).PadRight(region1.Code.Length, '0');
  174. //
  175. // // 同步层级为“1-省级”退出
  176. // if (syncLevel < 2) break;
  177. //
  178. // list.Add(region1);
  179. //
  180. // // 区县级
  181. // if (string.IsNullOrEmpty(item1.Href) || syncLevel <= 2) continue;
  182. //
  183. // var dom2 = await context.OpenAsync(item1.Href);
  184. // var itemList2 = dom2.QuerySelectorAll("table.countytable tr.countytr td a");
  185. // for (var i2 = 0; i2 < itemList2.Length; i2 += 2)
  186. // {
  187. // var item2 = (IHtmlAnchorElement)itemList2[i2 + 1];
  188. // var region2 = new SysRegion
  189. // {
  190. // Id = YitIdHelper.NextId(),
  191. // Pid = region1.Id,
  192. // Name = item2.TextContent,
  193. // Code = itemList2[i2].TextContent,
  194. // Remark = item2.Href,
  195. // Level = 3,
  196. // };
  197. // list.Add(region2);
  198. //
  199. // // 街道级
  200. // if (string.IsNullOrEmpty(item2.Href) || syncLevel <= 3) continue;
  201. //
  202. // var dom3 = await context.OpenAsync(item2.Href);
  203. // var itemList3 = dom3.QuerySelectorAll("table.towntable tr.towntr td a");
  204. // for (var i3 = 0; i3 < itemList3.Length; i3 += 2)
  205. // {
  206. // var item3 = (IHtmlAnchorElement)itemList3[i3 + 1];
  207. // var region3 = new SysRegion
  208. // {
  209. // Id = YitIdHelper.NextId(),
  210. // Pid = region2.Id,
  211. // Name = item3.TextContent,
  212. // Code = itemList3[i3].TextContent,
  213. // Remark = item3.Href,
  214. // Level = 4,
  215. // };
  216. // list.Add(region3);
  217. //
  218. // // 村级
  219. // if (string.IsNullOrEmpty(item3.Href) || syncLevel <= 4) continue;
  220. //
  221. // var dom4 = await context.OpenAsync(item3.Href);
  222. // var itemList4 = dom4.QuerySelectorAll("table.villagetable tr.villagetr td");
  223. // for (var i4 = 0; i4 < itemList4.Length; i4 += 3)
  224. // {
  225. // list.Add(new SysRegion
  226. // {
  227. // Id = YitIdHelper.NextId(),
  228. // Pid = region3.Id,
  229. // Name = itemList4[i4 + 2].TextContent,
  230. // Code = itemList4[i4].TextContent,
  231. // CityCode = itemList4[i4 + 1].TextContent,
  232. // Level = 5,
  233. // });
  234. // }
  235. // }
  236. // }
  237. // }
  238. // }
  239. //
  240. // //按省份同步快速写入提升同步效率,全部一次性写入容易出现从统计局获取数据失败
  241. // await _sysRegionRep.Context.Fastest<SysRegion>().BulkCopyAsync(list);
  242. // }
  243. }
  244. /// <summary>
  245. /// 从统计局地图页面同步
  246. /// </summary>
  247. /// <param name="syncLevel"></param>
  248. private async Task SyncByMap(int syncLevel)
  249. {
  250. var client = new HttpClient();
  251. client.DefaultRequestHeaders.Add("Referer", "http://xzqh.mca.gov.cn/map");
  252. var html = await client.GetStringAsync("http://xzqh.mca.gov.cn/map");
  253. var municipalityList = new List<string> { "北京", "天津", "上海", "重庆" };
  254. var provList = Regex.Match(html, @"(?<=var json = )(\[\{.*?\}\])(?=;)").Value.ToJsonEntity<List<Dictionary<string, string>>>();
  255. foreach (var dict1 in provList)
  256. {
  257. var list = new List<SysRegion>();
  258. var provName = dict1.GetValueOrDefault("shengji");
  259. var province = new SysRegion
  260. {
  261. Id = YitIdHelper.NextId(),
  262. Name = Regex.Replace(provName, "[((].*?[))]", ""),
  263. Code = dict1.GetValueOrDefault("quHuaDaiMa"),
  264. CityCode = dict1.GetValueOrDefault("quhao"),
  265. Level = 1,
  266. Pid = 0,
  267. };
  268. if (municipalityList.Any(m => province.Name.StartsWith(m))) province.Name += "(省)";
  269. list.Add(province);
  270. if (syncLevel <= 1) continue;
  271. var prefList = await GetSelectList(provName);
  272. foreach (var dict2 in prefList)
  273. {
  274. var prefName = dict2.GetValueOrDefault("diji");
  275. var city = new SysRegion
  276. {
  277. Id = YitIdHelper.NextId(),
  278. Code = dict2.GetValueOrDefault("quHuaDaiMa"),
  279. CityCode = dict2.GetValueOrDefault("quhao"),
  280. Pid = province.Id,
  281. Name = prefName,
  282. Level = 2
  283. };
  284. if (municipalityList.Any(m => city.Name.StartsWith(m))) city.Name += "(地)";
  285. list.Add(city);
  286. if (syncLevel <= 2) continue;
  287. var countyList = await GetSelectList(provName, prefName);
  288. foreach (var dict3 in countyList)
  289. {
  290. var countyName = dict3.GetValueOrDefault("xianji");
  291. var county = new SysRegion
  292. {
  293. Id = YitIdHelper.NextId(),
  294. Code = dict3.GetValueOrDefault("quHuaDaiMa"),
  295. CityCode = dict3.GetValueOrDefault("quhao"),
  296. Name = countyName,
  297. Pid = city.Id,
  298. Level = 3
  299. };
  300. list.Add(county);
  301. }
  302. }
  303. //按省份同步快速写入提升同步效率,全部一次性写入容易出现从统计局获取数据失败
  304. await _sysRegionRep.Context.Fastest<SysRegion>().BulkCopyAsync(list);
  305. }
  306. // 获取选择数据
  307. async Task<List<Dictionary<string, string>>> GetSelectList(string prov, string prefecture = null)
  308. {
  309. var data = "";
  310. if (!string.IsNullOrWhiteSpace(prov)) data += $"shengji={prov}";
  311. if (!string.IsNullOrWhiteSpace(prefecture)) data += $"&diji={prefecture}";
  312. var json = await client.PostFormAsync("http://xzqh.mca.gov.cn/selectJson", data);
  313. return json.ToJsonEntity<List<Dictionary<string, string>>>();
  314. }
  315. }
  316. }