package autonavi

import (
	"fmt"
	"net/http"
	"strings"

	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

func (a *API) AccessStorePage(fullURL string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(fullURL, "", bizParams), nil)
			request.Header.Set("Referer", "https://lbs.amap.com/")
			// a.FillRequestCookies(request)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了！")
			}
			if err == nil {
				if jsonResult1["info"].(string) != "OK" {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["info"].(string), jsonResult1["infocode"].(string))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) GetCoordinateFromAddressByPage(address string, cityCode int) (lng, lat float64, err error) {
	result, err := a.AccessStorePage("https://restapi.amap.com/v3/place/text", map[string]interface{}{
		"s":   "rsv3",
		"key": "49ae7e4552909cf33faba70443ad775b",
		//"key":        "e07ffdf58c8e8672037bef0d6cae7d4a",
		"page":       1,
		"offset":     10,
		"city":       cityCode,
		"language":   "zh_cn",
		"platform":   "JS",
		"logversion": 2.0,
		"sdkversion": 1.3,
		"appname":    "https://lbs.amap.com/console/show/picker",
		"csid":       "7A90908C-BBA6-49FE-895E-DB70600E14F8",
		"keywords":   address,
		"children":   "",
	})
	if err == nil {
		if len(result["pois"].([]interface{})) > 0 {
			str := result["pois"].([]interface{})[0].(map[string]interface{})["location"].(string)
			strs := strings.Split(str, ",")
			if len(strs) > 0 {
				return utils.Str2Float64(strs[0]), utils.Str2Float64(strs[1]), err
			}
		}
	}
	return lng, lat, err
}

type GetCoordinateFromAddressByPageAllResult struct {
	Lng      float64 `json:"lng"`
	Lat      float64 `json:"lat"`
	AdName   string  `json:"adName"`
	CityName string  `json:"cityName"`
}

func (a *API) GetCoordinateFromAddressByPageAll(address string, cityCode int) (getCoordinateFromAddressByPageAllResult *GetCoordinateFromAddressByPageAllResult, err error) {
	getCoordinateFromAddressByPageAllResult = &GetCoordinateFromAddressByPageAllResult{}
	result, err := a.AccessStorePage("https://restapi.amap.com/v3/place/text", map[string]interface{}{
		"s":   "rsv3",
		"key": "49ae7e4552909cf33faba70443ad775b",
		//"key":        "e07ffdf58c8e8672037bef0d6cae7d4a",
		"page":       1,
		"offset":     10,
		"city":       cityCode,
		"language":   "zh_cn",
		"platform":   "JS",
		"logversion": 2.0,
		"sdkversion": 1.3,
		"appname":    "https://lbs.amap.com/console/show/picker",
		"csid":       "7A90908C-BBA6-49FE-895E-DB70600E14F8",
		"keywords":   address,
		"children":   "",
	})
	if err == nil {
		if len(result["pois"].([]interface{})) > 0 {
			str := result["pois"].([]interface{})[0].(map[string]interface{})["location"].(string)
			strs := strings.Split(str, ",")
			if len(strs) > 0 {
				getCoordinateFromAddressByPageAllResult.Lng = utils.Str2Float64(strs[0])
				getCoordinateFromAddressByPageAllResult.Lat = utils.Str2Float64(strs[1])
			}
			for _, v := range result["pois"].([]interface{}) {
				if getCoordinateFromAddressByPageAllResult.CityName == "" {
					if str, ok := v.(map[string]interface{})["cityname"].(string); ok {
						getCoordinateFromAddressByPageAllResult.CityName = str
					}
				}
				if getCoordinateFromAddressByPageAllResult.AdName == "" {
					if str, ok := v.(map[string]interface{})["adname"].(string); ok {
						getCoordinateFromAddressByPageAllResult.AdName = str
					}
				}
				if getCoordinateFromAddressByPageAllResult.CityName != "" && getCoordinateFromAddressByPageAllResult.AdName != "" {
					break
				}
			}
		}

	}
	return getCoordinateFromAddressByPageAllResult, err
}
