geo.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package geo
  2. import (
  3. "reflect"
  4. "zhiyuan/models/geo"
  5. "zhiyuan/pkg/db"
  6. )
  7. type GeoType struct {
  8. Typ reflect.Type
  9. Code string
  10. Count int
  11. }
  12. var GEO_LIST = []GeoType{
  13. {
  14. Typ: db.Type(geo.Province{}),
  15. Code: "provinceCode",
  16. Count: 2,
  17. },
  18. {
  19. Typ: db.Type(geo.City{}),
  20. Code: "cityCode",
  21. Count: 4,
  22. },
  23. {
  24. Typ: db.Type(geo.Area{}),
  25. Code: "areaCode",
  26. Count: 6,
  27. },
  28. {
  29. Typ: db.Type(geo.Street{}),
  30. Code: "streetCode",
  31. Count: 9,
  32. },
  33. {
  34. Typ: db.Type(geo.Village{}),
  35. Code: "villageCode",
  36. Count: 12,
  37. },
  38. }
  39. func codeN(code string) int {
  40. for i, v := range GEO_LIST {
  41. if len(code) == v.Count {
  42. return i
  43. }
  44. }
  45. return -1
  46. }
  47. func Lower(code string) ([]map[string]interface{}, error) {
  48. n := codeN(code)
  49. var typ reflect.Type
  50. var search map[string]interface{}
  51. if n < 0 {
  52. typ = GEO_LIST[0].Typ
  53. } else if n >= 4 {
  54. return []map[string]interface{}{}, nil
  55. } else {
  56. typ = GEO_LIST[n+1].Typ
  57. search = map[string]interface{}{
  58. GEO_LIST[n].Code: code,
  59. }
  60. }
  61. s := db.ModelQuery(typ, search, false)
  62. query, params := s.Query()
  63. list, err := db.QueryMap(query, params, reflect.New(typ).Interface().(db.Model).DB())
  64. if err != nil {
  65. return []map[string]interface{}{}, err
  66. }
  67. if list == nil {
  68. list = make([]map[string]interface{}, 0)
  69. }
  70. return list, nil
  71. }
  72. func Code(code string) []map[string]interface{} {
  73. n := codeN(code)
  74. list := make([]map[string]interface{}, 0)
  75. if n < 0 {
  76. return list
  77. }
  78. for ; n >= 0; n-- {
  79. one, err := db.GetOneModelMap(GEO_LIST[n].Typ, map[string]interface{}{
  80. "code": code,
  81. }, nil)
  82. if err != nil || one == nil {
  83. return list
  84. }
  85. list = append([]map[string]interface{}{one}, list...)
  86. if n != 0 {
  87. code = db.ToString(one[GEO_LIST[n-1].Code])
  88. }
  89. }
  90. return list
  91. }