package fr.zng.xxzx.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import fr.zng.xxzx.common.dao.CityWeatherDao;
import fr.zng.xxzx.common.dao.WeatherDao;
import fr.zng.xxzx.common.dao.impl.CityWeatherDaoImpl;
import fr.zng.xxzx.common.dao.impl.WeatherDaoImpl;
import fr.zng.xxzx.common.entity.WeatherEntity;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HttpClient {

	public static final String URLP = "https://free-api.heweather.net/s6/weather/forecast?location=";

	public static final String URLA = "&key=6a24ec9799ac4be18c3d5ef608343df6";


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CityWeatherDao cw = new CityWeatherDaoImpl();
		final List<String> city = cw.getCityWeather();
		TimerTask task = new TimerTask() {
			public void run() {
				doUpdateWeather(city);
			}
		};
		Timer t = new Timer();
		long delay = 1000;
		long intevalTime = 82800;
		t.scheduleAtFixedRate(task, delay, intevalTime);

	}

	/**
	 * 通过地市的代号获取天气
	 */
	public static void doUpdateWeather(List<String> city) {
		try {
			for (String cy : city) {
				Thread.sleep(1000);
				// 根据代号获取天气
				String url = URLP + cy + URLA;
				// 天气请求
				String tqyb = doGet(url);
				System.out.println(tqyb);
				if (tqyb == null || tqyb == "") {
					continue;

				} else {
					//
					JSONObject job = JSONObject.fromObject(tqyb);
					JSONArray jarr = job.getJSONArray("HeWeather6");
					// 能够获取到数据
					if (jarr != null && jarr.size() > 0) {
						JSONObject jo = jarr.getJSONObject(0);
						// 获取到天气
						if (jo != null && "ok".equals(jo.getString("status"))) {

							JSONArray cast = jo.getJSONArray("daily_forecast");

							List<DailyBean> dailyList = getDailyWeather(cy,cast);
						}

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 解析每日
	 * 
	 * @param cast
	 *            json数组I安去
	 * @return
	 */
	public static List<DailyBean> getDailyWeather(String city,JSONArray cast) {
		if (cast != null && cast.size() > 0) {
			List<DailyBean> list = new ArrayList<DailyBean>();
			WeatherEntity we = new WeatherEntity();
			WeatherDao wd = new WeatherDaoImpl();
			we.setCityno(city);
			//第一天
			we.setDate1(cast.getJSONObject(0).getString("date"));
			we.setTmpMax1(cast.getJSONObject(0).getString("tmp_max"));
			we.setTmpMin1(cast.getJSONObject(0).getString("tmp_min"));
			we.setConCodeD1(cast.getJSONObject(0).getString("cond_code_d"));
			we.setConCodeN1(cast.getJSONObject(0).getString("cond_code_n"));
			we.setConTxtD1(cast.getJSONObject(0).getString("cond_txt_d"));
			we.setConTxtN1(cast.getJSONObject(0).getString("cond_txt_n"));
			//第二天
			we.setDate2(cast.getJSONObject(1).getString("date"));
			we.setTmpMax2(cast.getJSONObject(1).getString("tmp_max"));
			we.setTmpMin2(cast.getJSONObject(1).getString("tmp_min"));
			we.setConCodeD2(cast.getJSONObject(1).getString("cond_code_d"));
			we.setConCodeN2(cast.getJSONObject(1).getString("cond_code_n"));
			we.setConTxtD2(cast.getJSONObject(1).getString("cond_txt_d"));
			we.setConTxtN2(cast.getJSONObject(1).getString("cond_txt_n"));
			//第三天
			we.setDate3(cast.getJSONObject(2).getString("date"));
			we.setTmpMax3(cast.getJSONObject(2).getString("tmp_max"));
			we.setTmpMin3(cast.getJSONObject(2).getString("tmp_min"));
			we.setConCodeD3(cast.getJSONObject(2).getString("cond_code_d"));
			we.setConCodeN3(cast.getJSONObject(2).getString("cond_code_n"));
			we.setConTxtD3(cast.getJSONObject(2).getString("cond_txt_d"));
			we.setConTxtN3(cast.getJSONObject(2).getString("cond_txt_n"));
			wd.insert(we);
			/*for (int i = 0; i < cast.size(); i++) {
				bean = new DailyBean();
				JSONObject job = cast.getJSONObject(i);
				if (job != null) {
					// 日期
					bean.setDate(job.getString("date"));
					// 最高温度
					bean.setTmpMax(job.getString("tmp_max"));
					// 最低温度
					bean.setTmpMin(job.getString("tmp_min"));
					// 白天天气状况代码
					bean.setCondCoded(job.getString("cond_code_d"));
					// 夜间天气状况代码
					bean.setCondCoden(job.getString("cond_code_n"));
					// 白天天气状况描述
					bean.setCondTxtd(job.getString("cond_txt_d"));
					// 晚间天气状况描述
					bean.setCondTxtn(job.getString("cond_txt_n"));
					list.add(bean);
				}
			}*/
			return list;
		}
		return null;
	}

	/**
	 * Get请求
	 * 
	 * @param httpurl
	 *            请求url
	 * @return 数据json
	 */
	public static String doGet(String httpurl) {
		HttpURLConnection connection = null;
		InputStream is = null;
		BufferedReader br = null;
		String result = null;// 返回结果字符串
		try {
			// 创建远程url连接对象
			URL url = new URL(httpurl);
			// 通过远程url连接对象打开一个连接，强转成httpURLConnection类
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接方式：get
			connection.setRequestMethod("GET");
			// 设置连接主机服务器的超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取远程返回的数据时间：60000毫秒
			connection.setReadTimeout(60000);
			// 发送请求
			connection.connect();
			// 通过connection连接，获取输入流
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				// 封装输入流is，并指定字符集
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				// 存放数据
				StringBuffer sbf = new StringBuffer();
				String temp = null;
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			connection.disconnect();// 关闭远程连接
		}

		return result;
	}

	/**
	 * Post请求
	 * 
	 * @param httpurl
	 *            请求url
	 * @return 数据json
	 */
	public static String doPost(String httpUrl, String param) {

		HttpURLConnection connection = null;
		InputStream is = null;
		OutputStream os = null;
		BufferedReader br = null;
		String result = null;
		try {
			URL url = new URL(httpUrl);
			// 通过远程url连接对象打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接请求方式
			connection.setRequestMethod("POST");
			// 设置连接主机服务器超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取主机服务器返回数据超时时间：60000毫秒
			connection.setReadTimeout(60000);

			// 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
			connection.setDoOutput(true);
			// 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
			connection.setDoInput(true);
			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			// 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
			connection.setRequestProperty("Authorization",
					"Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
			// 通过连接对象获取一个输出流
			os = connection.getOutputStream();
			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
			os.write(param.getBytes());
			// 通过连接对象获取一个输入流，向远程读取
			if (connection.getResponseCode() == 200) {

				is = connection.getInputStream();
				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

				StringBuffer sbf = new StringBuffer();
				String temp = null;
				// 循环遍历一行一行读取数据
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 断开与远程地址url的连接
			connection.disconnect();
		}
		return result;
	}
}
