package com.sino.weixin.oauth.util;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sino.rescue.oauth.entity.SNSUserInfo;
import com.sino.rescue.oauth.entity.WeixinOauth2Token;
import com.sino.weixin.api.entity.WeixinApiTicket;
import com.sino.weixin.api.entity.WeixinApiToken;
import com.sino.weixin.util.SHA1;

public class AdvancedUtil {
	private static Log log =  LogFactory.getLog("AdvancedUtil");

	
	public WeixinOauth2Token getOauth2AccessToken(String appId,String appSeret,String code){
		String get_access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
		        "appid=APPID" +
		        "&secret=SECRET&" +
		        "code=CODE&grant_type=authorization_code";
		get_access_token_url=get_access_token_url.replace("APPID", appId);
        get_access_token_url=get_access_token_url.replace("SECRET", appSeret);
        get_access_token_url=get_access_token_url.replace("CODE", code);
        
        log.info("此时获取的微信code是否为空"+code);
        log.info("get_access_token_url:"+get_access_token_url);
        String json=HttpUtil.getUrl(get_access_token_url);
        log.info("json:"+json);
        
        String access_token;
		String openid;
		String refresh_token;
		String scope;
		int expires_in;
        
		try {
			JSONObject jsonObject=JSON.parseObject(json);
			access_token = jsonObject.getString("access_token");
			openid = jsonObject.getString("openid");
			refresh_token = jsonObject.getString("refresh_token");
			scope = jsonObject.getString("scope");
			expires_in = jsonObject.getIntValue("expires_in");
		} catch (Exception e) {
			JSONObject jsonObject=JSON.parseObject(json);
			access_token = jsonObject.getString("access_token");
			openid = jsonObject.getString("openid");
			refresh_token = jsonObject.getString("refresh_token");
			scope = jsonObject.getString("scope");
			expires_in = jsonObject.getIntValue("expires_in");
		}
		
		
		
		WeixinOauth2Token token = new WeixinOauth2Token();
		token.setAccess_token(access_token);
		token.setExpires_in(expires_in);
		token.setOpenid(openid);
		token.setRefresh_token(refresh_token);
		token.setScope(scope);
		System.out.println("此时获取到的openid是否为空"+token.getOpenid()+token.getAccess_token());
		return token;
	}
	
	/**
	 * 获取access_token
	 * @param appId
	 * @param appSeret
	 * @return
	 */
	public WeixinApiToken getWeixinApiToken(String appId,String appSeret){
		String get_access_token_url="https://api.weixin.qq.com/cgi-bin/token?" +
		        "appid=APPID" +
		        "&secret=APPSECRET" +
		        "&grant_type=client_credential";
		get_access_token_url=get_access_token_url.replace("APPID", appId);
        get_access_token_url=get_access_token_url.replace("APPSECRET", appSeret);
         
        System.out.println(get_access_token_url);
        String json=HttpUtil.getUrl(get_access_token_url);
        JSONObject jsonObject=JSON.parseObject(json);
        String access_token=jsonObject.getString("access_token");
		int expires_in = jsonObject.getIntValue("expires_in");
		
	//	Constants.ACCESS_TOKEN = access_token;
		
		WeixinApiToken token = new WeixinApiToken();
		token.setAccess_token(access_token);
		token.setExpires_in(expires_in);
		return token;
	}
	
    /**
     * 获取jsapi_ticket
     * @param access_token
     * @return
     */
	public WeixinApiTicket getJSApiTicket(String access_token){
		String get_api_ticket_url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		get_api_ticket_url=get_api_ticket_url.replace("ACCESS_TOKEN", access_token);

        String json=HttpUtil.getUrl(get_api_ticket_url);
        JSONObject jsonObject=JSON.parseObject(json);
        String ticket_str=jsonObject.getString("ticket");
		int expires_in = jsonObject.getIntValue("expires_in");

		WeixinApiTicket ticket = new WeixinApiTicket();
		ticket.setTicket(ticket_str);
		ticket.setExpires_in(expires_in);
		return ticket;
	}
	
	/**
	 * 获取签名
	 * @param jsapi_ticket
	 * @param noncestr
	 * @param timestamp
	 * @return
	 */
	public String getSha1Signature(String jsapi_ticket,String noncestr,String timestamp,String url){
		
		String[] str = { "jsapi_ticket="+jsapi_ticket, "noncestr="+noncestr, "timestamp="+timestamp,"url="+url};
        Arrays.sort(str); // 字典序排序
        String bigStr = str[0] +"&" + str[1] +"&" + str[2] + "&" + str[3];

        // SHA1加密
        String signature = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();

		return signature;
	}
	
	public SNSUserInfo getSNSUserInfo(String access_token,String openid){
		String get_userinfo="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		
		get_userinfo=get_userinfo.replace("ACCESS_TOKEN", access_token);
        get_userinfo=get_userinfo.replace("OPENID", openid);
        
        String userInfoJson=HttpUtil.getUrl(get_userinfo);
        System.out.println("userInfoJson="+userInfoJson);
        JSONObject userInfoJO=JSON.parseObject(userInfoJson);
        
        String user_openid=userInfoJO.getString("openid");
        Matcher userNickname=Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]").matcher(userInfoJO.getString("nickname"));
        String user_nickname=userNickname.find()?userNickname.replaceAll(""):userInfoJO.getString("nickname");
        //  String user_nickname= preg_replace('/[\x{10000}-\x{10FFFF}]/u', userInfoJO.getString("nickname"));
        String user_sex=userInfoJO.getString("sex");
        String user_province=userInfoJO.getString("province");
        String user_city=userInfoJO.getString("city");
        String user_country=userInfoJO.getString("country");
		SNSUserInfo snsUserInfo = new SNSUserInfo();
		snsUserInfo.setOpenid(user_openid);
		snsUserInfo.setNickname(user_nickname);
		snsUserInfo.setSex(user_sex);
		snsUserInfo.setCity(user_city);
		snsUserInfo.setProvince(user_province);
		snsUserInfo.setCountry(user_country);
		return snsUserInfo;
	}

}
