package cn.com.countrygarden.bi.main.service.wcx;

import cn.com.countrygarden.bi.main.configurer.WxAccessToken;
import cn.com.countrygarden.bi.main.util.HttpRequest;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

//import org.apache.commons.lang3.RandomStringUtils;

/**
 * 微信服务
 */
@Service
public class WcxService {


	@Autowired
	private WxAccessToken wxAccessToken;
	/*@Autowired
	private RedisUtil redisUtil;*/
	public static Map<String,String> thirdSession = new HashMap<>();



	//获取AccessToken
	public Map<String,Object> getWxAccessToken(){
		StringBuffer sb = new StringBuffer();
		sb.append("appid=").append(wxAccessToken.getAppId());
		sb.append("&secret=").append(wxAccessToken.getSecret());
		sb.append("&grant_type=").append(wxAccessToken.getGrantType());
		String res = HttpRequest.sendGet(wxAccessToken.getTokenUrl(), sb.toString());
		if(res == null || res.equals("")){
			return null;
		}
		return JSON.parseObject(res, Map.class);
	}

	public String postUr(String urlSr,String beginDate,String endDate) throws IOException {
		String serverURL = urlSr;
		StringBuffer sbf = new StringBuffer();
		String strRead = null;
		URL url = new URL(serverURL);
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		connection.setRequestMethod("POST");//请求post方式
		connection.setDoInput(true);
		connection.setDoOutput(true);
		//header内的的参数在这里set。||connection.setRequestProperty("健, "值");
		connection.setRequestProperty("Content-Type", "application/json");
		//connection.setRequestProperty("Authorization", "Bearer 59e0-9fcc-c3faea0e2a6c");
		connection.connect();
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
		//body参数在这里put到JSONObject中
		JSONObject parm = new JSONObject();
		parm.put("begin_date", beginDate);
		parm.put("end_date", endDate);
		writer.write(parm.toString());
		writer.flush();
		InputStream is = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		while ((strRead = reader.readLine()) != null) {
			sbf.append(strRead);
			//sbf.append("\r\n");
		}
		reader.close();
		connection.disconnect();
		String results = sbf.toString();
		return results;
	}


}
