package com.ho.common.tools.util;

import com.ho.common.tools.entity.WeatherRespVo;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author kerwin
 *
 * 获取海外天气
 */
@Slf4j
public class AbroadWeatherUtils {

    static String apiKey = "6358b3081a5849f09ac90138252107";
    public static void main(String[] args) {
        String latitude = "40.714224";
        String longitude = "-73.961452";

        try {
            System.out.println(getWeatherRespVo(latitude, longitude));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static WeatherRespVo getWeatherRespVo(String lat, String lng) {
        String urlString = "http://api.weatherapi.com/v1/forecast.json?key="+apiKey+"&q=" + lat + "," + lng +"&days=1";
        URL url = null;
        StringBuilder response = new StringBuilder();
        try {
            url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return parseWeatherData(response.toString());
    }

    private static WeatherRespVo parseWeatherData(String jsonResponse) {
        WeatherRespVo weatherRespVo =new WeatherRespVo();
        JSONObject root = new JSONObject(jsonResponse);

        // 解析地区信息
        JSONObject location = root.getJSONObject("location");
        String area = location.getString("name");
        weatherRespVo.setCityzh(area);

        // 获取天气预报数据
        JSONObject forecast = root.getJSONObject("forecast");
        JSONArray forecastday = forecast.getJSONArray("forecastday");
        JSONObject day = forecastday.getJSONObject(0).getJSONObject("day");

        // 解析温度数据
        double maxTemp = day.getDouble("maxtemp_c");
        weatherRespVo.setMaxTemperature(new BigDecimal(String.valueOf(maxTemp)));
        double minTemp = day.getDouble("mintemp_c");
        weatherRespVo.setMinTemperature(new BigDecimal(String.valueOf(minTemp)));
        String condition = day.getJSONObject("condition").getString("text");
        weatherRespVo.setSkyCon(condition);
        int code = day.getJSONObject("condition").getInt("code");
        weatherRespVo.setCode(code);
        double maxWindKph = day.getDouble("maxwind_kph");
        // 获取风向（从最近的小时数据中获取）
        JSONArray hours = forecastday.getJSONObject(0).getJSONArray("hour");
        String windDirection = hours.getJSONObject(0).getString("wind_dir");
        // 组合风向风速信息
        String windInfo = windDirection + " " + maxWindKph + " km/h";
        weatherRespVo.setSpeedAndDirection(windInfo);
        weatherRespVo.setUpdateTime(System.currentTimeMillis());
        return weatherRespVo;
    }

}
