package com.dlc.eboard

import android.app.ActivityManager
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.multidex.MultiDex
import android.util.Log
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.iflytek.AudioPlayerManager
import com.dlc.eboard.sp.EnvSp
import com.dlc.eboard.ui.SplashActivity
import com.rc.core.log.RcLog
import com.rc.core.util.CrashHandler
import com.rc.core.util.ScreenAdapter
import com.rc.httpcore.HttpClient
import com.rc.httpcore.config.ConfigCore
import com.rc.httpcore.config.ConfigFactory
import com.rc.httpcore.vo.response.LabConfig
import com.rc.httpcore.vo.response.NoticeSummaryVo
import com.rc.httpcore.vo.response.UserVo
//import com.squareup.leakcanary.LeakCanary
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.QbSdk.PreInitCallback

/**
 * info
 *
 * @author ReiChin_
 */
class LabApp : Application() {

    companion object {
        @JvmField
        var sLabConfig: LabConfig? = null

        @JvmField
        var sUserVo: UserVo? = null

        @JvmField
        var sNoticeList: List<NoticeSummaryVo>? = null
    }

    override fun onCreate() {
        super.onCreate()

        ScreenAdapter.initAppDensity(this)
        AudioPlayerManager.init(this)

        CrashHandler.initCrash(this)

        initBugly()

        // 初始化网络配置参数
        initHttpConfig()

        initX5()

//        LeakCanary.install(this)

    }

    private fun initHttpConfig() {
        HttpClient.init(this)
        HttpClient.token = Constants.NetExtra.TOKEN
        HttpClient.vName = BuildConfig.VERSION_NAME
        val envConfig = EnvSp.loadEnv(this)
        val configParam = ConfigFactory.buildReleaseConfig
        Constants.MqttConfig.initMqttConfig(configParam, envConfig)
        val apiVersion = envConfig?.apiVersion ?: Constants.NetExtra.API_VERSION
        ConfigCore.initConfig(
            configParam,
            envConfig?.baseUrl,
            envConfig?.signInCheckBaseUrlSp,
            apiVersion
        )
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (!topActivityIsSplashActivity()) {
                        Toast.makeText(
                            this@LabApp,
                            "登录过期，请重新登录",
                            Toast.LENGTH_SHORT
                        ).show()
                        mUiHandler.sendEmptyMessageAtTime(1, 1500)
                    }
                }

            }, IntentFilter("com.rc.core.token_expired"))
    }

    private val mUiHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (1 == msg.what) {
                // Token过期，进入登录页
                val intent = Intent().apply {
                    flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
                    setClass(this@LabApp, SplashActivity::class.java)
                }
                //跳转后清除handler机制
                removeCallbacksAndMessages(null)
                startActivity(intent)
            }
        }
    }

    private fun topActivityIsSplashActivity(): Boolean {
        return try {
            val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val componentName = activityManager.getRunningTasks(1)[0].topActivity
            SplashActivity::class.java.name == componentName?.className
        } catch (e: Exception) {
            false
        }
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    private fun initBugly() {
        /*
         * 第三个参数为SDK调试模式开关，调试模式的行为特性如下：
         *   1) 输出详细的Bugly SDK的Log；
         *   2) 每一条Crash都会被立即上报；
         *   3) 自定义日志将会在Logcat中输出。
         * 建议在测试阶段建议设置成true，发布时设置为false。
         */
        if (BuildConfig.DEBUG) {//发布版
            RcLog.DE_BUG = true
            CrashReport.initCrashReport(this, Constants.Bugly.APP_ID, false)
        }else {
            CrashReport.initCrashReport(this, Constants.Bugly.APP_ID, true)
        }

        CrashReport.setDeviceId(this, CommonUtils.getAndroidId())
    }

    private fun initX5() {
        // TBS服务
        val initParam = mapOf(
            TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER to true,
            TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE to true
        )
        QbSdk.initTbsSettings(initParam)
        QbSdk.setDownloadWithoutWifi(true)
        QbSdk.initX5Environment(this, object : PreInitCallback {
            override fun onCoreInitFinished() {
                Log.i("LabApp", "onCoreInitFinished")
            }

            override fun onViewInitFinished(b: Boolean) {
                // 加载x5内核成功返回值为true，否则返回false，加载失败会调用系统的webview
                Log.i("LabApp", "x5初始化结果===$b")
            }
        })
    }

}