package com.toss.service;

import com.toss.model.Email;
import com.toss.util.NetUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取天气
 * Created by VirtualPier on 2016/6/21.
 */
public class WeatherService {

    public static String excute(String cityName){
        String url="http://api.map.baidu.com/telematics/v3/weather?location=" + cityName
                + "&output=json&ak=URUeRRShDwbtooHKPhTxKMEWwfknnWIC";
        return NetUtil.get(url);//通过工具类获取返回数据
    }

    public static String getWeatherByCity(String city){
        if(StringUtils.isEmpty(city.trim())) return "请输入所在城市";
        return excute(city);
    }

    public static String pushWeatherInEmail(){
        JSONObject json = JSONObject.fromObject(getWeatherByCity("惠州"));
        StringBuffer message = new StringBuffer();
        if("success".equals(json.getString("status"))){
            String date = json.getString("date"); //返回时间
            JSONArray arr = json.getJSONArray("results");
            for (Object obj: arr) {
                json=JSONObject.fromObject(obj.toString());
                message.append("城市：" + json.getString("currentCity") + "\n");//获取返回城市
                message.append("PM 2.5 空气质量：" + json.getString("pm25") + "\n");//获取PM2.5
                JSONArray weather = json.getJSONArray("weather_data");
                JSONArray index = json.getJSONArray("index");

                JSONObject jsonObj ;
                for (Object wea: weather) {
                    jsonObj = JSONObject.fromObject(wea);
                    message.append("天气预报时间：" + jsonObj.getString("date") + "\n");
                    message.append("天气状况：" + jsonObj.getString("weather") + "\n");
                    message.append("风力：" + jsonObj.getString("wind") + "\n");
                    message.append("温度：" + jsonObj.getString("temperature") + "\n");
                    message.append("\n");
                }
                for (Object ind: index) {
                    jsonObj = JSONObject.fromObject(ind);
                    message.append(jsonObj.getString("title") + "\n");
                    message.append(jsonObj.getString("zs") + "\n");
                    message.append(jsonObj.getString("tipt") + "\n");
                    message.append(jsonObj.getString("des") + "\n");
                    message.append("\n");
                }
            }
        }
        return message.toString();
    }

    public static void main(String[] args) {
        String json = getWeatherByCity("惠州");
        System.out.println(json);
        System.out.println(pushWeatherInEmail());
    }
}
