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.therouter.TheRouter;
import com.gh.gamecenter.common.eventbus.EBShare;
import com.gh.gamecenter.common.utils.SensorsBridge;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.gh.gamecenter.common.utils.WXAPIProxyFactory;
import com.gh.gamecenter.core.provider.IAppProvider;
import com.gh.gamecenter.core.provider.IConfigProvider;
import com.gh.gamecenter.core.provider.IDefaultUrlHandlerProvider;
import com.gh.gamecenter.core.provider.IQGameProvider;
import com.gh.gamecenter.login.utils.LoginHelper;
import com.lightgame.utils.Utils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
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.SendMessageToWX;
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 = TheRouter.get(IConfigProvider.class);
        mWxApi = WXAPIFactory.createWXAPI(this, config.getWechatAppId(), false);
        mWxApi.handleIntent(getIntent(), this);
        TextView textView = new TextView(this);
        textView.setSingleLine(true);
    }

    @Override
    public 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 = TheRouter.get(IDefaultUrlHandlerProvider.class);
                if (defaultUrlHandler != null) {
                    defaultUrlHandler.interceptUrl(this, messageExt, "微信", true, "");
                }
                finishActivity();
            }
        }
    }

    @Override
    public void onResp(BaseResp baseResp) {
        IQGameProvider iqGameProvider = TheRouter.get(IQGameProvider.class);
        // 将分享和 auth 的部分回调抛给 QGameProvider 处理
        if (baseResp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX && baseResp instanceof SendMessageToWX.Resp) {
            SendMessageToWX.Resp rsp = (SendMessageToWX.Resp) baseResp;

            if (iqGameProvider != null) {
                switch (rsp.errCode) {
                    case BaseResp.ErrCode.ERR_OK:
                        iqGameProvider.onWechatShare(this.getApplicationContext(), 1);
                        break;
                    case BaseResp.ErrCode.ERR_USER_CANCEL:
                        iqGameProvider.onWechatShare(this.getApplicationContext(), -1);
                        break;
                    default:
                        iqGameProvider.onWechatShare(this.getApplicationContext(), 0);
                        break;
                }
            }
        } else if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH
                && baseResp instanceof SendAuth.Resp
                && ((SendAuth.Resp) baseResp).state != null
                && !((SendAuth.Resp) baseResp).state.contains("qqminigame")
        ) {
            WXAPIProxyFactory.getLiveData().postValue(baseResp);
        } else if (baseResp.getType() == ConstantsAPI.COMMAND_SUBSCRIBE_MESSAGE) {
            WXAPIProxyFactory.getLiveData().postValue(baseResp);
        }

        String resultString = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    String shareType;
                    if ("wechat_friend".equals(ShareUtils.shareType)) {
                        shareType = "微信好友";
                    } else {
                        shareType = "朋友圈";
                    }

                    resultString = "分享成功";
                    Utils.toast(this, resultString);
                    EventBus.getDefault().post(new EBShare(ShareUtils.shareEntrance, shareType));
                    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.additionalParams != null && (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);
                        SensorsBridge.trackArticleShareResult(
                                ShareUtils.additionalParams.getCustomerType(),
                                ShareUtils.additionalParams.getContentId(),
                                ShareUtils.additionalParams.getBbsId(),
                                ShareUtils.additionalParams.getBbsType(),
                                ShareUtils.additionalParams.getActivityTagName(),
                                ShareUtils.additionalParams.getGameForumType(),
                                ShareUtils.additionalParams.getContentType(),
                                shareType,
                                "分享成功"
                        );
                    } else if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.gameCollection) {
                        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);
                        resultString = "登录成功，即将获取用户信息";
                        new WeChatUserInfoThread(WXEntryActivity.this, resp, WXEntryActivity.this)
                                .start();
                    } else {
                        resultString = "登录失败";
                        LoginHelper.onWechatLoginFailure(resultString);
                    }
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    resultString = getString(com.gh.gamecenter.common.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 = "登录已取消";
                    if (baseResp instanceof SendAuth.Resp
                            && ((SendAuth.Resp) baseResp).state != null
                            && !((SendAuth.Resp) baseResp).state.contains("qqminigame")
                    ) {
                        iqGameProvider.onWechatLogin(this, "", true, resultString);
                    }
                }
                LoginHelper.onWechatLoginFailure(resultString);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    resultString = "分享被拒绝";
                } else {
                    resultString = "登录被拒绝";
                    if (baseResp instanceof SendAuth.Resp
                            && ((SendAuth.Resp) baseResp).state != null
                            && !((SendAuth.Resp) baseResp).state.contains("qqminigame")
                    ) {
                        iqGameProvider.onWechatLogin(this, "", true, 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);
                    }

                    if(ShareUtils.additionalParams != null && (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video
                            || ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle
                            || ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal))
                    {
                        String shareType;
                        if ("wechat_friend".equals(ShareUtils.shareType)) {
                            shareType = "微信好友";
                        } else {
                            shareType = "朋友圈";
                        }

                        SensorsBridge.trackArticleShareResult(
                                ShareUtils.additionalParams.getCustomerType(),
                                ShareUtils.additionalParams.getContentId(),
                                ShareUtils.additionalParams.getBbsId(),
                                ShareUtils.additionalParams.getBbsType(),
                                ShareUtils.additionalParams.getActivityTagName(),
                                ShareUtils.additionalParams.getGameForumType(),
                                ShareUtils.additionalParams.getContentType(),
                                shareType,
                                "分享失败"
                        );
                    }
                } else {
                    resultString = "登录错误";
                    if (baseResp instanceof SendAuth.Resp
                            && ((SendAuth.Resp) baseResp).state != null
                            && !((SendAuth.Resp) baseResp).state.contains("qqminigame")
                    ) {
                        iqGameProvider.onWechatLogin(this, "", false, resultString);
                    }
                }
                LoginHelper.onWechatLoginFailure(resultString);
                break;
        }

        if (!TextUtils.isEmpty(resultString)) {
            finishActivity();
        }
    }

    @Override
    public void onComplete(SendAuth.Resp resp, final JSONObject content) {
        runOnUiThread(() -> {
            LoginHelper.onWechatLoginSuccess(content);
            if (resp.state != null && resp.state.contains("qqminigame")
            ) {
                IQGameProvider iqGameProvider = TheRouter.get(IQGameProvider.class);
                if (iqGameProvider != null) {
                    iqGameProvider.onWechatLogin(this, content.toString(), false, "登录成功");
                }
            }

            finishActivity();
        });
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IAppProvider appProvider = TheRouter.get(IAppProvider.class);
        if (appProvider != null) {
            appProvider.setDisableSplashAdTemporarily(false);
        }
    }
}