package com.sunzee.app

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Environment
import android.os.Process
import android.text.TextUtils

import com.hjq.http.EasyConfig
import com.hjq.http.config.IRequestHandler
import com.hjq.http.request.HttpRequest
import com.hjq.toast.Toaster
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
import com.quyunshuo.androidbaseframemvvm.base.BuildConfig
import com.quyunshuo.androidbaseframemvvm.base.utils.LanguageUtilsObject
import com.quyunshuo.androidbaseframemvvm.base.utils.multilanguages.MultiLanguages
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.util.AppTypeManger
import com.quyunshuo.androidbaseframemvvm.common.util.FileUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.service.ForceBackToAppService
import com.quyunshuo.module.home.service.GlobalService
import com.quyunshuo.module.home.service.MqService
import dagger.hilt.android.HiltAndroidApp
import okhttp3.OkHttpClient
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.lang.reflect.Type


/**
 * App壳
 *
 * @author Qu Yunshuo
 * @since 4/23/21 6:08 PM
 */
@HiltAndroidApp
class AppApplication : BaseApplication() {
    private val TAG = "AppApplication"
    private var instances: AppApplication? = null


    override fun onCreate() {
        instances = this
      //  MultiLanguages.init(this)
       // LanguageUtilsObject.applyOnCreate(this)

        AppTypeManger.getInstance().init(com.quyunshuo.androidbaseframemvvm.BuildConfig.APP_TYPE)
       // initLog()
        if (isAppMainProcess()) {

            XLogUtil.init()
            // 开启EventBusAPT,优化反射效率 当组件作为App运行时需要将添加的Index注释掉 因为找不到对应的类了
            EventBus
                .builder()
//            .addIndex(MainEventIndex())
                .installDefaultEventBus()

            // 初始化 Toast 框架
            Toaster.init(this)
            //打开串口
//            connectDevice()
            //创建设备编号
           // Heartbeat.deviceId = FileUtil.getDeviceId()
            Heartbeat.deviceId = XLogUtil.getDeviceId()
            initEasyOkHttp()
            val intent = Intent(this, GlobalService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            //强制自恢复App
            val forceBackToAppIntent = Intent(this, ForceBackToAppService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(forceBackToAppIntent)
            } else {
                startService(forceBackToAppIntent)
            }

            //开启MQ
            startService(Intent(this, MqService::class.java))

        }


        super.onCreate()
    }

/*    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(MultiLanguages.attach(base));
    }*/


    private fun initLog() {
//        initLeakCanary();//内存泄漏检测库
        FileUtil.createLogFile() //日志初始化
        FileUtil.createPhoneFile() //创建电话日志文件
        FileUtil.pastDueLog() //删除过期日志
        //创建文件夹
        val externalFilesDir =
            File(Environment.getExternalStorageDirectory().absolutePath + "/promptAudio")
        if (externalFilesDir == null || !externalFilesDir.exists()) {
            externalFilesDir!!.mkdir()
        }
    }

    private fun initEasyOkHttp() {

        /**
         * 初始哈EasyHttp
         */
        var okHttpClient: OkHttpClient? = OkHttpClient.Builder().build()

        // 网络请求框架初始化
        EasyConfig.with(okHttpClient)
            //  http://app.sunzee.com.cn/
            .setServer { "https://sz.sunzee.com.cn/" } // 设置服务器配置（必须设置）
            .setHandler(object : IRequestHandler {
                override fun requestSuccess(p0: HttpRequest<*>, result: Response, p2: Type): Any {
                    return result
                }

                override fun requestFail(p0: HttpRequest<*>, p1: Throwable): Throwable {
                    return p1
                }
            })
            .setRetryCount(1) // 设置请求重试次数
            .setRetryTime(2000) // 设置请求重试时间
            .into()

    }

//    private fun connectDevice() {
//        //对plc进行连接
////        val device = SerialPortDevice("/dev/ttyS4", "9600")
////        try {
////            SerialPortManager.getInstance().open(device)
////        } catch (e: Exception) {
////            Log.d(TAG, "connectDevice 串口打开失败: ")
////        }
////        Log.d(TAG, "connectDevice 串口打开成功: ")
//
//        //对单片机进行连接
//        val device: VboxSerialPortDevice = VboxSerialPortDevice("dev/"+SpUtils.getString(MMKVName.TTYS_PLC,"ttyS7"), "115200")
//        try {
//            VboxSerialPortManager.getInstance().open(device)
//        } catch (e: Exception) {
//            Log.d(TAG, "connectDevice 串口打开失败: ")
//        }
//        Log.d(TAG, "connectDevice 串口打开成功: ")
//    }

    /**
     * 判断是不是UI主进程，因为有些东西只能在UI主进程初始化
     */
    fun isAppMainProcess(): Boolean {
        try {
            val pid = Process.myPid()
            val process: String = getAppNameByPID(instances!!.baseContext, pid)
            return if (TextUtils.isEmpty(process)) {
                true
            } else if ("com.quyunshuo.androidbaseframemvvm".equals(process, ignoreCase = true)) {
                true
            } else {
                false
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return true
        }
    }

    /**
     * 根据Pid得到进程名
     */
    fun getAppNameByPID(context: Context, pid: Int): String {
        val manager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == pid) {
                return processInfo.processName
            }
        }
        return ""
    }
}