package com.wechat.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.wechat.dao.BaiDuTokenRedisDao;
import com.wechat.model.dto.BaiDuTokenDto;

import net.sf.json.JSONObject;

@Service
public class BaiDuTokenService {

	@Value("#{configProperties['baidu.grant.type']}")
	private String grantType;

	@Value("#{configProperties['baidu.client.id']}")
	private String clientId;

	@Value("#{configProperties['baidu.client.secret']}")
	private String clientSecret;

	@Value("#{configProperties['baidu.api.accesstoken.url']}")
	private String accesstoken;

	private static final Log log = LogFactory.getLog(WeiXinService.class);

	@Autowired
	private BaiDuTokenRedisDao baiDuTokenRedisDao;

	public BaiDuTokenDto getBaiDuAccessToken() {
		BaiDuTokenDto baiDuTokenDto = null;
		StringBuffer buffer=new StringBuffer(accesstoken);
		buffer.append("grant_type="+grantType);
		buffer.append("&client_id="+clientId);
		buffer.append("&client_secret="+clientSecret);
		baiDuTokenDto = baiDuTokenRedisDao.selectBaiDuToken("baiduAccessToken");
		if (baiDuTokenDto == null) {
			baiDuTokenDto = processRequest(buffer.toString());
			baiDuTokenRedisDao.insertBaiDuToken("baiduAccessToken", baiDuTokenDto); // acctoken存入redis
		} else {
			if (Long.parseLong(baiDuTokenDto.getExpires_in()) < System.currentTimeMillis()) {
				baiDuTokenDto = processRequest(buffer.toString());
				baiDuTokenRedisDao.updateBaiDuToken("baiduAccessToken", baiDuTokenDto);
			}
		}
		return baiDuTokenDto;
	}

	/**
	 * 请求处理
	 * 
	 * @param url
	 * @return 处理完毕返回的数据
	 */
	@SuppressWarnings("null")
	public BaiDuTokenDto processRequest(String url) {
		URL getUrl;
		BaiDuTokenDto baiDuTokenDto = null;
		BufferedReader reader = null;
		try {
			getUrl = new URL(url.toString());
			HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
			connection.setDoOutput(true);

			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
			String lines;
			StringBuilder buf = new StringBuilder();
			while ((lines = reader.readLine()) != null) {
				buf.append(lines);
			}
			JSONObject fromObject = JSONObject.fromObject(buf.toString());
			if (fromObject != null) {
				String accexxToken = fromObject.getString("access_token");
				long expires_in = Long.parseLong(fromObject.getString("expires_in")) * 1000;
				long currentTimeMillis = System.currentTimeMillis() + expires_in;
				 baiDuTokenDto = new BaiDuTokenDto();
				baiDuTokenDto.setAccess_token(accexxToken);
				baiDuTokenDto.setExpires_in(String.valueOf(currentTimeMillis));
			}
			reader.close();
			return baiDuTokenDto;
		} catch (Exception e) {
			log.error(e);
			return baiDuTokenDto;
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				log.error(e);
			}
		}
	}
}
