package tencent_map

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
	"net/http"
	"sort"
	"strings"
)

const (
	signKey                = "sig"
	BaseUrl                = `https://apis.map.qq.com`     // 基础访问链接
	TencentCoordinateApi   = "/ws/coord/v1/translate"      // 坐标转换API
	TencentCyclingPlanning = "/ws/direction/v1/ebicycling" // 电动骑行车规划API
	TencentWalkingPlanning = "/ws/direction/v1/walking"    // 步行规划API
	TencentGeoAddress2Code = "/ws/geocoder/v1"             // 地址解析,地址逆转坐标 	// https://lbs.qq.com/service/webService/webServiceGuide/address/Geocoder
	TencentCoder2Address   = "/ws/geocoder/v1"             // 地址逆解析,坐标转地址 	// https://lbs.qq.com/service/webService/webServiceGuide/address/Gcoder
	TencentGetDistrictList = "/ws/district/v1/list"        // 本接口用于获取全部省市区三级行政区划列表。
	TencentGetChildrenList = "/ws/district/v1/getchildren" // 根据父级code获取行政区划

	// 坐标转换类型(输入类型)
	CoordinateChangeTypeGPS     = 1 // GPS坐标
	CoordinateChangeTypeSoGou   = 2 // 搜狗坐标
	CoordinateChangeTypeBaidu   = 3 // 百度坐标
	CoordinateChangeTypeMapbar  = 4 // mapbar
	CoordinateChangeTypeGaoDe   = 5 // [默认]腾讯、google、高德坐标
	CoordinateChangeTypeSoGouMt = 6 // 搜狗墨脱

	DistrictLevelCountry  = 0 // 国家
	DistrictLevelProvince = 1 // 省
	DistrictLevelCity     = 2 // 市
	DistrictLevelDistrict = 3 // 县
	DistrictLevelStreet   = 4 // 街道

	MaxConvertCount = 40
)

type API struct {
	platformapi.APICookie

	client *http.Client
	config *platformapi.APIConfig
	key    string
	sk     string
}

func (a *API) SetKey(key string) {
	a.key = key
}
func (a *API) GetKey() string {
	return a.key
}

func (a *API) SetSK(sk string) {
	a.sk = sk
}
func (a *API) GetSK() string {
	return a.sk
}

func New(key, sk string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	return &API{
		key:    key,
		sk:     sk,
		client: &http.Client{Timeout: curConfig.ClientTimeout},
		config: &curConfig,
	}
}

func (a *API) signParams(params map[string]interface{}, url string) string {
	if params["key"] == nil || params["key"].(string) == "" {
		params["key"] = a.GetKey()
	}
	params2 := utils.Map2URLValues(params)

	keys := make([]string, 0)
	for k := range params2 {
		if k != signKey {
			keys = append(keys, k)
		}
	}
	sort.Strings(keys)
	finalStr := ""
	for index, key := range keys {
		valStr := strings.Join(params2[key], "")
		if valStr != "" {
			finalStr += key + "=" + valStr
			if index+1 != len(keys) {
				finalStr += "&"
			}
		}
	}

	sign := url + "?" + finalStr + a.GetSK()
	return fmt.Sprintf("%x", md5.Sum([]byte(sign)))
}

func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	if bizParams["key"] == nil || bizParams["key"].(string) == "" {
		bizParams["key"] = a.GetKey()
	}
	// 序列化
	data, err := json.Marshal(bizParams)
	if err != nil {
		return nil, err
	}

	// 发送请求
	sendUrl := func() *http.Request {
		var request *http.Request
		if http.MethodPost == method {
			request, _ = http.NewRequest(http.MethodPost, utils.GenerateGetURL(baseUrl, actionApi, nil), strings.NewReader(string(data)))
		} else {
			request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
		}
		request.Header.Set("Content-Type", "application/json")
		return request
	}

	// 数据解析
	dataMarshal := 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 err != nil {
			return "", err
		}
		if utils.MustInterface2Int64(jsonResult1["status"]) != 0 {
			errLevel = platformapi.ErrLevelGeneralFail
			err = utils.NewErrorCode(jsonResult1["message"].(string), utils.Int64ToStr(utils.MustInterface2Int64(jsonResult1["status"])))
		}
		retVal = jsonResult1
		return errLevel, err
	}

	err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
	return retVal, err
}
