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_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.fragment.MainWrapperFragment.INDEX_PERSONAL;
import static com.gh.gamecenter.login.utils.LoginHelper.WEIBO_SCOPE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
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.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;

import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.common.DefaultUrlHandler;
import com.gh.common.constant.Config;
import com.gh.common.exposure.ExposureEvent;
import com.gh.common.exposure.ExposureManager;
import com.gh.common.exposure.ExposureSource;
import com.gh.common.exposure.ExposureType;
import com.gh.common.history.HistoryDatabase;
import com.gh.common.history.HistoryHelper;
import com.gh.common.repository.ReservationRepository;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.util.ActivationHelper;
import com.gh.common.util.AdHelper;
import com.gh.common.util.CertificationSwitchHelper;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DeviceTokenUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DirectUtils;
import com.gh.common.util.EntranceUtils;
import com.gh.common.util.ErrorHelper;
import com.gh.common.util.HomePluggableHelper;
import com.gh.common.util.LogUtils;
import com.gh.common.util.LunchType;
import com.gh.common.util.NewFlatLogUtils;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
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.Constants;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.entity.LinkEntity;
import com.gh.gamecenter.common.entity.NotificationUgc;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.retrofit.BiResponse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.DeviceUtils;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.NotificationHelper;
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.MtaHelper;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.SentryHelper;
import com.gh.gamecenter.core.utils.TimeUtils;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.download.DownloadFragment;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.InnerMetaInfoEntity;
import com.gh.gamecenter.entity.StartupAdEntity;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.eventbus.EBSkip;
import com.gh.gamecenter.fragment.MainWrapperFragment;
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.manager.DataCollectionManager;
import com.gh.gamecenter.manager.UpdateManager;
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.suggest.SuggestSelectFragment;
import com.gh.gamecenter.suggest.SuggestType;
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.download.FileUtils;
import com.lightgame.utils.AppManager;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

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

public class MainActivity extends BaseActivity {

    public final static String EB_SKIP_MAIN = "MainActivity";
    public final static String SWITCH_TO_COMMUNITY = "switch_to_community";
    public final static String SWITCH_TO_VIDEO = "switch_to_video";
    public final static String SHOW_AD = "show_ad";
    private final static int COUNTDOWN_AD = 100;
    private final static int countdownMaxCount = 3;
    private int countdownCount = 0;

    private final static String CURRENT_PAGE = "current_page";

    private PackageViewModel mPackageViewModel;

    private MainWrapperFragment mMainWrapperFragment;

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

    public static boolean isNewFirstLaunch;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        showAd = getIntent().getBooleanExtra(SHOW_AD, false) && savedInstanceState == null;

        HaloApp.getInstance().initFresco();
        HaloApp.getInstance().isAlreadyUpAndRunning = true;

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

        Fragment fragmentFromFM = getSupportFragmentManager().findFragmentById(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);

        mSp = PreferenceManager.getDefaultSharedPreferences(this);

        isNewFirstLaunch = mSp.getBoolean("isNewFirstLaunchV" + PackageUtils.getGhVersionName(), true);
        if (isNewFirstLaunch) {
            final LunchType lunchType = DeviceTokenUtils.getLaunchType(false);
            // 延时两秒提交，避免提交时还没获取到 GID/OAID
            AppExecutor.getUiExecutor().executeWithDelay(() -> {
                if (!this.isFinishing()) {
                    LogUtils.uploadDevice(lunchType);
                    ActivationHelper.sendActivationInfo();
                    // 第一次打开App删除模拟器游戏记录（不包括更新版本）
                    if (HaloApp.getInstance().isBrandNewInstall) {
                        getTeenagerMode();
                        SimulatorGameManager.deleteAllSimulatorGame();
                    }
                }
            }, 2000L);
            getPluginUpdate();
            mSp.edit().putBoolean("isNewFirstLaunchV" + PackageUtils.getGhVersionName(), false).apply();

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

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

            checkDevice();  // 根据设备信息判断用户是否是新用户
        }

