package com.ym.unityandroid;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unity3d.player.UnityPlayer;
import com.ym.unityandroid.webview.UnityWebActivity;

public class UnityWxLoginUtil {


    private static volatile UnityWxLoginUtil sInstance;
    private UnityWxLoginUtil() {

    }

    public static UnityWxLoginUtil getInstance() {
        if (sInstance == null) {
            synchronized (UnityWxLoginUtil.class) {
                if (sInstance == null) {
                    sInstance = new UnityWxLoginUtil();
                }
            }
        }
        return sInstance;
    }
    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    public static String WxAPP_ID = "";
    private IWXAPI api;

    //初始化微信登录key
    public void InitWxLogin(Activity activity, String WxAppId){
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WxAPP_ID = WxAppId;
                // 通过WXAPIFactory工厂，获取IWXAPI的实例
                api = WXAPIFactory.createWXAPI(activity.getBaseContext(), WxAPP_ID, true);
                // 将应用的appId注册到微信
                api.registerApp(WxAPP_ID);
            }
        });
    }
    //微信登录页面
    public void wxLogin(Activity activity){
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (api.isWXAppInstalled()){
                    Log.d("wxw","wxwisWXAppInstalled1");
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk";
                    if (api!=null){
                        api.sendReq(req);
                    }
                }else {
                    UnityPlayer.UnitySendMessage("WxLoginTool","OnWxAuthFail", "微信未安装");
                    Toast.makeText(activity, "请安装微信", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    //打开H5页面
    public void OpenH5Page(Activity activity,String url,String title){
        Intent intent = new  Intent(activity, UnityWebActivity.class);
        intent.putExtra("url",url);
        activity.startActivity(intent);
    }


}
