package cn.pluss.platform.wechat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pluss.platform.constants.Constant;

public class Oauth2Util{
	 private static final Logger Log = LoggerFactory.getLogger( Oauth2Util.class);

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
	{
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try
		{
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());

			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr)
			{
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null)
			{
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
		}
		catch (ConnectException ce)
		{
			System.out.println("Weixin server connection timed out.");
		}
		catch (Exception e)
		{
			System.out.println("https request error:{}"+ e);
		}
		return jsonObject;
	}
	
	
	

	/**
	 * 1、获取Oauth2 acess_token
	 * 
	 * @param appId
	 * @param appSecret
	 * @param code
	 * @return
	 * @author cdw
	 */
//	public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code){
//		WeixinOauth2Token wot = null;
//		String requesturl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
//		requesturl = requesturl.replace("APPID", appId);
//		requesturl = requesturl.replace("SECRET", appSecret);
//		requesturl = requesturl.replace("CODE", code);
//		JSONObject jsonObject =httpRequest(requesturl, "GET", null);
//		if (jsonObject != null)	{
//			System.out.println("jsonObject++++++++++++++++++"+com.alibaba.fastjson.JSONObject.toJSONString(jsonObject));
//			try	{
//				wot = new WeixinOauth2Token();
//				wot.setAccessToken(jsonObject.getString("access_token"));
//				wot.setExpiresIn(jsonObject.getInteger("expires_in"));
//				wot.setRefreshToken(jsonObject.getString("refresh_token"));
//				wot.setOpenId(jsonObject.getString("openid"));
//				wot.setScope(jsonObject.getString("scope"));
//				if(jsonObject.containsKey("unionid")){
//					wot.setUnionId(jsonObject.getString("unionid"));
//				}
//			}catch (Exception e){
//				wot = null;
//				String errCode = jsonObject.getString("errcode");
//				String errMsg = jsonObject.getString("errmsg");
//				Log.error("获取网页信息的失败errcode:{" + errCode + "} errmsg{" + errMsg + "}");
//			}
//
//		}
//
//		return wot;
//	}

	/**
	 * 2、 刷新Oauth2 acess_token
	 * 
	 * @param appId
	 * @param refreshToken
	 * @return
	 * @author cdw
	 */
//	public static WeixinOauth2Token refreshOauth2AccessToken(String appId, String refreshToken){
//		WeixinOauth2Token wot = null;
//
//		String requestUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
//
//		requestUrl.replace("APPID", appId);
//		requestUrl.replace("REFRESH_TOKEN", refreshToken);
//
//		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
//		if (jsonObject != null)	{
//			try	{
//				wot = new WeixinOauth2Token();
//				wot.setAccessToken(jsonObject.getString("access_token"));
//				wot.setExpiresIn(jsonObject.getInteger("expires_in"));
//				wot.setRefreshToken(jsonObject.getString("refresh_token"));
//				wot.setOpenId(jsonObject.getString("openid"));
//				String scope=jsonObject.getString("scope");
//				System.out.println("----scope-----"+scope);
//				wot.setScope(scope);
//				//wot.setScope(jsonObject.getString("scope"));
//			}catch (Exception e){
//				wot = null;
//				String errCode = jsonObject.getString("errcode");
//				String errMsg = jsonObject.getString("errmsg");
//				Log.error("获取网页信息的失败errcode:{" + errCode + "} errmsg{" + errMsg + "}");
//			}
//		}
//
//		return wot;
//	}

	/**
	 * 查询用户信息
	 * @param accessToken
	 * @param openId
	 * @return
	 */
//	public static UserApp getUserInfo(String accessToken, String openId){
//		MerchantMenber uinfo = null;
//		String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//
//		Log.info("==Oauth2Util======查询用户信息==getUserInfo===requestUrl="+requestUrl);
//		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
//		requestUrl = requestUrl.replace("OPENID", openId);
//
//		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
//
//		if (jsonObject != null)	{
//			try{
//				uinfo = new MerchantMember();
////				uinfo.setCity(jsonObject.getString("city"));
////				uinfo.setCountry(jsonObject.getString("country"));
//				uinfo.setPic(jsonObject.getString("headimgurl"));
//				String nickName = jsonObject.getString("nickname");
//				//对微信用户昵称进行编码，解决昵称中有图片的问题
//				nickName = URLEncoder.encode(nickName, "utf-8");
//				uinfo.setNickName(nickName);
//				uinfo.setOpenId(jsonObject.getString("openid"));
//				Date createDt = new Date(jsonObject.getLong("subscribe_time")*1000);//转换为毫秒
//				uinfo.setCreateDt(createDt);
//				uinfo.setSex(String.valueOf(jsonObject.getInt("sex")));
//				Log.info("==Oauth2Util==============panTestSubscribe===================jsonObject="+jsonObject);
//
//			}catch (Exception e){
//				uinfo = null;
//				String errCode = jsonObject.getString("errcode");
//				String errMsg = jsonObject.getString("errmsg");
//				Log.error("获取网页信息的失败errcode:{" + errCode + "} errmsg{" + errMsg + "}");
//			}
//		}
//		return uinfo;
//
//	}
	
	/**
	 * 获取AccessToken
	 * @param appId
	 * @param appSecret
	 * @return
	 */
