package xn.hxp.app

import android.app.Application
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.multidex.MultiDex
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.CrashUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ThreadUtils
import com.clj.fastble.BleManager
import com.github.anrwatchdog.ANRWatchDog
import com.hjq.toast.Toaster
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.util.TextInfo
import com.rc.core.util.ScreenAdapter
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.apk.LabInfo
import com.rc.httpcore.bean.ConfigBean
import com.rc.httpcore.bean.UserData
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import xn.hxp.R
import xn.hxp.utils.Tool
import xn.hxp.utils.bluetooth.SppTool

//新版化学品-使用V3版本API
class ChemicalApp : Application() {

    companion object {
        lateinit var appContext: Context

        @JvmField
        var userData: UserData? = null

        @JvmField
        var subjectId: String? = null   //实验室id

        @JvmField
        var subjectName: String? = null //实验室name

        @JvmField
        var confs: ConfigBean? = null   //基础信息以及 双人 认证方式

        @JvmField
        var labInfo: LabInfo? = null    //基础信息以及 双人 认证方式

        @JvmField
        var subRoom: String? = null     //房间号

        @JvmField
        var administrators = true      //是否是校院级管理员  管控类的仅校级管理员或院级管理员可操作  新增入库  操作管控or非管控

        @JvmField
        var responsibles = true        //是否是 责任人      实验室负责人或安全责任人、柜门管理员   新增入库  只能操作非管控
    }

    override fun onCreate() {
        super.onCreate()
        ANRWatchDog(5000).setANRListener {
            ThreadUtils.runOnUiThread {
                Toast.makeText(
                    ActivityUtils.getTopActivity(),
                    "检测到应用卡顿,重启应用恢复!",
                    Toast.LENGTH_LONG
                ).show()
                var anrSize = SPUtils.getInstance().getInt("ANR_size", 0)
                if (anrSize > 5) {
                    SPUtils.getInstance().put("ANR_size", 0)
                    Tool.INSTANCE.reboot()
                } else {
                    SPUtils.getInstance().put("ANR_size", ++anrSize)
                    Tool.INSTANCE.reStartApp()
                }
            }
            LogUtils.e(it, it.message)
        }.start()
        SppTool.INSTANCE.init()
        BleManager.getInstance().enableLog(true).setReConnectCount(3).init(this)

        DialogX.init(this)
        DialogX.globalTheme = DialogX.THEME.DARK
        DialogX.cancelable = false
        DialogX.cancelableTipDialog = false
        DialogX.tipProgressColor = getColor(R.color.teal_700)

        var textInfo = TextInfo()
        textInfo.fontColor = getColor(R.color.teal_700)
        textInfo.fontSizeUnit = TextInfo.FONT_SIZE_UNIT.SP
        textInfo.fontSize = 20
        DialogX.tipTextInfo = textInfo
        DialogX.globalHoverWindow = true;
        if (AppUtils.isAppDebug()) {
            HttpConfig.API_BASE_URL = "http://192.168.1.8/api/"
            HttpConfig.API_BASE_IMG_URL = "http://192.168.1.8/api/"
        }
        ScreenAdapter.initAppDensity(this)
        initX5()
        appContext = applicationContext
        initLog()
        Toaster.init(this)
    }

    private fun initLog() {
        val logPath = "/sdcard/logs/"
        val crashPath = "/sdcard/logs/crash/"
        // log文件存储地址
        FileUtils.createOrExistsDir(logPath)
        FileUtils.createOrExistsDir(crashPath)
        CrashUtils.init(crashPath) { crashInfo ->
            LogUtils.e(crashInfo)
        }
        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() + "_App")
        // log边框开关
        config.setBorderSwitch(true)
        // log文件保存天数
        config.setSaveDays(7)
    }

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

    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 : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                Log.i("LabApp", "onCoreInitFinished")
            }

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