package cn.iselab.mooctest.user.util;

import cn.iselab.mooctest.rpc.user.data.WechatUserInfoDTO;
import cn.iselab.mooctest.user.data.Token;
import cn.iselab.mooctest.user.data.UserInfo;
import com.google.gson.Gson;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author ROKG
 * @Description
 * @Date: Created in 下午4:41 2018/4/2
 * @Modified By:
 */
public class WechatUtil {

    protected final static Logger LOG = LoggerFactory.getLogger(WechatUtil.class);

    public final static String base_url="https://api.weixin.qq.com/sns/";

    public final static String token_url=base_url+"oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    public final static String refresh_url=base_url+"oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";

    public final static String user_info_url=base_url+"userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    public static Token getToken(String appId, String appSecret, String code) {
        Token token = new Token();
        LOG.info("Ready to get the token");
        String result="";
        try {
            String url = token_url.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
            result = HttpClientUtils.get(url.toString(), "UTF-8");
        }catch (Exception e){
            LOG.error("获取token失败："+e.getMessage());
        }
        JSONObject object=new JSONObject(result);
        try {
            LOG.info(object.toString());
            token.setAccessToken(object.getString("access_token"));
            token.setExpiresIn(object.getInt("expires_in"));
            token.setRefresh_token(object.getString("refresh_token"));
            token.setOpenId(object.getString("openid"));
        }catch (Exception e){
            LOG.error("获取token失败 errcode:" + object.getInt("errcode") + " errmsg:" + object.getString("errmsg"));
        }
        return token;
    }



    public static WechatUserInfoDTO getWxUser(String accessToken, String openid){
        Gson gson=new Gson();
        String result="";
        try {
            String url = user_info_url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
            result = HttpClientUtils.get(url.toString(), "UTF-8");
        }catch (Exception e){
            LOG.error("获取token失败："+e.getMessage());
        }
        WechatUserInfoDTO userInfo=gson.fromJson(result,WechatUserInfoDTO.class);
        System.out.println("openId:"+userInfo.getOpenid());
        System.out.println("unionId:"+userInfo.getUnionid());
        System.out.println("nickname:"+userInfo.getNickname());
        return userInfo;
    }
}
