SysRegionService.cs 15 KB

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