SysRegionService.cs 16 KB

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