package com.gh.gamecenter

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.KeyEvent
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import com.therouter.TheRouter
import com.therouter.router.Route
import com.gh.common.dialog.NewPrivacyPolicyDialogFragment
import com.gh.common.util.DeviceTokenUtils
import com.gh.common.util.DialogUtils
import com.gh.common.util.GameSubstituteRepositoryHelper.updateGameSubstituteRepository
import com.gh.common.util.PackageHelper
import com.gh.common.util.PackageUtils
import com.gh.common.util.UsageStatsHelper.checkAndPostUsageStats
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.EntranceConsts.KEY_FROM
import com.gh.gamecenter.common.constant.EntranceConsts.KEY_GAMEID
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.tracker.TrackerLogger
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.iinterface.ISplashScreen
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.provider.IPackageUtilsProvider
import com.gh.gamecenter.core.provider.IPushProvider
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.feature.utils.PlatformUtils
import com.gh.gamecenter.pkg.PkgHelper
import com.halo.assistant.HaloApp
import org.json.JSONObject
import splitties.systemservices.notificationManager
import java.text.SimpleDateFormat
import java.util.*

/**
 * 引导页面
 */
@Route(path = RouteConsts.activity.splashActivity)
class SplashScreenActivity : BaseActivity(), ISplashScreen {

    private var mSharedPreferences: SharedPreferences? = null
    private var mIsNewForThisVersion = false
    private var mViewModel: SplashScreenViewModel? = null
    private var mShouldPrefetchData = true

    override fun onCreate(savedInstanceState: Bundle?) {
        mViewModel = viewModelProvider()
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        mIsNewForThisVersion = HaloApp.getInstance().isNewForThisVersion
        HaloApp.getInstance().isBrandNewInstall = SPUtils.getBoolean(Constants.SP_BRAND_NEW_USER, true)
        if (HaloApp.getInstance().isBrandNewInstall) {
            SPUtils.setLong(Constants.SP_BRAND_NEW_FIRST_LAUNCH_TIME, System.currentTimeMillis())
        }

        // 用户不是新版本，但应用最后更新时间不是上次的时间代表用户重新安装了当前版本
        if (!mIsNewForThisVersion) {
            val ghLastUpdateTime = SPUtils.getLong(Constants.SP_GH_LAST_UPDATE_TIME, 0)
            if (ghLastUpdateTime != 0L && ghLastUpdateTime != PackageUtils.getHaloLastUpdateTime()) {
                HaloApp.getInstance().setIsReinstallTheSameVersion(true)
            }
        }
        super.onCreate(savedInstanceState)
        DisplayUtils.transparentStatusBar(this)
        TrackerLogger.logAppLaunch(this)

        // 处理助手已经在后台运行导致的再次启动助手
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
            return
        }

