package com.gh.gamecenter.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gh.gamecenter.common.utils.SensorsBridge;
import com.gh.gamecenter.login.utils.LoginHelper;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.common.eventbus.EBShare;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.gh.gamecenter.core.provider.IConfigProvider;
import com.gh.gamecenter.core.provider.IDefaultUrlHandlerProvider;
import com.gh.gamecenter.login.R;
import com.lightgame.utils.Utils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

/**
 * 微信客户端回调activity示例
 * 注意：WXEntryActivity类只能在wxapi包下
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler, WeChatUserInfoThread.OnUserInfoCallBackListener {

    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    private IWXAPI mWxApi;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IConfigProvider config = (IConfigProvider) ARouter.getInstance().build(RouteConsts.provider.config).navigation();
        mWxApi = WXAPIFactory.createWXAPI(this, config.getWechatAppId(), false);
        mWxApi.handleIntent(getIntent(), this);
        TextView textView = new TextView(this);
        textView.setSingleLine(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWxApi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        if (baseReq instanceof ShowMessageFromWX.Req) {
            String messageExt = ((ShowMessageFromWX.Req) baseReq).message.messageExt;
            if (!TextUtils.isEmpty(messageExt)) {
                IDefaultUrlHandlerProvider defaultUrlHandler = (IDefaultUrlHandlerProvider) ARouter.getInstance().build(RouteConsts.provider.defaultUrlHandler).navigation();
                defaultUrlHandler.interceptUrl(this, messageExt, "浏览器", true);
                finishActivity();
            }
        }
    }

    @Override
    public void onResp(BaseResp baseResp) {
        String resultString = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    resultString = "分享成功";
                    Utils.toast(this, resultString);
                    EventBus.getDefault().post(new EBShare(ShareUtils.shareEntrance));
                    com.gh.gamecenter.common.utils.LogUtils.uploadShareResult(ShareUtils.shareType, ShareUtils.shareEntrance.getName(), "success",
                            ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
                    if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                            ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle ||
                            ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                        com.gh.gamecenter.common.utils.NewLogUtils.logShareResult(ShareUtils.additionalParams, true);
                    } else if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.gameCollection) {
                        String shareType;
                        if ("wechat_friend".equals(ShareUtils.shareType)) {
                            shareType = "微信";
                        } else {
                            shareType = "朋友圈";
                        }
                        com.gh.gamecenter.common.utils.NewLogUtils.logViewOrClickGameCollectionDetail(
                                "click_game_collect_detail_favorite_success",
                                ShareUtils.shareEntity.getShareTitle(),
                                ShareUtils.resourceId,
                                shareType
                        );
                        SensorsBridge.trackEvent(
                                "GameCollectDetailShareClickSuccess",
                                "game_collect_title", ShareUtils.shareEntity.getShareTitle(),
                                "game_collect_id", ShareUtils.resourceId,
                                "share_type", shareType
                        );
                    }
                } else {
                    if (baseResp instanceof SendAuth.Resp) {
                        SendAuth.Resp resp = (SendAuth.Resp) baseResp;
                        Utils.log("WXEntryActivity=TOKEN::" + resp.code);
                        new WeChatUserInfoThread(WXEntryActivity.this, resp.code, WXEntryActivity.this)
                                .start();
                    } else {
                        resultString = "登录失败";
                        LoginHelper.onWechatLoginFailure(resultString);
                    }
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    resultString = getString(R.string.share_cancel_hint);
                    com.gh.gamecenter.common.utils.LogUtils.uploadShareResult(ShareUtils.shareType, ShareUtils.shareEntrance.getName(), "cancel",
                            ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
                    if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                            ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle ||
                            ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                        com.gh.gamecenter.common.utils.NewLogUtils.logShareResult(ShareUtils.additionalParams, false);
                    }
                } else {
                    resultString = "登录已取消";
                }
                LoginHelper.onWechatLoginFailure(resultString);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    resultString = "分享被拒绝";
                } else {
                    resultString = "登录被拒绝";
                }
                LoginHelper.onWechatLoginFailure(resultString);
                break;
            default:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    resultString = "分享错误";
                    com.gh.gamecenter.common.utils.LogUtils.uploadShareResult(ShareUtils.shareType, ShareUtils.shareEntrance.getName(), "fail",
                            ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
                    if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                            ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle ||
                            ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                        com.gh.gamecenter.common.utils.NewLogUtils.logShareResult(ShareUtils.additionalParams, false);
                    }
                } else {
                    resultString = "登录错误";
                }
                LoginHelper.onWechatLoginFailure(resultString);
                break;
        }
        if (!TextUtils.isEmpty(resultString)) {
            finishActivity();
        }
    }

    @Override
    public void onComplete(final JSONObject content) {
        runOnUiThread(() -> {
            LoginHelper.onWechatLoginSuccess(content);
            finishActivity();
        });
    }

    @Override
    public void onError() {
        LoginHelper.onWechatLoginFailure("登录失败");
        finishActivity();
    }

    private void finishActivity() {
        this.finish();
        overridePendingTransition(0, 0);//禁止退出Activity 动画
    }
}