package com.gh.gamecenter.wxapi;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.core.provider.IConfigProvider;
import com.lightgame.utils.Utils;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by khy on 30/06/17.
 * 获取微信 accessToken 和 userInfo
 */

public class WeChatUserInfoThread extends Thread {

    private Context mContext;
    private OnUserInfoCallBackListener listener;

    private String mCode;

    //刷新access_token有效期
    private String refresh_token = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";

    public WeChatUserInfoThread(OnUserInfoCallBackListener listener, String code, Context context) {
        this.listener = listener;
        this.mCode = code;
        this.mContext = context;
    }

    @Override
    public void run() {
        super.run();
        try {
            IConfigProvider config = (IConfigProvider) ARouter.getInstance().build(RouteConsts.provider.config).navigation();
            String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
                    config.getWechatAppId() + "&secret=" +
                    config.getWechatSecret() + "&code=" +
                    mCode + "&grant_type=authorization_code";
            String jsonResult = getJsonResultByUrlPath(tokenUrl);
            JSONObject jsonObject = new JSONObject(jsonResult);
            String accessToken = jsonObject.getString("access_token");
            String refreshToken = jsonObject.getString("refresh_token");
            String openid = jsonObject.getString("openid");
            String unionid = jsonObject.getString("unionid");

            if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(openid) && !TextUtils.isEmpty(refreshToken) && listener != null) {
//                String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid;
//                String userInfo = getJsonResultByUrlPath(userInfoUrl);
                JSONObject content = new JSONObject();
                content.put("openid", openid);
                content.put("access_token", accessToken);
                content.put("access_token_expire", Utils.getTime(mContext) + 7200); // 有效期 2小时
                content.put("refresh_token", refreshToken);
//                content.put("refresh_token_expire", Utils.getTime(mContext) + 86400 * 30); // 有效期 30天
                content.put("unionid", unionid);

                listener.onComplete(content);
            } else {
                if (listener != null) {
                    listener.onError();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onError();
            }
        }
    }

    private String getJsonResultByUrlPath(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        int code = conn.getResponseCode();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        Utils.log(WeChatUserInfoThread.class.getSimpleName(), "WeChatUserInfoThread-getJsonResultByUrlPath::" + code);
        if (code == 200) {
            InputStream is = conn.getInputStream();
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String str = new String(baos.toByteArray());
            Utils.log(WeChatUserInfoThread.class.getSimpleName(), "WeChatUserInfoThread-Body::" + str);
            return str;
        }
        return null;
    }

    public interface OnUserInfoCallBackListener {
        void onComplete(JSONObject content);

        void onError();
    }
}