        // 判断是不是这个版本的新用户
        if (mIsNewForThisVersion) {
            // 判断是不是光环的新用户
            if (HaloApp.getInstance().isBrandNewInstall) {
                SPUtils.setLong(Constants.SP_INITIAL_USAGE_TIME, System.currentTimeMillis())
                if (!PackageFlavorHelper.IS_TEST_FLAVOR) {
                    showPrivacyDialog()
                } else {
                    val spanBuilder = buildSpannedString {
                        append(
                            "这个弹窗只会在右上角有环境标签的测试包出现" +
                                    "\n进入应用以后还可以到关于我们页面长按应用图标重新选择"
                        )
                        bold {
                            color(com.gh.gamecenter.common.R.color.text_theme.toColor(this@SplashScreenActivity)) {
                                append("\n点击这里进行预设置渠道")
                            }
                        }
                    }

                    // Test dex2oat
                    executeDex2OatInAdvance()
                    DialogHelper.showDialog(
                        context = this,
                        title = "选择环境",
                        content = spanBuilder,
                        confirmText = "正式环境",
                        cancelText = "测试环境",
                        confirmClickCallback = {
                            SPUtils.setBoolean(Constants.SP_IS_DEV_ENV, false)
                            showPrivacyDialog()
                        },
                        cancelClickCallback = {
                            SPUtils.setBoolean(Constants.SP_IS_DEV_ENV, true)
                            showPrivacyDialog()
                        },
                        uiModificationCallback = {
                            it.contentTv.setOnClickListener {
                                EnvHelper.showChangeChannelDialog(this@SplashScreenActivity)
                            }
                        }
                    )
                }
            } else {
                PackageHelper.checkIfGetInstalledApiSwitchShouldBeIgnored(this)
                cancelPreviousUpdateTask()
                launchMainActivity()
            }
        } else {
            launchMainActivity()
        }
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
            SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "")
            SPUtils.setString(Constants.SP_XAPK_URL, "")
        }
    }

    private fun logAppLaunch() {
        val packageUtilsConfig = TheRouter.get(IPackageUtilsProvider::class.java)
        val appProvider = TheRouter.get(IAppProvider::class.java)
        val signatureHash = packageUtilsConfig?.getApkSignatureByPackageName(this, packageName)?.get(0)
        val sideLoadInfo = packageUtilsConfig?.getSideLoadedInfo()
        val trackEvent = JSONObject()
        // 是否首次使用神策
        val isFirstTime = SPUtils.getBoolean(Constants.SP_SENSORS_IS_FIRST_TIME, true)
        val therouterPath = intent.extras?.getString(EntranceConsts.KEY_THE_ROUTER_PATH) ?: ""
        val uri = Uri.parse(therouterPath)
        val isFromWechat = WECHAT_APPOINTMENT == if (!uri.isOpaque) uri.getQueryParameter(KEY_FROM) else false
        val gameId = if (!uri.isOpaque) uri.getQueryParameter(KEY_GAMEID) else ""
        tryCatchInRelease {
            trackEvent.run {
                put("\$is_first_time", isFirstTime)
                put("is_side_loaded", sideLoadInfo?.get("is_side_loaded").toBoolean())
                put("installer_store", sideLoadInfo?.get("installer_store") ?: "")
                put("package_name", packageName)
                put("signature", signatureHash)
                put("app_name", appProvider?.getAppName())
                put("install_first_time", if (HaloApp.getInstance().isBrandNewInstall) "是" else "否")
                if (isFromWechat) {
                    put("source_entrance", WECHAT_NOTIFICATION)
                    put("page_business_id", gameId)
                }
            }
        }
        SensorsBridge.trackEvent("AppLaunch", trackEvent)
        SPUtils.setBoolean(Constants.SP_SENSORS_IS_FIRST_TIME, false)
    }

    private fun showPrivacyDialog() {
        NewPrivacyPolicyDialogFragment.show(this, null) { isSuccess: Boolean ->
            if (isSuccess) {
                mShouldPrefetchData = false
                prefetchData()

                SPUtils.setBoolean(Constants.SP_BRAND_NEW_USER, false)

                // 荣耀高版本系统设备在获取已安装列表权限时，会把存储权限等的东西也一并弹出来，导致超量获取权限
                // 神奇的是，只需要在获取权限前弹出一条通知，再获取权限就会恢复正常.....
                val isMalfunctioningHonorDevice = Build.MANUFACTURER.lowercase() == "honor"
                        && Build.VERSION.SDK_INT > Build.VERSION_CODES.R

                if (isMalfunctioningHonorDevice) {
                    showHonorNotification()
                    mBaseHandler.postDelayed({
                        launchMainActivity()
//                        requestGetInstallListPermissionAndLaunchMainActivity()
                    }, 100L)
                } else {
                    launchMainActivity()
//                    requestGetInstallListPermissionAndLaunchMainActivity()
                }
            } else {
                DialogUtils.showPrivacyPolicyDisallowDialog(this) {
                    showPrivacyDialog()
                }
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun showHonorNotification() {
        val channel =
            NotificationChannel(HONOR_CULPRIT_CHANNEL, HONOR_CULPRIT_CHANNEL, NotificationManager.IMPORTANCE_MIN)
        notificationManager.createNotificationChannel(channel)
        val builder = NotificationCompat.Builder(HaloApp.getInstance().application, HONOR_CULPRIT_CHANNEL)
            .setSmallIcon(com.gh.gamecenter.common.R.mipmap.logo)
            .setContentTitle("光环助手荣耀设备启动服务")

        val notification = builder.build()

        notificationManager.notify(HONOR_CULPRIT_CHANNEL, HONOR_CULPRIT_ID, notification)
        notificationManager.cancel(HONOR_CULPRIT_ID)
    }

    // 尝试获取安装应用列表权限并启动首页（不在乎结果）
//    private fun requestGetInstallListPermissionAndLaunchMainActivity() {
//        if (PackageHelper.isSupportGetInstalledAppsPermission(this)
//            && PermissionHelper.isGetInstalledListPermissionDisabled(this)
//        ) {
//            PermissionHelper.requestGetInstalledAppsListPermission(this, true) {
//                launchMainActivity()
//            }
//        } else {
//            launchMainActivity()
//        }
//    }

    // 删除更新后的光环助手包
    private fun cancelPreviousUpdateTask() {
        val all = DownloadManager.getInstance().allDownloadEntity
        for (downloadEntity in all) {
            if (downloadEntity.packageName == packageName) {
                DownloadManager.getInstance().cancel(downloadEntity.url, true, true, false)
                break
            }
        }
    }

    /**
     * 让系统执行 dex2oat
     */
    private fun executeDex2OatInAdvance() {
        try {
            Runtime.getRuntime().exec("cmd package compile -m speed -f " + BuildConfig.APPLICATION_ID)
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    override fun getLayoutId() = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
            if (mIsNewForThisVersion) {
                launchMainActivity()
            } else {
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun useEventBus() = false

    // 跳转到主界面
    private fun launchMainActivity() {
        SPUtils.setLong(Constants.SP_GH_LAST_UPDATE_TIME, PackageUtils.getHaloLastUpdateTime())
        HaloApp.getInstance().postInit(true)
        TrackerLogger.logAppLaunchSuccessful()
        if (mShouldPrefetchData) {
            prefetchData()
        }
        val bundle = intent.extras
        val intent = Intent(this@SplashScreenActivity, MainActivity::class.java)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        intent.putExtra(MainActivity.SHOW_AD, !mIsNewForThisVersion)
        overridePendingTransition(0, 0)
        startActivity(intent)
        doFlavorInit()
        logAppLaunch()
        finish()
    }

    private fun doFlavorInit() {
        HaloApp.getInstance().flavorProvider.init(HaloApp.getInstance(), this, PkgHelper.getActivateRatio())

        SensorsBridge.init(HaloApp.getInstance(), HaloApp.getInstance().channel)
        SensorsBridge.setOAID(HaloApp.getInstance().oaid)

//        val pushProvider = ARouter.getInstance().build(RouteConsts.provider.push).navigation() as? IPushProvider
//        val registrationId = pushProvider?.getRegistrationId(this)
//        if (!registrationId.isNullOrEmpty()) {
//            SensorsBridge.profileSet(KEY_REGISTRATION_ID, registrationId)
//        }
    }

    private fun prefetchData() {
        runOnIoThread {
            mViewModel?.deviceDialogSetting()
            mViewModel?.filterDetailTags()
            mViewModel?.postMark(mIsNewForThisVersion)
            mViewModel?.regulationTestStatus()
            checkAndPostUsageStats()
            updateGameSubstituteRepository()

            if (BuildConfig.CONFIG_ID.isNotEmpty()) {
                PkgHelper.requestPkgConfig(BuildConfig.CONFIG_ID)
            }

            // 获取自动刷新的cd，获取版本对应表
            val time = mSharedPreferences!!.getString("refresh_time", null)
            val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            val today = format.format(Date())
            if (today != time) {
                // 获取版本代码、名称
                PlatformUtils.getInstance(applicationContext).getPlatform()
            }

            // 更新本地时间
            DeviceTokenUtils.syncServerTime(this)
        }
    }

    override fun initPageLevel(savedInstanceState: Bundle?) {
        // do nothing
    }

    companion object {
        private const val KEY_REGISTRATION_ID = "registration_id"

        const val HONOR_CULPRIT_ID = 12324
        const val HONOR_CULPRIT_CHANNEL = "荣耀通道"

        private const val WECHAT_APPOINTMENT = "wechat_appointment"
        private const val WECHAT_NOTIFICATION = "微信通知"

        @JvmStatic
        fun getSplashScreenIntent(context: Context?, bundle: Bundle?): Intent {
            val intent = Intent(context, SplashScreenActivity::class.java)
            intent.action = Intent.ACTION_MAIN
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putExtras(bundle ?: Bundle())
            return intent
        }
    }
}