package amap

import (
	"cold-delivery/conf"
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
	"strconv"
)

type Address struct {
	Status    string    `json:"status"`
	Regeocode Regeocode `json:"regeocode"`
	Info      string    `json:"info"`
	Infocode  string    `json:"infocode"`
}

type Regeocode struct {
	AddressComponent AddressComponent `json:"addressComponent"`
	FormattedAddress string           `json:"formatted_address"`
}

type AddressComponent struct {
	City         string       `json:"city"`
	Province     string       `json:"province"`
	Adcode       string       `json:"adcode"`
	District     string       `json:"district"`
	Township     string       `json:"township"`
	StreetNumber StreetNumber `json:"streetNumber"`
	Country      string       `json:"country"`
	Citycode     string       `json:"citycode"`
}

type StreetNumber struct {
	Number    string `json:"number"`
	Location  string `json:"location"`
	Direction string `json:"direction"`
	Distance  string `json:"distance"`
	Street    string `json:"street"`
}

// 高德-逆地址解析
func GeocodeRegeo(lng, lat string) (address Address) {
	if len(lng) == 0 || len(lat) == 0 {
		return
	}

	lngFloat64, err := strconv.ParseFloat(lng, 64)
	if err != nil {
		return
	}
	lngStr := fmt.Sprintf("%.6f", lngFloat64)

	latFloat64, err := strconv.ParseFloat(lat, 64)
	if err != nil {
		return
	}
	latStr := fmt.Sprintf("%.6f", latFloat64)

	client := resty.New()

	resp, err := client.R().SetQueryParams(map[string]string{
		"key":      conf.ExtConfig.Amap.Key,
		"location": lngStr + "," + latStr,
	}).Get("https://restapi.amap.com/v3/geocode/regeo")

	if err != nil {
		return
	}
	err = json.Unmarshal(resp.Body(), &address)
	if err != nil {
		return
	}
	return address
}
