package com.xty.common.app

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.util.Log
import cat.ereza.customactivityoncrash.CustomActivityOnCrash
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.alibaba.android.arouter.launcher.ARouter
import com.auparty.android.crashguard.CrashGuard
import com.auparty.android.crashguard.ExceptionHandler
import com.hjq.toast.ToastUtils
import com.liulishuo.filedownloader.FileDownloader
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxTool
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.umeng.commonsdk.UMConfigure
import com.xty.common.*
import com.xty.common.bracelet.checkBlueConnectPermission
import com.xty.common.bracelet.getBluePermission
import com.xty.common.event.BlueToothConnectEvent
import com.xty.common.receiver.BluetoothMonitorReceiver
import com.yucheng.ycbtsdk.Constants
import com.yucheng.ycbtsdk.YCBTClient
import com.yucheng.ycbtsdk.response.BleConnectResponse
import com.yucheng.ycbtsdk.response.BleDeviceToAppDataResponse
import me.leolin.shortcutbadger.ShortcutBadger
import org.greenrobot.eventbus.EventBus


class MyApp : Application() {

    private lateinit var  blueToothReceiver: BluetoothMonitorReceiver

    companion object {
        var instance: MyApp? = null
        private fun getInstance(app: MyApp) {
            instance = app
        }
    }

    var api: IWXAPI? = null
    override fun onCreate() {
        super.onCreate()
        LogUtils.d("MyApp onCreate!!!!")

        if (BuildConfig.isRelease){
            initCrash()
        }

        // 初始化 Toast 框架
        getInstance(this)
        MMkvHelper.initMmkv(this)
        ToastUtils.init(this)
        ARouter.openDebug()
        ARouter.init(this)
       // initTouch()
        initTimeUtils()
        initWxApi()
        initUMengSdk()
        initRefresh()
        registerBlueToothBoardCastReceiver()
        initX5()
        //bugly 上报  在release版本才会上报
//        if(BuildConfig.isRelease){
//            CrashReport.initCrashReport(this, "", true)
//        }
        //删除角标
        ShortcutBadger.applyCount(applicationContext, 0)

//        if (MMkvHelper.contains("private")){
//            val isTopRun = isTopRun()
//            LogUtils.d("isTopRun：$isTopRun")
//            if (!isTopRun){
//                RxActivityTool.AppExit(applicationContext)
//                forceStopApp()
//                exitProcess(0)
//            }
//        }



        FileDownloader.setupOnApplicationOnCreate(this)
            .connectionCreator(
                com.liulishuo.filedownloader.connection.FileDownloadUrlConnection.Creator(
                    com.liulishuo.filedownloader.connection.FileDownloadUrlConnection.Configuration()
                        .connectTimeout(15000) // set connection timeout.
                        .readTimeout(15000) // set read timeout.
                )
            )
            .commit()
    }

//    private fun forceStopApp(){
//        LogUtils.d("forceStopApp")
//        val manager =
//            applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//        manager.killBackgroundProcesses(packageName)
//    }

