package com.gh.gamecenter;

import static com.gh.gamecenter.common.constant.Constants.LOGIN_TAG;
import static com.gh.gamecenter.common.constant.Constants.LOGOUT_TAG;
import static com.gh.gamecenter.common.constant.EntranceConsts.ENTRANCE_BROWSER;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_LAUNCH_SIMULATOR_GAME;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_LAUNCH_VM_GAME;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_QQ;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_QQ_GROUP;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_WEB;
import static com.gh.gamecenter.common.constant.EntranceConsts.KEY_DATA;
import static com.gh.gamecenter.common.constant.EntranceConsts.KEY_MARKET_DETAILS;
import static com.gh.gamecenter.common.constant.EntranceConsts.KEY_NEXT_TO;
import static com.gh.gamecenter.common.constant.EntranceConsts.KEY_TO;
import static com.gh.gamecenter.common.constant.EntranceConsts.KEY_TYPE;
import static com.gh.gamecenter.common.utils.ExtensionsKt.observableToMain;
import static com.gh.gamecenter.login.utils.LoginHelper.WEIBO_SCOPE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import com.gh.ad.AdDelegateHelper;
import com.gh.ad.SplashAdVideoView;
import com.gh.common.constant.Config;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.history.HistoryDatabase;
import com.gh.common.history.HistoryHelper;
import com.gh.common.prioritychain.GlobalPriorityChainHelper;
import com.gh.common.repository.ReservationRepository;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.util.AdHelper;
import com.gh.common.util.CertificationSwitchHelper;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DirectUtils;
import com.gh.common.util.EntranceUtils;
import com.gh.common.util.ErrorHelper;
import com.gh.common.util.LogUtils;
import com.gh.common.util.LunchType;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.WechatBindHelper;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.common.avoidcallback.AvoidOnResultManager;
import com.gh.gamecenter.common.base.activity.BaseActivity;
import com.gh.gamecenter.common.base.activity.ToolBarActivity;
import com.gh.gamecenter.common.base.fragment.BaseFragment_ViewPager;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.common.constant.CommonConsts;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.entity.LinkEntity;
import com.gh.gamecenter.common.entity.SuggestType;
import com.gh.gamecenter.common.eventbus.EBNetworkState;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.pagelevel.PageLevel;
import com.gh.gamecenter.common.pagelevel.PageLevelManager;
import com.gh.gamecenter.common.retrofit.BiResponse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.FileUtils;
import com.gh.gamecenter.common.utils.NewFlatLogUtils;
import com.gh.gamecenter.common.utils.SensorsBridge;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.core.utils.ClassUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.GsonUtils;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.entity.StartupAdEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.feature.utils.SentryHelper;
import com.gh.gamecenter.home.custom.model.CustomPageShareRepository;
import com.gh.gamecenter.home.skip.PackageSkipActivity;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.login.utils.QuickLoginHelper;
import com.gh.gamecenter.packagehelper.PackageViewModel;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.room.AppDatabase;
import com.gh.gamecenter.room.dao.SimulatorGameDao;
import com.gh.gamecenter.wrapper.MainWrapperFragment;
import com.gh.gamecenter.wrapper.MainWrapperRepository;
import com.gh.gamecenter.wrapper.MainWrapperViewModel;
import com.gh.vspace.VHelper;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.halo.assistant.HaloApp;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;
import com.lightgame.utils.Utils;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.WBAPIFactory;

import com.therouter.TheRouter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import kotlin.Pair;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import tv.danmaku.ijk.media.exo2.ExoSourceManager;

public class MainActivity extends BaseActivity {

    public static final String SHOW_AD = "show_ad";
    public static final int COUNTDOWN_AD = 100;
    private int mCountdownMaxCount = 3;
    public static final int COUNTDOWN_SDK_AD = 101;
    public static final int COUNTDOWN_SDK_MAX_COUNT = 5;
    private int mCountdownCount = 0;

    private static final String CURRENT_PAGE = "current_page";

    private PackageViewModel mPackageViewModel;

    private MainWrapperViewModel mMainWrapperViewModel;

    private MainWrapperFragment mMainWrapperFragment;

    // 黄壮华 按连续按返回键两次才退出应用
    private final long[] mHits = new long[2];

    private final Handler handler = new Handler();
    private boolean mShouldShowAd = false; // 是否显示广告

    private Bundle mTempSavedInstanceState;
    private boolean mFragmentIsCreated = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mTempSavedInstanceState = savedInstanceState;

        mShouldShowAd = getIntent().getBooleanExtra(SHOW_AD, false) && savedInstanceState == null
                && !HaloApp.getInstance().isAlreadyUpAndRunning;
        HaloApp.getInstance().isAlreadyUpAndRunning = true;

        mMainWrapperViewModel = new ViewModelProvider(this, new MainWrapperViewModel.Factory(HaloApp.getInstance()))
                .get(MainWrapperViewModel.class);

