package com.platform.yijia.utils.weixinapp;


import com.platform.yijia.utils.redis.RedisCacheUtil;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <Title>工具类: WeiXinUtil</Title>
 * <description> 获取微信用户信息和凭证 </description>
 * @author JK
 * @date 2019年11月10日
 */
public class WeiXinUserUtil {

    //微信小程序获取用户信息 https://api.weixin.qq.com/sns/userinfo
    //public final static String weiXinUserInfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    //凭证获取路径
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    //微信小程序路径获取openID "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";
    public final static String OPENID_URL  ="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";

    //微信公众号获取通过code换取网页授权access_token
    public final static String GZHAUTHORIZEINFO_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    //获取UnionId
    public final static String unionId_Url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    //获取公众号jsapi_ticket
    private static final String JSAPI_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    //日志
    private static final Logger logger = LoggerFactory.getLogger(WeiXinUserUtil.class);

    /*
     * 获取公众号jsapi_ticket
     * @param accessToken
     * @return
     */
    public static JSONObject getGzhJsapiTicket(String accessToken){
        String requestUrl =JSAPI_TICKET_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取公众号jsapi_ticket：" + jsonObject.toString());
        return jsonObject;

    }


    /*
     * 获取用户公众号的授权信息
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static JSONObject getGzhAuthorizeInfo(String appId, String appSecret, String code){
        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret +" ;code参数: " +code);
        String requestUrl = GZHAUTHORIZEINFO_URL.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取用户公众号的授权后信息：" + jsonObject.toString());
        return jsonObject;
    }


    /*
     * 获取公众号UnionId信息
     * @param accessToken
     * @param openId
     * @return
     */
    public static JSONObject getUnionIdInfo(String accessToken, String openId){
        String requestUrl = unionId_Url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取UnionId信息：" + jsonObject.toString());
        return jsonObject;
    }

    /*
     * 获取用户的openid和session_key 格式例子:{"session_key":"rlxKT/xhq2bxAuvrMeEq8Q==","openid":"o9RM50ppeCgx065T2PvJjtzB_Gmo"}
     * @param appId     //凭证
     * @param appSecret     //密钥
     * @param code
     * @return
     */
    public static Map<String, Object> getUserSessionKeyAndOpenID(String appId, String appSecret, String code){
        String requestUrl = OPENID_URL.replace("APPID", appId).replace("APPSECRET", appSecret).replace("CODE", code);
        Map<String, Object> resultMap = new HashMap<>();
        //发起GET请求
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("用户通过code获取到信息：:" + jsonObject.toString());
        if(jsonObject != null && jsonObject.containsKey("openid")){
            resultMap.put("openId", jsonObject.getString("openid"));
        }
        if(jsonObject != null && jsonObject.containsKey("session_key")){
            resultMap.put("sessionKey", jsonObject.getString("session_key"));
        }
        if(jsonObject != null && jsonObject.containsKey("unionid")){
            resultMap.put("unionId", jsonObject.getString("unionid"));
        }
        resultMap.put("code", code);
        return resultMap;
    }


    /*
     * 获取接口访问凭证
     * @param appId         //凭证
     * @param appSecret     //密钥
     * @return
     */
    public static Token getToken(String appId, String appSecret){
        Token token = null;
        String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", appSecret);
        //发起GET请求获取凭证
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        System.out.println("getToken: "+jsonObject);
        if(jsonObject != null){
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        return token;
    }

    /*
     * 从redis获取token
     * @param appId
     * @param appSecret
     * @return
     */
//    public String getTokenByRedisCache(String appId, String appSecret){
//        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret);
//        String tokenCache ="";
//        if(!redisCacheUtil.hasKey(appId)){
//            String token = WeiXinUserUtil.getToken(appId, appSecret).getAccessToken();
//            redisCacheUtil.setCacheObject(appId, token);
//            redisCacheUtil.expire(appId, 7200, TimeUnit.SECONDS);
//            tokenCache = token;
//            logger.info("Redis缓存中token信息: " + tokenCache);
//        }else {
//            tokenCache = redisCacheUtil.getCacheObject(appId);
//        }
//        return tokenCache;
//    }


}
