package com.qunzhixinxi.hnqz.admin.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序获取openid
 *
 * @author Mr.Lin
 */
public class GetOpenIDUtil {

	// cos pro 环境
	public static final String CSO_PRO_APPID = "wxd03398e1bff2b241";
	public static final String CSO_PRO_APPSECRET = "f745fa594d51534845e8412433951a20";

	// cos demo 环境
	public static final String CSO_DEMO_APPID = "wx956bb32e73073426";
	public static final String CSO_DEMO_APPSECRET = "cb722986c23cc352b7f87ff2dae4cc11";

	public static Map<String, Object> oauth2GetOpenid(String code, String env) {
		String appid;
		String appsecret;
		if ("cso_demo".equals(env)) {
			appsecret = CSO_DEMO_APPSECRET;
			appid = CSO_DEMO_APPID;
		} else if ( "cso_prod".equals(env)) {
			appsecret = CSO_PRO_APPSECRET;
			appid = CSO_PRO_APPID;
		} else {
			appsecret = CSO_PRO_APPSECRET;
			appid = CSO_PRO_APPID;
		}
		final String URL = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appid, appsecret, code);

		return oauth2GetOpenid(URL);

	}


	// 网页授权接口
//    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";//
//    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
	private static Map<String, Object> oauth2GetOpenid(String requestUrl) {
		HttpClient client = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			client = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(requestUrl);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String response = client.execute(httpget, responseHandler);
			JSONObject OpenidJSONO = JSONObject.parseObject(response);
			String openid = String.valueOf(OpenidJSONO.get("openid"));
			String session_key = String.valueOf(OpenidJSONO.get("session_key"));
			String unionid = String.valueOf(OpenidJSONO.get("unionid"));
			String errcode = String.valueOf(OpenidJSONO.get("errcode"));
			String errmsg = String.valueOf(OpenidJSONO.get("errmsg"));

			result.put("openid", openid);
			result.put("sessionKey", session_key);
			result.put("unionid", unionid);
			result.put("errcode", errcode);
			result.put("errmsg", errmsg);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			client.getConnectionManager().shutdown();
		}
		return result;
	}
}
