package com.dlc.exam

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.util.Log
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.multidex.MultiDex
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.dlc.exam.common.Constants
import com.dlc.exam.sp.EnvSp
import com.dlc.exam.ui.StartActivity
import com.iflytek.cloud.SpeechConstant
import com.iflytek.cloud.SpeechUtility
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.LearnLoginVo
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.QbSdk.PreInitCallback

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

    companion object {
        @JvmField
        var sLearnLoginVo : LearnLoginVo? = null
    }

    override fun onCreate() {
        super.onCreate()

        val logPath = "/sdcard/logs/"
        val config = LogUtils.getConfig()
        // log开关控制
        config.setLogSwitch(true)
        // log控制台开关
        config.setConsoleSwitch(true)
        // logTag
        config.setGlobalTag("Jayce")
        // log头部信息开关
        config.setLogHeadSwitch(true)
        // log文件开关
        config.setLog2FileSwitch(true)
        config.setDir(logPath)
        // log文件前缀
        config.setFilePrefix(AppUtils.getAppName())
        // log边框开关
        config.setBorderSwitch(true)
        // log文件保存天数
        config.setSaveDays(7)


        ScreenAdapter.initAppDensity(this)

        CrashHandler.initCrash(this)

        initBugly()

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

        // 初始化讯飞语音引擎
        initIflytek()

        initX5()
    }

    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)
        ConfigCore.initConfig(configParam, envConfig?.baseUrl, envConfig?.fileBrowserBaseUrl)
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (!topActivityIsSplashActivity()) {
                        Toast.makeText(applicationContext, "登录过期，请重新登录", 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@ExamApp, StartActivity::class.java)
                }
                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
            StartActivity::class.java.name == componentName?.className
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 初始化讯飞语音引擎
     */
    private fun initIflytek() {
        // 初始化讯飞语音引擎
        val param = StringBuilder().apply {
            append("${SpeechConstant.APPID}=${Constants.Iflytek.APP_ID},")
            // 设置使用v5+
            append("${SpeechConstant.ENGINE_MODE}=${SpeechConstant.MODE_MSC}")
        }.toString()
        val speechUtility = SpeechUtility.createUtility(this, param)
        val engines = speechUtility.queryAvailableEngines()
        RcLog.info("[Iflytek]讯飞语音引擎初始化结束")
        engines.forEachIndexed { index, value ->
            RcLog.info("[Iflytek]engines[$index]=$value")
        }
    }

    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。
         */
//        CrashReport.initCrashReport(this, Constants.Bugly.APP_ID, true)
//        CrashReport.initCrashReport(this, Constants.Bugly.APP_ID, false)
    }

    private fun initX5() {
        // TBS服务
//        HashMap map = new HashMap();
//        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
//        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
//        QbSdk.initTbsSettings(map);
//
//        QbSdk.setDownloadWithoutWifi(true);

        QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                Log.i("LabApp", "onCoreInitFinished")
            }

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

        val cb: PreInitCallback = object : PreInitCallback {
            override fun onViewInitFinished(b: Boolean) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("LabApp", " onViewInitFinished is $b")
            }

            override fun onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        }

        //x5内核初始化接口
        QbSdk.initX5Environment(this, cb)
    }

}