        DisplayUtils.transparentStatusBar(this);

        super.onCreate(savedInstanceState);
        setStatusBarColor(Color.TRANSPARENT);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (HaloApp.getInstance().isNewForThisVersion) {
            LunchType lunchType = HaloApp.getInstance().getLaunchType();
            AppExecutor.getUiExecutor().executeWithDelay(() -> {
                if (!this.isFinishing()) {
                    // 第一次打开App删除模拟器游戏记录（不包括更新版本）
                    if (HaloApp.getInstance().isBrandNewInstall) {
                        getTeenagerMode();
                        SimulatorGameManager.deleteAllSimulatorGame();
                    }
                }
            }, 2000L);
            sp.edit().putBoolean(Constants.SP_NEW_FIRST_LAUNCH_VERSION + PackageUtils.getGhVersionName(), false).apply();

            // 记录曾安装过的版本 + 渠道
            SPUtils.setString("installedVersionV" + PackageUtils.getGhVersionName(), HaloApp.getInstance().getChannel());

            SPUtils.setString(Constants.SP_INSTALL_TYPE, lunchType.name());
        }

        // 若 SplashActivity 没能获取到 Gid 这里再重试一次
        if (TextUtils.isEmpty(HaloApp.getInstance().getGid())) {
            DataUtils.getGid();
        }

        mPackageViewModel = ViewModelProviders.of(this, new PackageViewModel.Factory()).get(PackageViewModel.class);

        final boolean containsErrorMsg = com.gh.gamecenter.common.constant.Config.isContainsErrorMsg();
        if (containsErrorMsg) {
            com.gh.gamecenter.common.constant.Config.updateContainsErrorMsg(false);
            DataUtils.reportException(this, new Throwable(com.gh.gamecenter.common.constant.Config.getExceptionMsg()));
            // 被改过的包闪退时增加跳转到光环游戏详情并自动下载的方法
            if (com.gh.gamecenter.common.constant.Config.DEFAULT_CHANNEL_FOR_RELEASE.equals(HaloApp.getInstance().getChannel())) {
                DialogHelper.showCenterWarningDialog(this, "发生闪退", "光环助手发生了闪退，建议安装到最新版本修复异常"
                        , "马上反馈", "马上安装修复",
                        () -> {
                            DirectUtils.directToGameDetail(this, Constants.GHZS_GAME_ID, "", "crash", true, "desc", null, "");
                            return null;
                        },
                        () -> {
                            DirectUtils.directToSuggestion(MainActivity.this, SuggestType.APP, "APP闪退：", false, 100);
                            return null;
                        });
            } else {
                DialogHelper.showCenterWarningDialog(this, "发生闪退", "光环助手刚刚发生了闪退，马上反馈以帮助我们更好地修复问题？（只需简单描述你刚才的操作）"
                        , "暂不", "马上反馈",
                        () -> {
                            DirectUtils.directToSuggestion(MainActivity.this, SuggestType.APP, "APP闪退：", false, 100);
                            return null;
                        },
                        () -> null);
            }
        }

        ReservationRepository.refreshReservations();

        // 跳转至其它页面
        if (getIntent() != null
                && getIntent().getExtras() != null) {
            if (getIntent().getBooleanExtra(EntranceConsts.KEY_REQUIRE_REDIRECT, false)) {
                doSkip();
            } else if (!TextUtils.isEmpty(getIntent().getStringExtra(EntranceConsts.KEY_THE_ROUTER_PATH))) {
                doRedirect(getIntent().getStringExtra(EntranceConsts.KEY_THE_ROUTER_PATH));
            }
        }

        // debug 模式下的快速跳转页面
        if (BuildConfig.DEBUG) {
            handler.postDelayed(() -> EntranceUtils.jumpShortcut(this), 500);
        }

        if (mShouldShowAd) {
            showAd();
        } else {
            doInitMainFragment(mTempSavedInstanceState);
            hideTextAd();
            hideSplashAd();
        }

        // 默认配置为空时重试
        if (Config.getSettings() == null) {
            Config.getGhzsSettings();
        } else if (Config.getVSettingEntity() == null) {
            Config.refreshVSettingEntity();
        } else if (Config.getVNewSettingEntity() == null) {
            Config.getNewSetting();
        }