    /**
     * 判断应用是否在顶层运行
     * @return
     */
    private fun isTopRun(): Boolean {
        val am: ActivityManager = applicationContext.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val list: List<ActivityManager.RunningTaskInfo> = am.getRunningTasks(100)
        var isAppRunning = false
        //100表示取的最大的任务数，info.topActivity表示当前正在运行的Activity，info.baseActivity表系统后台有此进程在运行
        for (info in list) {
            if (info.topActivity?.packageName
                    .equals(packageName) || info.baseActivity?.packageName.equals(packageName)
            ) {
                isAppRunning = true
                break
            }else{
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    android.os.Process.killProcess(info.taskId)
                }else{
                    android.os.Process.killProcess(info.id)
                }
            }
        }
        LogUtils.d("list:${list.toString()}")
        return isAppRunning
    }

    /**
     * 注册蓝牙广播监听
     */
    fun registerBlueToothBoardCastReceiver(){
        blueToothReceiver = BluetoothMonitorReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(blueToothReceiver, intentFilter)
    }


    fun initUMengSdk(){
        //设置LOG开关，默认为false
        UMConfigure.setLogEnabled(!BuildConfig.isRelease)
        //友盟预初始化
        UMConfigure.preInit(applicationContext, BuildConfig.umengKey, BuildConfig.umengChannelName)
        // 支持在子进程中统计自定义事件
        UMConfigure.setProcessEvent(true)
    }

    /**
     * 注册微信到app
     */
    fun initWxApi() {
        api = WXAPIFactory.createWXAPI(this, BuildConfig.appid, false)
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {

                // 将该app注册到微信
                api!!.registerApp(BuildConfig.appid)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    fun initTimeUtils() {
        RxTool.init(this)
    }

    private fun initX5() {
        QbSdk.setCoreMinVersion(QbSdk.CORE_VER_ENABLE_202112);
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        val cb: QbSdk.PreInitCallback =
            object : QbSdk.PreInitCallback {
                override fun onViewInitFinished(arg0: Boolean) {
                    //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                    Log.d("webX5", " onViewInitFinished is $arg0")
                }

                override fun onCoreInitFinished() {}
            }
        //x5内核初始化接口
        if (!QbSdk.isTbsCoreInited()) {
            QbSdk.initX5Environment(applicationContext, cb)
        }
    }


    /**
     * 初始化手环SDK
     */
    fun initTouch() {
        YCBTClient.initClient(this, true)
        YCBTClient.registerBleStateChange(bleConnectResponse)
        YCBTClient.deviceToApp(toAppDataResponse)

    }

    var toAppDataResponse =
        BleDeviceToAppDataResponse { dataType, dataMap ->
            LogUtils.d("被动回传数据:$dataMap")
        }
    private var bleConnectResponse = BleConnectResponse { code ->
        val isLogin = MMkvHelper.contains(Const.Auth_Token)
        val hasBlueMac = MMkvHelper.contains(Const.Blue_Tooth)
        LogUtils.d("全局监听返回=$code; isLogin:$isLogin; hasBlueMac:$hasBlueMac")
        if (isLogin && hasBlueMac) {
            when (code) {
                Constants.BLEState.Disconnect -> {
                    EventBus.getDefault().post(BlueToothConnectEvent())
                }
                Constants.BLEState.ReadWriteOK -> {
                    EventBus.getDefault().post(BlueToothConnectEvent())
                }

            }
        }


//        if (code == Constants.BLEState.Disconnect) {
//            //断开连接也修改状态
//            EventBus.getDefault().post(BlueToothConnectEvent())
//            //                thirdConnect = false;
//            //                BangleUtil.getInstance().SDK_VERSIONS = -1;
//            //                EventBus.getDefault().post(new BlueConnectFailEvent());
//            /*if(SPUtil.getBindedDeviceMac() != null && !"".equals(SPUtil.getBindedDeviceMac())){
//                       YCBTClient.connectBle(SPUtil.getBindedDeviceMac(), new BleConnectResponse() {
//                           @Override
//                           public void onConnectResponse(int code) {
//
//                           }
//                       });
//                   }*/
//        } else if (code == Constants.BLEState.Connected) {
//        } else if (code == Constants.BLEState.ReadWriteOK) {
//            //                thirdConnect = true;
//            //                BangleUtil.getInstance().SDK_VERSIONS = 3;
//            //                Log.e("deviceconnect", "蓝牙连接成功，全局监听");
//            //                setBaseOrder();
//            //EventBus.getDefault().post(new ConnectEvent());
//        } else {
//            //code == Constants.BLEState.Disconnect
//            //                thirdConnect = false;
//            //                BangleUtil.getInstance().SDK_VERSIONS = -1;
//            //                EventBus.getDefault().post(new ConnectEvent());
//        }
    }

    private fun initRefresh() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.col_009, android.R.color.white) //全局设置主题颜色
            ClassicsHeader(context) //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter(context).setDrawableSize(20f)
        }
    }

    /**
     * 崩溃拦截框架
     */
    @SuppressLint("RestrictedApi")
    private fun initCrash() {
        CrashGuard.install(this, object : ExceptionHandler() {
            override fun onUncaughtException(thread: Thread, throwable: Throwable) {
                LogUtils.e("simon", "thread:${thread.name} throwable:${throwable.message}")

            }

            override fun onLifeCycleException(thread: Thread, e: Throwable) {
                LogUtils.e("simon", "生命周期异常 thread:${thread.name} throwable:${e.message}")
            }
        })
    }

//        CaocConfig.Builder.create()
//            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT)
//            .enabled(false)     //这阻止了对崩溃的拦截,false表示阻止。用它来禁用customactivityoncrash框架
//            .minTimeBetweenCrashesMs(2000)      //定义应用程序崩溃之间的最短时间，以确定我们不在崩溃循环中。比如：在规定的时间内再次崩溃，框架将不处理，让系统处理！
//            .errorDrawable(R.mipmap.ic_add)     //崩溃页面显示的图标
//            .errorActivity(CrashAct::class.java)
//            .apply()
//        CustomActivityOnCrash.install(this);
    }
    /**
     * 崩溃拦截框架
     */
//    private fun initCrash() {
//        CaocConfig.Builder.create()
//            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT)
//            .enabled(false)     //这阻止了对崩溃的拦截,false表示阻止。用它来禁用customactivityoncrash框架
//            .showErrorDetails(true) //这将隐藏错误活动中的“错误详细信息”按钮，从而隐藏堆栈跟踪。
//            .showRestartButton(true)    //是否可以重启页面
//            .trackActivities(false)     //错误页面中显示错误详细信息
//            .minTimeBetweenCrashesMs(2000)      //定义应用程序崩溃之间的最短时间，以确定我们不在崩溃循环中。比如：在规定的时间内再次崩溃，框架将不处理，让系统处理！
//            .errorDrawable(R.mipmap.ic_logo)     //崩溃页面显示的图标
//            .errorActivity(CrashAct::class.java) //程序崩溃后显示的页面
//            .apply()
//    }
//
//}