//	public static String getAccessToken4User(String appId, String appSecret){
//		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
//		requestUrl =  requestUrl.replace("APPID", appId);
//		requestUrl =  requestUrl.replace("SECRET", appSecret);
//		String access_token =null;
//		Log.info("getAccessToken4User===requestUrl===="+requestUrl);
//		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
//		if (jsonObject != null){
//			try {
//				access_token = jsonObject.getString("access_token");
//			} catch (Exception e) {
//				String errCode = jsonObject.getString("errcode");
//				String errMsg = jsonObject.getString("errmsg");
//				Log.error("获取token失败errcode:{" + errCode + "} errmsg{" + errMsg + "}");
//			}
//		}
//		return access_token;
//	}

	
	/**
	 * 根据token创建二维码
	 * @param access_token
	 * @return
	 */
	public static String qrCodeCreate(String access_token, int sceneId){
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+access_token;
		Log.info("qrCodeCreate====requestUrl===="+requestUrl);
		// output data  
	    Map<String, Integer> intMap = new HashMap<String, Integer>();  
	    intMap.put("scene_id", sceneId);  
	    Map<String, Map<String, Integer>> mapMap = new HashMap<String, Map<String, Integer>>();  
	    mapMap.put("scene", intMap);  
	    //  
	    Map<String, Object> paramsMap = new HashMap<String, Object>();  
	    paramsMap.put("action_name", Constant.QR_LIMIT_SCENE);  
	    paramsMap.put("action_info", mapMap);  
	    com.alibaba.fastjson.JSONObject gson = new  com.alibaba.fastjson.JSONObject();  
	    String data = gson.toJSONString(paramsMap);  
		JSONObject jsonObject = httpRequest(requestUrl, "POST", data);
		Log.info("qrCodeCreate====jsonObject===="+jsonObject);
		String url =null;
		if (jsonObject != null){
			try {
				url = jsonObject.getString("url");
			} catch (Exception e) {
				String errCode = jsonObject.getString("errcode");
				String errMsg = jsonObject.getString("errmsg");
				Log.error("获取url失败errcode:{" + errCode + "} errmsg{" + errMsg + "}");
			}
		}
		return url;
	}	
	
	public static String cancelCode(String access_token, String params){
		String requestUrl="https://api.weixin.qq.com/card/code/consume?access_token="+access_token;
		Log.info("queryCode====requestUrl===="+requestUrl);
		Map<String, Object> dataMap=new HashMap<String, Object>();
		dataMap.put("code", params);
		com.alibaba.fastjson.JSONObject gson = new  com.alibaba.fastjson.JSONObject();  
		String data=gson.toJSONString(dataMap);
	    System.out.println("data="+data);
		JSONObject jsonObject = httpRequest(requestUrl, "POST",data);
		if(jsonObject!=null){
			String errmsg = jsonObject.getString("errmsg");
			if("ok".equals(errmsg)){
				return "ok";
			}
		}
		return "error";
	}
	/**
	 * @description:发送微信模板消息
	 * @date: 2021/9/24 11:18
	 * @param appId:
	 * @param appSecret:
	 * @param openid:
	 * @param tempId:
	 * @param toUrl:
	 * @param miniprogram:
	 * @param data:
	 * @return java.lang.String
	 */
//	public static void sendTemplateMsg(String appId,
//										 String appSecret,
//										 String openid,
//										 String tempId,
//										 String toUrl,
//										 com.alibaba.fastjson.JSONObject miniprogram,
//									   com.alibaba.fastjson.JSONObject data){
//		String accToken = getAccessToken4User(appId, appSecret);
//		if(StringUtil.isNotEmpty(accToken)){
//			String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accToken;
//			com.alibaba.fastjson.JSONObject reqData = new com.alibaba.fastjson.JSONObject();
//			reqData.put("touser",openid);
//			reqData.put("template_id",tempId);
//			if(StringUtil.isNotEmpty(toUrl)){
//				reqData.put("url",toUrl);
//			}
//			if(miniprogram != null){
//				reqData.put("miniprogram",miniprogram);
//			}
//			reqData.put("data",data);
//			JSONObject object = httpRequest(url, "POST", reqData.toJSONString());
//			if(object == null){
//				Log.error("发送模板消息失败");
//			}else{
//				Log.info("发送模板消息返回参数:{}", com.alibaba.fastjson.JSONObject.toJSONString(object));
//				int errcode = object.getInteger("errcode");
//				if(errcode == 0){
//					Log.info("模板消息发送成功！");
//				}
//			}
//		}
//	}

	/**
	 * @description:小程序获取appid
	 * @date: 2021/10/13 13:52
	 * @param appid:
	 * @param appSecret:
	 * @param code:
	 * @return java.lang.String
	 */
//	public static JSONObject getWxAppOpenId(String appid,String appSecret,String code){
//		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";
//		url = url.replace("APPID",appid).replace("APPSECRET",appSecret).replace("CODE",code);
//		JSONObject respones = httpRequest(url, "GET", null);
//		Log.info("【获取小程序openid接口】返回参数:{}",respones.toString());
//		if(respones == null){
//			MsgException.throwException("获取失败！");
//		}
//		return respones;
//	}


	public static String getJsapiTicket(String accessToken){
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		url = url.replace("ACCESS_TOKEN",accessToken);
		JSONObject respones = httpRequest(url, "GET", null);
		Log.info("【获取小程序小程序接口】返回参数:{}",respones.toString());
		if(respones == null){
			MsgException.throwException("获取失败！");
		}
		if(respones.getInteger("errcode") != 0){
			MsgException.throwException(respones.getString("errmsg"));
		}
		return respones.getString("ticket");
	}
}