        // 若 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.crash, "APP闪退：", 100);
                            MtaHelper.onEventWithBasicDeviceInfo(
                                    "闪退弹窗",
                                    "玩家操作", "点击反馈");
                            return null;
                        });
            } else {
                DialogHelper.showCenterWarningDialog(this, "发生闪退", "光环助手刚刚发生了闪退，马上反馈以帮助我们更好地修复问题？（只需简单描述你刚才的操作）"
                        , "暂不", "马上反馈",
                        () -> {
                            DirectUtils.directToSuggestion(MainActivity.this, SuggestType.crash, "APP闪退：", 100);
                            MtaHelper.onEventWithBasicDeviceInfo(
                                    "闪退弹窗",
                                    "玩家操作", "点击反馈");
                            return null;
                        },
                        () -> {
                            MtaHelper.onEventWithBasicDeviceInfo(
                                    "闪退弹窗",
                                    "玩家操作", "点击关闭");
                            return null;
                        });
            }
        }

//        checkTinkerPath(); //　看情况是否需要显示补丁弹窗

        // 必须放在这里，否则会导致获取 baseActivity 不是本应用包名
        DownloadManager.getInstance().initDownloadService();

        ReservationRepository.refreshReservations();

        if (getIntent().getBooleanExtra(SWITCH_TO_VIDEO, false)) {
            handler.postDelayed(() -> mMainWrapperFragment.setCurrentItem(2), 800);
        }

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

        if (BuildConfig.DEBUG) {
            handler.postDelayed(() -> {
                EntranceUtils.jumpShortcut(this);
            }, 500);
        }

        if (showAd) {
            observeStartUp();
        } else {
            checkDialog();
        }

        // 耗时操作
        AppExecutor.getIoExecutor().execute(() -> {
            // 上传数据
            DataCollectionManager.getInstance().upload();
            // 获取默认配置

            if (Config.getSettings() == null) {
                Config.getGhzsSettings();
            }

            // 初始化PlatformUtils
            PlatformUtils.getInstance(getApplicationContext());
            HomePluggableHelper.activationFilterData();

            // 启动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, "");

        postAttentionVideoRecord();
        deleteSimulatorGame();

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

        QuickLoginHelper.getPhoneInfo();
        WechatBindHelper.getWechatConfig(null);
        initWBSDK();
        CertificationSwitchHelper.getCertificationSwitch();
    }

    @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(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            int currentPageIndex = savedInstanceState.getInt(CURRENT_PAGE, -1);
            if (currentPageIndex >= 0) {
                EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, currentPageIndex));
                if (currentPageIndex == MainWrapperFragment.INDEX_VIDEO) {
                    DisplayUtils.setLightStatusBar(this, false);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == SuggestSelectFragment.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();

        handler.removeCallbacksAndMessages(null);
        releaseExoSourceCache();
    }

    /**
     * 由于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 observeStartUp() {
        if (!showAd) {
            hideStartUp();
            hideStartUpAd();
            return;
        }
        final StartupAdEntity startUp = AdHelper.getStartUp();
        if (startUp != null) {
            showStartUp(startUp);
            AppExecutor.getUiExecutor().executeWithDelay(() -> {
                hideStartUp();
                observeStartUpAd();
            }, 2000);
        } else {
            observeStartUpAd();
        }
    }

    private void observeStartUpAd() {
        final StartupAdEntity startUpAd = AdHelper.getStartUpAd();
        if (startUpAd != null && !TextUtils.isEmpty(startUpAd.getImg())) {
            final String showedTodayTimestamp = SPUtils.getString(Constants.SP_STARTUP_AD_TIMESTAMP, "");
            final String rule = startUpAd.getRule();
            switch (rule) {
                case "each":
                    showStartUpAd(startUpAd);
                    break;
                case "once":
                    if (TextUtils.isEmpty(showedTodayTimestamp)
                            || !showedTodayTimestamp.contains(startUpAd.getId())) {
                        showStartUpAd(startUpAd);
                    } else {
                        hideStartUpAd();
                    }
                    break;
                case "everyday":
                    final String today = TimeUtils.getToday();
                    if (TextUtils.isEmpty(showedTodayTimestamp)
                            || !showedTodayTimestamp.contains(today)
                            || !showedTodayTimestamp.contains(startUpAd.getId())) {
                        showStartUpAd(startUpAd);
                    } else {
                        hideStartUpAd();
                    }
                    break;
                default:
                    hideStartUpAd();
                    break;
            }
            SPUtils.setString(Constants.SP_STARTUP_AD_TIMESTAMP, startUpAd.getId() + TimeUtils.getToday());
        } else {
            hideStartUpAd();
        }
    }

    @Override
    protected void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == COUNTDOWN_AD) {
            countdownCount++;
            TextView jumpBtn = findViewById(R.id.jumpBtn);
            jumpBtn.setText(String.format(Locale.CHINA, "跳过 %d", countdownMaxCount - countdownCount));
            if (countdownMaxCount < countdownCount) {
                hideStartUpAd();
            } else {
                mBaseHandler.sendEmptyMessageDelayed(COUNTDOWN_AD, 1000);
            }
        }
    }

    private void hideStartUp() {
        View maskContainer = findViewById(R.id.maskContainer);
        if (maskContainer != null) {
            maskContainer.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(maskContainer);
        }
    }

    private void hideStartUpAd() {
        showAd = false;
        getIntent().putExtra(SHOW_AD, false);
        View startAdContainer = findViewById(R.id.startAdContainer);
        if (startAdContainer != null) {
            startAdContainer.setVisibility(View.GONE);
            ExtensionsKt.removeFromParent(startAdContainer);
        }
        checkDialog();
    }

    private void checkDialog() {
        // 检查通知权限
        checkNotificationPermission();
        // 检查助手更新
        AppExecutor.getIoExecutor().execute(() -> {
            UpdateManager updateManager = UpdateManager.getInstance(this);
            updateManager.checkUpdate(true, null);
            updateManager.setDismissCallback(mMainWrapperFragment::getDialog);
        });
    }

    private void showStartUpAd(StartupAdEntity ad) {
        View startAdContainer = findViewById(R.id.startAdContainer);
        View jumpBtn = findViewById(R.id.jumpBtn);
        TextView jumpDetailBtn = findViewById(R.id.jumpDetailBtn);
        SimpleDraweeView adImage = findViewById(R.id.adImage);
        startAdContainer.setVisibility(View.VISIBLE);
        jumpDetailBtn.setText(ad.getDesc());
        ExtensionsKt.setDrawableEnd(jumpDetailBtn, VectorDrawableCompat.create(getResources(), R.drawable.ic_startup_ad_arrow, null), null, null);
        ImageUtils.display(adImage, ad.getImg());
        startAdContainer.setOnClickListener(v -> {
            // do nothing 只是为了点击拦截事件，避免传递到下面的页面
        });
        jumpBtn.setOnClickListener(v -> {
            mBaseHandler.removeMessages(COUNTDOWN_AD);
            hideStartUpAd();
            LinkEntity linkEntity = ad.getJump();
            NewFlatLogUtils.logOpenScreenAdSkip(
                    ad.getId(),
                    linkEntity.getText() != null ? linkEntity.getText() : "",
                    linkEntity.getType() != null ? linkEntity.getType() : "",
                    linkEntity.getLink() != null ? linkEntity.getLink() : ""
            );
        });
        List<ExposureSource> sources = new ArrayList<>();
        sources.add(new ExposureSource("开屏广告", ad.getId()));
        final ExposureEvent event = ExposureEvent.createEvent(null, sources, null, ExposureType.EXPOSURE);
        ExposureManager.INSTANCE.log(event);
        if (ad.getButton()) {
            jumpDetailBtn.setOnClickListener(v -> {
                DirectUtils.directToLinkPage(this, ad.getJump(), "(启动广告)", "", event);
                v.postDelayed(() -> {
                    mBaseHandler.removeMessages(COUNTDOWN_AD);
                    hideStartUpAd();
                }, 1000);
            });
            jumpDetailBtn.setVisibility(View.VISIBLE);
            LogUtils.logStartAd("watch_start_ads", ad);
        } else {
            LogUtils.logStartAd("start_ads", ad);
        }
        mBaseHandler.sendEmptyMessageDelayed(COUNTDOWN_AD, 1000);
    }

    private void showStartUp(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 -> {
            // do nothing 只是为了点击拦截事件，避免传递到下面的页面
        });
        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);
//                            startActivity(skipIntent);
                            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());
                                    DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(gameEntity.getApk().get(0).getUrl());
                                    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 KEY_MARKET_DETAILS:
                                redirectGameDetail(bundle.getString(KEY_DATA));
                                break;
                        }
                    }
                }

                Utils.log(bundle);
                if (bundle.getInt(EntranceConsts.KEY_POSITION) != -1) {
                    EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, bundle.getInt(EntranceConsts.KEY_POSITION)));
                }
            }
        }, 500);
    }

    /**
     * 应用跳转
     */
    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, new Function1<Integer, Boolean>() {
                                @Override
                                public Boolean invoke(Integer code) {
                                    if (code == 404001) {
                                        if (showAd) {
                                            AppExecutor.getUiExecutor().executeWithDelay(() -> {
                                                toast("抱歉，暂未找到相关内容");
                                            }, 1000);
                                        } else {
                                            toast("抱歉，暂未找到相关内容");
                                        }
                                        LogUtils.uploadPackageSkip("external_jump", "进入游戏库", "", "");
                                        EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, MainWrapperFragment.INDEX_GAME));
                                        return true;
                                    }
                                    return false;
                                }
                            });
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                });
    }

    private void checkNotificationPermission() {
        // 仅登录后再启动光环时请求一次权限
        if (UserManager.getInstance().isLoggedIn()) {
            NotificationHelper.showNotificationHintDialog(NotificationUgc.LOGIN, null);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && !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(() -> 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
    public void finish() {
        // 上传数据
        DataCollectionManager.getInstance().statClickData();
        super.finish();
    }

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

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

    @Override
    protected int getLayoutId() {
        if (showAd) {
            return R.layout.activity_main;
        } else {
            return 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();
        }

        if (getIntent().getBooleanExtra(SWITCH_TO_VIDEO, false)) {
            mMainWrapperFragment.setCurrentItem(2);
        }
    }


    private void checkTinkerPath() {
//        CommonDebug.logMethodWithParams(this, TinkerManager.getTinkerId(), TinkerManager.getNewTinkerId());
//        CommonDebug.logMethodWithParams(this, CrashReport.getAppVer(), CrashReport.getAppID(), CrashReport.getAppChannel(), CrashReport.getSdkExtraData());
//
//        // 1.（母包）首次启动，tinkerId不为空，newTinkerId(patchTinkerId)应该是空的
//        // 2. 补丁包启动，tinkerId和之前一致，但newTinkerId不一致
//        // 2.1 显示更新信息弹窗，记录tinkerId+newTinkerId
//        // 2.1.1 若tinkerId一致，但newTinkerId不一致才能认为是一次补丁更新
//
//        String tinkerId = TinkerManager.getTinkerId();
//        String newTinkerId = TinkerManager.getNewTinkerId();
//
//        if (TextUtils.isEmpty(newTinkerId)) {
//            //这是一个新的母包，没有任何补丁信息
//            return;
//        }
//
//        final Gson gson = new Gson();
//
//        Type type = new TypeToken<HashMap<String, Set<String>>>() {
//        }.getType();
//
//        final Map<String, Set<String>> tinkerIdMap;
//        final String tinkerMapJson = mSp.getString(Config.PATCHES, "");
//        if (!TextUtils.isEmpty(tinkerMapJson)) {
//            tinkerIdMap = gson.fromJson(tinkerMapJson, type);
//        } else {
//            tinkerIdMap = new HashMap<>();
//        }
//
//        Set<String> tinkerIdSet = tinkerIdMap.get(tinkerId);
//        if (tinkerIdSet == null) {
//            tinkerIdSet = new HashSet<>();
//            tinkerIdMap.put(tinkerId, tinkerIdSet);
//        }
//
//        // 有新的补丁，没有显示过
//        if (!tinkerIdSet.contains(newTinkerId)) {
//            tinkerIdSet.add(newTinkerId);
//
//            final Dialog dialog = new Dialog(this, R.style.GhAlertDialog);
//
//            View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_alert, null);
//            TextView contentTv = contentView.findViewById(R.id.dialog_content);
//            TextView titleTv = contentView.findViewById(R.id.dialog_title);
//            TextView negativeTv = contentView.findViewById(R.id.dialog_negative);
//            TextView positiveTv = contentView.findViewById(R.id.dialog_positive);
//
//            titleTv.setText("补丁更新成功");
//            contentTv.setText(("光环助手已成功更新到V" + PackageUtils.getVersionName() + "-" + newTinkerId));
//            positiveTv.setText("知道了");
//            negativeTv.setText(null);
//
//            negativeTv.setOnClickListener(view -> dialog.dismiss());
//
//            positiveTv.setOnClickListener(view -> dialog.dismiss());
//            dialog.setOnDismissListener(dialog1 -> mSp.edit().putString(Config.PATCHES, gson.toJson(tinkerIdMap)).apply());
//
//            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//            dialog.setContentView(contentView);
//            dialog.show();
//        }
    }

    private void checkDevice() {
        String content = DeviceUtils.getUserDevice(MainActivity.this).toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), content);
        RetrofitManager.getInstance().getApi().checkDevice(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<ResponseBody>() {
                    @Override
                    public void onResponse(ResponseBody response) {
                        super.onResponse(response);
                        try {
                            String string = response.string();
                            JSONObject object = new JSONObject(string);
                            String deviceId = object.getString("device_id");
                            if (!TextUtils.isEmpty(deviceId)) {
                                oldUserSkip(deviceId);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void oldUserSkip(String deviceId) {
        mSp.edit().putString("syncDeviceID", deviceId).apply();
        DialogUtils.showForceDialog(MainActivity.this, "数据同步提醒"
                , "系统检测到你是光环助手的老用户，为了避免数据丢失，请尽快登录"
                , "前往登录", "残忍拒绝", () -> EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, INDEX_PERSONAL)), null);
    }

    // 获取META-INF中的plugin_update 文件，判断是否从游戏插件中下载的app，是则获取游戏id，启动游戏更新，下载该游戏
    private void getPluginUpdate() {
        AppExecutor.getIoExecutor().execute(() -> {
            ApplicationInfo appinfo = getApplicationInfo();
            String sourceDir = appinfo.sourceDir;
            ZipFile zipfile = null;

            try {
                zipfile = new ZipFile(sourceDir);
                Enumeration<?> entries = zipfile.entries();

                while (entries.hasMoreElements()) {
                    ZipEntry entry = ((ZipEntry) entries.nextElement());
                    String entryName = entry.getName();
                    if (entryName.contains("gh_assist")) {
                        String packageName = entryName.substring(entryName.lastIndexOf("_") + 1);
                        startActivity(DownloadManagerActivity.getDownloadMangerIntent(MainActivity.this,
                                packageName, DownloadFragment.INDEX_UPDATE, "(游戏插件)"));
                        break;
                    } else if (entryName.contains("halo_skip.json")) {
                        InputStream in = zipfile.getInputStream(entry);
                        if (in != null) {
                            final BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                            InnerMetaInfoEntity info = GsonUtils.getGson().fromJson(reader, InnerMetaInfoEntity.class);
                            if (info != null) {
                                if (EntranceConsts.HOST_COMMUNITY.equals(info.getType())) {
                                    runOnUiThread(() -> mMainWrapperFragment.setCurrentItem(MainWrapperFragment.INDEX_BBS));
                                } else {
                                    DirectUtils.directToSpecificPage(this,
                                            info.getType(),
                                            info.getLink(),
                                            info.getText(),
                                            EntranceConsts.KEY_PLUGIN,
                                            "特定包启动跳转");
                                }
                            }
                        }
                    } else if (entryName.contains("halo_skip.dat")) {
                        InputStream in = zipfile.getInputStream(entry);
                        if (in != null) {
                            final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                            String content = "";
                            for (String line; (line = reader.readLine()) != null; content += line) ;

                            if (!TextUtils.isEmpty(content)) {
                                DefaultUrlHandler.interceptUrl(this, content, "(特定包启动跳转)");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (zipfile != null) {
                    try {
                        zipfile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    // 连接上网络事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (Config.getSettings() == null) {
                AppExecutor.getIoExecutor().execute(Config::getGhzsSettings);
            }

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

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

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

    public static void skipToMainActivity(Context context, int position) {
        Activity activity = AppManager.getInstance().findActivity(MainActivity.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
                && activity != null && !activity.isDestroyed()) {
            EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, position));
        } else {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, position));
                }
            }, 300);
        }

        Intent intent = MainActivity.getMainIntent(context);
        context.startActivity(intent);
    }

    //需要提前初始化微博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) {
                    PackageInstaller.install(this, downloadEntity, 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(R.id.lightgame_tab_container);
        blackList.add(R.id.wrapper_toolbar);
        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);
        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<>());
            }
        }
    }
}
