package tech.glinfo.enbao.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeatherUtils {

    private final static Logger logger = LoggerFactory.getLogger(WeatherUtils.class);


    public static final String WEATHER_URL = "https://restapi.amap.com/v3/weather/weatherInfo?city=%s&key=0ce9568174013319b580fc40754af333";

    public static String getWeatherData(String code) {
        String datas = HttpUtil.doGet(String.format(WEATHER_URL, code));
        logger.info("当前天气：{}， 查询结果：{}", code, datas);
        String rtn = null;
        if(datas != null) {
            StringBuffer sb = new StringBuffer("当前天气：");
            JSONObject jsonObject = JSONObject.parseObject(datas);
            String status = jsonObject.getString("status");
//            System.out.println(status);
            if("1".equals(status)) {
                JSONArray lives = jsonObject.getJSONArray("lives");
                JSONObject o = lives.getJSONObject(0);
                sb.append(o.getString("weather"));
                sb.append("，温度：" + o.getString("temperature") + "度");
                sb.append("，风向：" + o.getString("winddirection"));
                sb.append("，相对湿度：" + o.getString("humidity")).append("。");
                rtn = sb.toString();
            }
        }

        return rtn;
    }

    public static void main(String[] args) {
        System.out.println(getWeatherData("440112"));
    }
}
