RegionHelper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using Dapper;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using Wicture.DbRESTFul.Infrastructure.Repository;
  8. namespace JiaZhiQuan.Common.Region
  9. {
  10. public class RegionHelper
  11. {
  12. private readonly IConnectionManager _connectionManager;
  13. private readonly ILogger _logger;
  14. public List<RegionModel> Regions { get; private set; }
  15. public Dictionary<string, string> CodeNameMap = new Dictionary<string, string>();
  16. /// <summary>
  17. /// 匹配省市区的正则对象
  18. /// </summary>
  19. public Regex AreaMatchRegex { get; private set; }
  20. public RegionHelper(IConnectionManager manager, ILoggerFactory loggerFactory)
  21. {
  22. _connectionManager = manager;
  23. _logger = loggerFactory.CreateLogger("DbRESTFul");
  24. try
  25. {
  26. Resolve();
  27. }
  28. catch (Exception ex)
  29. {
  30. _logger.LogError(ex, "Region 读取失败");
  31. }
  32. }
  33. public RegionHelper Resolve()
  34. {
  35. using (var conn = _connectionManager.GetConnection())
  36. {
  37. conn.Open();
  38. Init(SqlMapper.Query(conn, "select * from n_region where code<'700000' order by code asc"));
  39. }
  40. return this;
  41. }
  42. private void Init(IEnumerable<dynamic> regions)
  43. {
  44. var arr = new RegionModel[2];
  45. var root = new List<RegionModel>();
  46. foreach (var item in regions)
  47. {
  48. CodeNameMap[item.code] = item.name;
  49. var ritem = new RegionModel { Code = item.code, Name = item.name, Alias = item.alias, PY = item.py };
  50. if (arr[0] != null && arr[0].Code.StartsWith(ritem.Code.Substring(0, 2)))
  51. {
  52. if (arr[1] != null && arr[1].Code.StartsWith(ritem.Code.Substring(0, 4)) && arr[1].Code.EndsWith("00"))
  53. {
  54. arr[1].Children.Add(ritem);
  55. }
  56. else
  57. {
  58. arr[0].Children.Add(ritem);
  59. arr[1] = ritem;
  60. //if (ritem.Code.EndsWith("00"))
  61. //{
  62. // arr[0].Children.Add(ritem);
  63. // arr[1] = ritem;
  64. //}
  65. //else
  66. //{
  67. // arr[1] = new RegionModel { Code = arr[0].Code, Name = arr[0].Name, Alias = arr[0].Alias };
  68. // arr[0].Children.Add(arr[1]);
  69. //}
  70. }
  71. }
  72. else
  73. {
  74. root.Add(ritem);
  75. arr[0] = ritem;
  76. arr[1] = null;
  77. }
  78. }
  79. Regions = root;
  80. }
  81. }
  82. }