package com.gree.mall.manager.logic.common;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Service
public class LbsAmapLogic {

//    private static final String lbsWebKey = "b772f8b0ace6bc96c04ae8e48f241e36";
    private static final String lbsWebKey = "428a7111e02ea8367a3b34804eaa025b";


    /**
     * 根据地址反查经纬度
     * @Param 中文地址(最好详细)
     * @return lng,lat
     */
    public String getLocationByAddress(String address){
        //String lbsWebKey = "b772f8b0ace6bc96c04ae8e48f241e36";
        //String address = "广东省广州市天河区华景新城";
        String url = "https://restapi.amap.com/v3/geocode/geo?key="+lbsWebKey+"&address="+address;
        String s = HttpUtil.get(url);
        JSONObject jsonObject = new JSONObject(s);
        String status = jsonObject.getStr("status");
        if(!status.equals("1")){
            return null;
        }
        JSONArray geocodes = jsonObject.getJSONArray("geocodes");
        if(CollectionUtils.isEmpty(geocodes))
            return null;
        Map<String, Object> map = (Map<String, Object>) geocodes.get(0);
        String location = (String)map.get("location");
        log.info("根据地址【{}】反查经纬度【{}】",address,new JSONObject(map));
        return location;
    }



}