        // 耗时操作
        AppExecutor.getIoExecutor().execute(() -> {
            // 初始化PlatformUtils
            PlatformUtils.getInstance(getApplicationContext());

            // 启动app删除视频缓存文件
            try {
                String dirPath = getCacheDir().getAbsolutePath() + File.separator + "exo";
                FileUtils.deleteFolder(new File(dirPath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //恢复视频流非Wifi提醒
        SPUtils.setBoolean(Constants.SP_NON_WIFI_TIPS, true);
        //重置首页视频播放进度
        SPUtils.setString(Constants.SP_HOME_VIDEO_PLAY_RECORD, "");
        //第一次进入发现页列表数据强制刷新
        SPUtils.setBoolean(Constants.SP_DISCOVER_FORCE_REFRESH, true);

        postAttentionVideoRecord();
        deleteSimulatorGame();
        if (SPUtils.getBoolean(RegionSettingHelper.SP_SETTING_FAILURE)) {
            RegionSettingHelper.getRegionSetting();
        }

        // 检查是否需要触发 XAPK 安装
        AppExecutor.getUiExecutor().executeWithDelay(this::resumeXapkInstallIfNeeded, 150);

        mMainWrapperViewModel.requestAllDialogData();

        QuickLoginHelper.preLogin(this);

        // TODO 搞清楚为什么这里要获取微信相关配置
        WechatBindHelper.getWechatConfig(null);

        // TODO 根据用户是否安装微博来确定是否需要初始化微博 SDK
        initWBSDK();
        CertificationSwitchHelper.getCertificationSwitch();
    }

    private void doInitMainFragment(Bundle savedInstanceState) {
        if (mFragmentIsCreated) return;

        mTempSavedInstanceState = null;
        Fragment fragmentFromFM = getSupportFragmentManager().findFragmentById(com.gh.gamecenter.selector.R.id.layout_activity_content);

        mMainWrapperFragment = fragmentFromFM != null ? (MainWrapperFragment) fragmentFromFM : new MainWrapperFragment();
        if (savedInstanceState != null) {
            mMainWrapperFragment.setArguments(savedInstanceState);
        } else if (getIntent() != null) {
            mMainWrapperFragment.setArguments(getIntent().getExtras());
        }
        replaceFragment(mMainWrapperFragment);

        mFragmentIsCreated = true;
    }

    @SuppressLint("CheckResult")
    private void getTeenagerMode() {
        RetrofitManager.getInstance()
                .getApi().getTeenagerMode(HaloApp.getInstance().getGid())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BiResponse<ResponseBody>() {
                    @Override
                    public void onSuccess(ResponseBody data) {
                        try {
                            boolean preStatus = SPUtils.getBoolean(Constants.SP_TEENAGER_MODE);
                            JSONObject object = new JSONObject(data.string());
                            boolean curStatus = "open".equals(object.getString("status"));
                            SPUtils.setBoolean(Constants.SP_TEENAGER_MODE, curStatus);
                            if (preStatus != curStatus) {
                                Intent intent = getMainIntent(MainActivity.this);
                                intent.putExtra(SHOW_AD, true);
                                finish();
                                startActivity(intent);
                            }
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //上传关注视频浏览记录
    @SuppressLint("CheckResult")
    private void postAttentionVideoRecord() {
        if (UserManager.getInstance().isLoggedIn()) {
            Map<String, Object> requestMap = new HashMap<>();
            HistoryDatabase.Companion.getInstance().videoHistoryDao()
                    .getAttentionVideoRecord()
                    .flatMap((Function<List<String>, SingleSource<ResponseBody>>) strings -> {
                        requestMap.put("cache_video_ids", strings);
                        RequestBody body = ExtensionsKt.toRequestBody(requestMap);
                        return RetrofitManager.getInstance()
                                .getApi()
                                .postAttentionVideoRecord(UserManager.getInstance().getUserId(), body);
                    })
                    .subscribeOn(Schedulers.io())
                    .subscribe(new BiResponse<ResponseBody>() {
                        @Override
                        public void onSuccess(ResponseBody data) {
                            HistoryHelper.deleteAttentionVideoRecord();
                        }
                    });
        }
    }

    //查询到模拟器游戏表中逻辑删除的数据后，删除服务器中的记录
    @SuppressLint("CheckResult")
    private void deleteSimulatorGame() {
        SimulatorGameDao dao = AppDatabase.getInstance().simulatorGameDao();
        dao.getSimulatorGameByDeleted()
                .subscribeOn(Schedulers.io())
                .subscribe(new BiResponse<List<String>>() {
                    @Override
                    public void onSuccess(List<String> data) {
                        if (!data.isEmpty()) {
                            SimulatorGameManager.deleteSimulatorGames(data, () -> {
                                for (String id : data) {
                                    dao.deleteSimulatorGameById(id);
                                }
                                return null;
                            });
                        }
                    }
                });
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            int bottomTabPosition = savedInstanceState.getInt(CURRENT_PAGE, -1);
            if (bottomTabPosition != -1) {
                MainWrapperRepository.Companion.getInstance().sendSelectTabEvent(bottomTabPosition, -1);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == CommonConsts.SUGGEST_TYPE_REQUEST) {
            showKefuReportDialog();
        }
    }

    private void showKefuReportDialog() {
        // 只有是APP闪退反馈成功后弹出联系客服的弹窗
        String str = "您也可以联系客服进一步描述闪退的情况，如果您反馈的是新问题，即有机会获得红包奖励";
        DialogHelper.showCenterWarningDialog(MainActivity.this, "反馈成功", Html.fromHtml(str.substring(0, str.indexOf("红包奖励")) + "<font color='#FF0000'>红包奖励</font>"), "暂不", "联系客服",
                () -> {
                    if (ShareUtils.isQQClientAvailable(this)) {
                        DirectUtils.directToQqConversation(this, null);
                    } else {
                        toast("本机未安装QQ应用");
                    }
                    return null;
                }, () -> null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        CustomPageShareRepository.Companion.getInstance().onClear();
        AdDelegateHelper.INSTANCE.cancelSplashAd(this);

        handler.removeCallbacksAndMessages(null);
        releaseExoSourceCache();

        // 移除推送触发启动记录
        HaloApp.remove(Constants.PUSH_MESSAGE_ID);
        HaloApp.remove(Constants.PUSH_LINK_ENTITY);
    }

    /**
     * 由于ExoTransformer中拦截了{@link ExoSourceManager#release}方法,
     * 所以需要在app退出的时候手动release
     */
    private void releaseExoSourceCache() {
        Cache cache = ExoSourceManager.getCacheSingleInstance(HaloApp.getInstance().getApplication(), null);
        cache.release();
        try {
            Field cacheField = ExoSourceManager.class.getDeclaredField("mCache");
            cacheField.setAccessible(true);
            cacheField.set(null, null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示广告 (包括文本广告和开屏广告)
     */
    private void showAd() {
        if (!mShouldShowAd) {
            hideTextAd();
            hideSplashAd();
            return;
        }
        final StartupAdEntity textAd = AdHelper.getStartUp();
        if (textAd != null) {
            showTextAd(textAd);
            AppExecutor.getUiExecutor().executeWithDelay(() -> {
                hideTextAd();
                showSplashAd();
            }, 2000);
        } else {
            showSplashAd();
        }
    }

    /**
     * 显示冷启动开屏广告
     */
    private void showSplashAd() {
        if (AdDelegateHelper.INSTANCE.shouldShowStartUpAd(false)) {
            ViewGroup startAdContainer = findViewById(R.id.startAdContainer);
            ViewGroup sdkStartAdContainer = findViewById(R.id.sdkStartAdContainer);
            TextView sdkJumpBtn = findViewById(R.id.sdkJumpBtn);
            FrameLayout adsFl = findViewById(R.id.adsFl);
            View icpContainer = findViewById(R.id.sdkStartAdIcpContainer);
            if (icpContainer != null) {
                icpContainer.setOnClickListener((view) -> {
                    // consume click event
                });
            }
            int screenWidthInPx = DisplayUtils.getScreenWidth(this);
            int screenHeightInPx = DisplayUtils.getScreenHeight(this)
                    + DisplayUtils.getStatusBarHeight(this.getResources())
                    - ExtensionsKt.dip2px(112F);
            float screenWidthInDp = DisplayUtils.px2dip(this, screenWidthInPx);
            float screenHeightInDp = DisplayUtils.px2dip(this, screenHeightInPx);

            if (startAdContainer != null && sdkStartAdContainer != null && adsFl != null) {
                mCountdownMaxCount = AdDelegateHelper.INSTANCE.getSplashAdDisplayInterval();
                TextView jumpBtn = findViewById(R.id.jumpBtn);
                if (jumpBtn != null) {
                    jumpBtn.setText(getString(R.string.splash_jump, mCountdownMaxCount));
                }
                AdDelegateHelper.requestSplashAd(
                        this,
                        screenWidthInPx,
                        screenHeightInPx,
                        screenWidthInDp,
                        screenHeightInDp,
                        startAdContainer,
                        sdkStartAdContainer,
                        sdkJumpBtn,
                        adsFl,
                        (BaseHandler) mBaseHandler,
                        false,
                        () -> {
                            hideSplashAd();
                            return null;
                        }
                );
            } else {
                hideSplashAd();
            }
        } else {
            hideSplashAd();
        }
    }

    @Override
    protected void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == COUNTDOWN_AD || msg.what == COUNTDOWN_SDK_AD) {
            int maxCount;

            if (msg.what == COUNTDOWN_AD) {
                maxCount = mCountdownMaxCount;
            } else {
                maxCount = COUNTDOWN_SDK_MAX_COUNT;
            }

            // 读秒到一半的时候初始化 MainWrapperFragment
            if (mCountdownCount == maxCount / 2) {
                doInitMainFragment(mTempSavedInstanceState);
            }

            mCountdownCount++;

            if (maxCount < mCountdownCount) {
                AdDelegateHelper.INSTANCE.setShowingSplashAd(false);
                hideSplashAd();

                if (msg.what == COUNTDOWN_AD && msg.obj instanceof StartupAdEntity) {
                    StartupAdEntity ad = (StartupAdEntity) msg.obj;
                    if (!AdDelegateHelper.INSTANCE.isOwnerSplashAdShown()) {
                        com.gh.common.util.NewFlatLogUtils.logSplashAdFail(ad.getId(), "广告加载超时");
                    }
                    AdDelegateHelper.INSTANCE.setOwnerSplashAdShown(false);
                    LinkEntity linkEntity = ad.getJump();
                    SensorsBridge.trackEvent(
                            "SplashAdOwnSkip",
                            "splash_ad_id",
                            ad.getId(),
                            "link_type",
                            linkEntity.getType(),
                            "link_id",
                            linkEntity.getLink(),
                            "link_text",
                            linkEntity.getText());
                } else if (msg.what == COUNTDOWN_SDK_AD) {
                    SPUtils.setLong(Constants.SP_LAST_SPLASH_AD_SHOW_TIME, System.currentTimeMillis());
                }
            } else {
                if (msg.what == COUNTDOWN_AD) {
                    TextView jumpBtn = findViewById(R.id.jumpBtn);
                    if (jumpBtn != null) {
                        jumpBtn.setText(getString(R.string.splash_jump, maxCount - mCountdownCount));
                    }
                    Message newMsg = Message.obtain();
                    newMsg.what = COUNTDOWN_AD;
                    newMsg.obj = msg.obj;
                    mBaseHandler.sendMessageDelayed(newMsg, 1000);
                } else {
                    TextView jumpBtn = findViewById(R.id.sdkJumpBtn);
                    if (jumpBtn != null) {
                        jumpBtn.setText(getString(R.string.splash_jump, maxCount - mCountdownCount));
                    }
                    mBaseHandler.sendEmptyMessageDelayed(COUNTDOWN_SDK_AD, 1000);
                }
            }
        }
    }

    /**
     * 隐藏开屏文案
     */
    private void hideTextAd() {
        View maskContainer = findViewById(R.id.maskContainer);
        if (maskContainer != null) {
            maskContainer.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(maskContainer, true);
        }
    }

    /**
     * 隐藏开屏广告
     */
    private void hideSplashAd() {
        mShouldShowAd = false;
        getIntent().putExtra(SHOW_AD, false);
        View startAdContainer = findViewById(R.id.startAdContainer);
        if (startAdContainer != null) {
            // 如果有播放开屏视频广告，需要及时释放
            SplashAdVideoView adVideoView = startAdContainer.findViewById(R.id.ad_video);
            if (adVideoView != null) {
                adVideoView.clearAll();
            }
            startAdContainer.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(startAdContainer, true);
        }
        View startSdkAdContainer = findViewById(R.id.sdkStartAdContainer);
        if (startSdkAdContainer != null) {
            startSdkAdContainer.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(startSdkAdContainer, true);
            AdDelegateHelper.INSTANCE.cancelSplashAd(this);
        }
        TextView jumpBtn = findViewById(R.id.sdkJumpBtn);
        if (jumpBtn != null) {
            jumpBtn.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(jumpBtn, true);
        }
        View startSdkAdIcpContainer = findViewById(R.id.sdkStartAdIcpContainer);
        if (startSdkAdIcpContainer != null) {
            startSdkAdIcpContainer.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(startSdkAdIcpContainer, true);
        }

        onAdHidden();
    }

    private void onAdHidden() {
        doInitMainFragment(mTempSavedInstanceState);
        // 通知全局弹窗可以进行显示
        AppExecutor.getUiExecutor().execute(GlobalPriorityChainHelper.INSTANCE::start);
    }

    /**
     * 显示文本广告
     */
    private void showTextAd(StartupAdEntity ad) {
        TextView adContentTv = findViewById(R.id.adContentTv);
        View containerView = findViewById(R.id.maskContainer);
        containerView.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            containerView.setElevation(500F);
        }
        containerView.setOnClickListener(v -> {
            // 拦截点击事件，避免传递到下面的页面
        });
        adContentTv.setText(ad.getDesc());
        adContentTv.setVisibility(View.VISIBLE);
        if (ad.getButton()) {
            View adBtn = findViewById(R.id.adBtn);
            adBtn.setOnClickListener(v -> {
                DirectUtils.directToLinkPage(this, ad.getJump(), "(启动广告)", "", "开屏文案");
                LogUtils.logStartAd("click_watch_start_ads", ad);
            });
            adBtn.setVisibility(View.VISIBLE);
            LogUtils.logStartAd("watch_start_ads", ad);
        } else {
            LogUtils.logStartAd("start_ads", ad);
        }
    }

    @NonNull
    public static Intent getMainIntent(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return intent;
    }

    private void doSkip() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            getIntent().getExtras().putBoolean(EntranceConsts.KEY_REQUIRE_REDIRECT, false);
        }
        handler.postDelayed(() -> {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                String to = bundle.getString(KEY_TO);
                if (!TextUtils.isEmpty(to)) {
                    Class<?> clazz = ClassUtils.forName(to);
                    if (clazz != null) {
                        String entrance = bundle.getString(EntranceConsts.KEY_ENTRANCE);
                        if (TextUtils.isEmpty(entrance) || !entrance.startsWith("(") || !entrance.endsWith(")")) {
                            bundle.putString(EntranceConsts.KEY_ENTRANCE, "(插件跳转)");
                        }

                        String packageName = bundle.getString("packageName");
                        if (packageName != null) {
                            bundle.putInt(BaseFragment_ViewPager.ARGS_INDEX, 1);
                        }

                        if (ToolbarFragment.class.isAssignableFrom(clazz)) {
                            ToolBarActivity.startFragment(MainActivity.this, (Class<? extends ToolbarFragment>) clazz, bundle);
                        } else {
                            Intent skipIntent = new Intent(MainActivity.this, clazz);
                            skipIntent.putExtras(bundle);
                            AvoidOnResultManager.Companion.getInstance(this)
                                    .startForResult(skipIntent, (resultCode, data) -> {
                                        Bundle nextToBundle = getIntent().getBundleExtra(KEY_NEXT_TO);
                                        if (nextToBundle != null) {
                                            EntranceUtils.jumpActivity(this, nextToBundle);
                                        }
                                    });
                        }
                    } else {
                        // 使用光环进行二次跳转的页面会经过这里
                        switch (to) {
                            case HOST_QQ:
                                DirectUtils.directToQqConversation(this, bundle.getString(KEY_DATA));
                                break;
                            case HOST_QQ_GROUP:
                                DirectUtils.directToQqGroup(this, bundle.getString(KEY_DATA));
                                break;
                            case HOST_WEB:
                                String url = bundle.getString(KEY_DATA) == null ? "" : bundle.getString(KEY_DATA);
                                if ("internal".equals(bundle.getString(KEY_TYPE))) {
                                    DirectUtils.directToWebView(this, url, ENTRANCE_BROWSER);
                                } else {
                                    DirectUtils.directToExternalBrowser(this, url);
                                }
                                break;
                            case HOST_LAUNCH_SIMULATOR_GAME:
                                String json = getIntent().getStringExtra(EntranceConsts.KEY_GAME);
                                try {
                                    GameEntity gameEntity = GsonUtils.getGson().fromJson(json, new TypeToken<GameEntity>() {
                                    }.getType());
                                    if (gameEntity != null) {
                                        String apkUrl = gameEntity.getApk().isEmpty() ? "" : gameEntity.getApk().get(0).getUrl();
                                        DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(apkUrl);
                                        if (downloadEntity != null) {
                                            File file = new File(downloadEntity.getPath());
                                            if (!file.exists()) {
                                                ToastUtils.showToast("文件已被删除，无法启动");
                                                return;
                                            }

                                            SimulatorGameManager.launchSimulatorGame(downloadEntity, gameEntity);
                                        }
                                    }
                                } catch (JsonSyntaxException exception) {
                                    exception.printStackTrace();
                                    toast("模拟器游戏启动失败，请联系客服反馈相关信息");
                                    SentryHelper.INSTANCE.onEvent(
                                            "SIMULATOR_SHORTCUT_LAUNCH_ERROR",
                                            "error_digest",
                                            exception.getLocalizedMessage()
                                    );
                                }
                                break;
                            case HOST_LAUNCH_VM_GAME:
                                String gamePackageName = getIntent().getStringExtra(EntranceConsts.KEY_GAME_PKG);
                                if (TextUtils.isEmpty(gamePackageName)) {
                                    ToastUtils.showToast("游戏启动失败，请联系客服反馈相关信息");
                                    return;
                                }

                                VHelper.INSTANCE.logLaunchButtonClicked(
                                        gamePackageName,
                                        null,
                                        null,
                                        null,
                                        "桌面快捷图标"
                                );

                                ToastUtils.showToast("游戏启动中，请稍后~");
                                handler.postDelayed(() -> {
                                    if (VHelper.isInnerInstalled(gamePackageName)) {
                                        launchGame(gamePackageName).invoke();
                                    } else {
                                        VHelper.postOnInitialized(launchGame(gamePackageName));
                                    }
                                }, 500);
                                break;
                            case KEY_MARKET_DETAILS:
                                redirectGameDetail(bundle.getString(KEY_DATA));
                                break;
                        }
                    }
                }

                Utils.log(bundle);
                if (!TextUtils.isEmpty(bundle.getString(EntranceConsts.KEY_TYPE, ""))) {
                    MainWrapperRepository.Companion.getInstance().sendSelectTabEvent(bundle.getString(EntranceConsts.KEY_TYPE));
                }
            }
        }, 500);
    }

    /**
     * 重定向至 TheRouter 配置的页面
     */
    private void doRedirect(String path) {
        if (getIntent().getExtras() != null) {
            // 更新 intent 数据，避免页面重建重新跳转
            getIntent().getExtras().putString(EntranceConsts.KEY_THE_ROUTER_PATH, "");
            AppExecutor.getUiExecutor().executeWithDelay(() -> {
                TheRouter.build(path).navigation(this);
            }, 500L);
        }
    }

    @NonNull
    private Function0<Unit> launchGame(String gamePackageName) {
        return () -> {
            if (!VHelper.isInnerInstalled(gamePackageName) && !VHelper.isInstalled(gamePackageName)) {
                ToastUtils.showToast("应用已被卸载！");
            } else {
                VHelper.shortcutLaunch();
                VHelper.launch(this, gamePackageName, false, true);
            }
            return null;
        };
    }

    /**
     * 应用跳转
     */
    private void redirectGameDetail(String packageName) {
        String filterQuery = UrlFilterUtils.getFilterQuery("package", packageName, "type", "package_redirect");
        RetrofitManager.getInstance().getApi().loadGameDataByPackageName(filterQuery)
                .compose(observableToMain())
                .subscribe(new Response<List<GameEntity>>() {
                    @Override
                    public void onResponse(@Nullable List<GameEntity> response) {
                        super.onResponse(response);
                        if (response == null || response.isEmpty()) return;
                        if (response.size() > 1) {
                            startActivity(PackageSkipActivity.getIntent(MainActivity.this, response));
                            LogUtils.uploadPackageSkip("external_jump", "进入展示页", "", "");
                        } else {
                            GameDetailActivity.startGameDetailActivity(MainActivity.this, response.get(0), "应用跳转", null);
                            LogUtils.uploadPackageSkip("external_jump", "进入游戏详情", response.get(0).getId(), response.get(0).getName());
                        }
                    }

                    @Override
                    public void onFailure(@Nullable HttpException e) {
                        super.onFailure(e);
                        try {
                            ErrorHelper.handleErrorWithCustomizedHandler(MainActivity.this, e.response().errorBody().string(), false, "", "", "内容实名", null, null, code -> {
                                if (code == 404001) {
                                    if (mShouldShowAd) {
                                        AppExecutor.getUiExecutor().executeWithDelay(() -> {
                                            toast("抱歉，暂未找到相关内容");
                                        }, 1000);
                                    } else {
                                        toast("抱歉，暂未找到相关内容");
                                    }
                                    return true;
                                }
                                return false;
                            });
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0
                && mMainWrapperFragment != null
                && !mMainWrapperFragment.onHandleBackPressed()) {
            DownloadEntity downloadEntity = null;
            for (DownloadEntity entity : DownloadManager.getInstance().getAllDownloadEntityExcludeSilentTask()) {
                if (entity.getStatus().equals(DownloadStatus.done)) {
                    if (PackageUtils.isInstalled(getApplicationContext(), entity.getPackageName())
                            && (!entity.isPlugin()
                            || PackageUtils.isSignedByGh(getApplicationContext(), entity.getPackageName()))) {
                        continue;
                    }
                    if (ExtensionsKt.isSimulatorGame(entity)) continue;
                    if (downloadEntity == null) {
                        downloadEntity = entity;
                    } else if (entity.getEnd() > downloadEntity.getEnd()) {
                        downloadEntity = entity;
                    }
                }
            }
            if (downloadEntity != null) {
                String msg;
                if (downloadEntity.isPlugin()) {
                    msg = "《" + downloadEntity.getName() + "-"
                            + PlatformUtils.getInstance(getApplicationContext()).getPlatformName(downloadEntity.getPlatform())
                            + "》已下载完但还未安装，是否立即安装？";
                } else {
                    msg = "《" + downloadEntity.getName() + "》已下载完但还未安装，是否立即安装？";
                }
                DownloadEntity finalDownloadEntity = downloadEntity;
                DialogHelper.showCenterWarningDialog(this,
                        "提示", msg,
                        "直接退出",
                        "立即安装",
                        () -> {
                            handler.postDelayed(() -> {
                                NewFlatLogUtils.INSTANCE.logGameInstall(
                                        finalDownloadEntity.getGameId(),
                                        finalDownloadEntity.getName(),
                                        "主动安装"
                                );
                                SensorsBridge.trackInstallGameClick(
                                        finalDownloadEntity.getGameId(),
                                        finalDownloadEntity.getName(),
                                        "主动安装",
                                        "true".equals(ExtensionsKt.getMetaExtra(finalDownloadEntity, Constants.DSP_GAME)),
                                        ExtensionsKt.getMetaExtra(finalDownloadEntity, Constants.DSP_AD_ID)
                                );
                                PackageInstaller.install(MainActivity.this, finalDownloadEntity);
                            }, 200);
                            return null;
                        },
                        () -> {
                            finish();
                            return null;
                        });
                return true;
            }
            System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
            mHits[mHits.length - 1] = SystemClock.uptimeMillis();
            if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
                finish();
            } else {
                toast("再按一次就退出光环助手了哦");
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected boolean handleBackPressed() {
        return true;
    }

    @Override
    protected void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.clear();
        if (mMainWrapperFragment != null) {
            outState.putInt(CURRENT_PAGE, mMainWrapperFragment.getCurrentItem());
        }
    }

    @Override
    protected boolean preventRecreateFragmentByFragmentManager() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        if (mShouldShowAd) {
            return R.layout.activity_main;
        } else {
            return com.lightgame.R.layout.layout_wrapper_activity;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // 跳转至其它页面
        if (getIntent() != null
                && getIntent().getExtras() != null
                && getIntent().getBooleanExtra(EntranceConsts.KEY_REQUIRE_REDIRECT, false)) {
            doSkip();
        }
    }

    // 连接上网络事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (Config.getSettings() == null) {
                Config.getGhzsSettings();
            } else if (Config.getVSettingEntity() == null) {
                Config.refreshVSettingEntity();
            } else if (Config.getVNewSettingEntity() == null) {
                Config.getNewSetting();
            }

            mPackageViewModel.checkData();
            deleteSimulatorGame();
        }
    }

    // 接收登录和登出更新事件统计的 Meta
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        boolean isLoginEvent = reuse.getType().equals(LOGIN_TAG);
        if (isLoginEvent || reuse.getType().equals(LOGOUT_TAG)) {
            MetaUtil.INSTANCE.refreshMeta();
            VHelper.INSTANCE.updateAuthorizeInfo(isLoginEvent);
        }
    }

    @Override
    public String getActivityNameInChinese() {
        return "游戏首页";
    }

    //需要提前初始化微博sdk，否则第一次分享或授权登录会失败
    private void initWBSDK() {
        IWBAPI mWBAPI = WBAPIFactory.createWBAPI(this);
        mWBAPI.registerApp(this, new AuthInfo(this, Config.WEIBO_APPKEY, "http://www.sina.com", WEIBO_SCOPE));
    }

    /**
     * 重新触发 XAPK 安装流程
     * 因为 Android 12 起授予应用安装未知应用权限以后不触发进程重启，导致应用一直无法读写 android/data 目录
     * 所以这里再手动重启应用进程时再触发一回安装
     */
    private void resumeXapkInstallIfNeeded() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            String xapkUrl = SPUtils.getString(Constants.SP_XAPK_URL);
            if (!TextUtils.isEmpty(xapkUrl)) {
                DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(xapkUrl);
                if (downloadEntity != null) {
                    NewFlatLogUtils.INSTANCE.logGameInstall(
                            downloadEntity.getGameId(),
                            downloadEntity.getName(),
                            "自动安装"
                    );
                    SensorsBridge.trackInstallGameClick(
                            downloadEntity.getGameId(),
                            downloadEntity.getName(),
                            "自动安装",
                            "true".equals(ExtensionsKt.getMetaExtra(downloadEntity, Constants.DSP_GAME)),
                            ExtensionsKt.getMetaExtra(downloadEntity, Constants.DSP_AD_ID)
                    );
                    PackageInstaller.install(this, downloadEntity, false, false);
                }
            }
            SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
            SPUtils.setString(Constants.SP_XAPK_URL, "");
        }
    }

    @Override
    protected boolean isAutoResetViewBackgroundEnabled() {
        return true;
    }

    @Override
    protected void updateStaticViewBackground(View view) {
        ArrayList<Integer> blackList = new ArrayList<>();
        blackList.add(R.id.tabLayout);
        blackList.add(R.id.appbar);
        blackList.add(R.id.communityHomeContainer);
        blackList.add(com.lightgame.R.id.lightgame_tab_container);
        blackList.add(R.id.darkModeIv);
        blackList.add(R.id.myGameTv);
        blackList.add(R.id.myGameCollectionTv);
        blackList.add(R.id.myPostTv);
        blackList.add(R.id.historyTv);
        blackList.add(R.id.myCollectionTv);
        blackList.add(R.id.searchTv);
        blackList.add(R.id.subject_tab);
        updateStaticView(view, blackList);

        View communityHomeWrapper = view.findViewById(R.id.communityHomeContainer);
        if (communityHomeWrapper instanceof ConstraintLayout) {
            for (int i = 0; i < ((ConstraintLayout) communityHomeWrapper).getChildCount(); i++) {
                View child = ((ConstraintLayout) communityHomeWrapper).getChildAt(i);
                updateStaticView(child, new ArrayList<>());
            }
        }
    }

    @Override
    public void initPageLevel(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.getParcelable(PageLevelManager.KEY_PAGE_LEVEL) != null) {
                mPageLevel = savedInstanceState.getParcelable(PageLevelManager.KEY_PAGE_LEVEL);
            }
        }

        if (mPageLevel == null) {
            mPageLevel = new PageLevel(
                    PageLevel.TYPE_T,
                    -1,
                    -1,
                    new HashMap<>(),
                    -1,
                    null);
        }

        PageLevelManager.INSTANCE.setCurrentPageLevel(mPageLevel);
    }


    @Override
    public Pair<String, String> getBusinessId() {
        if (mMainWrapperFragment != null) {
            return mMainWrapperFragment.getBusinessId();
        }
        return super.getBusinessId();
    }
}
