package com.miya.fastcashier

import android.app.Activity
import android.os.Bundle
import androidx.multidex.MultiDexApplication
import com.blankj.utilcode.util.LogUtils
import com.elvishew.xlog.LogConfiguration
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import com.elvishew.xlog.printer.AndroidPrinter
import com.elvishew.xlog.printer.ConsolePrinter
import com.elvishew.xlog.printer.Printer
import com.elvishew.xlog.printer.file.FilePrinter
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.utils.ContextUtils
import com.miya.fastcashier.utils.DateUtils
import com.miya.fastcashier.utils.DensityUtils
import com.miya.fastcashier.utils.LogFileUtils
import com.miya.fastcashier.utils.manage.LocalKeyDataMKManageKit
import com.miya.fastcashier.utils.manage.OrderRecordManageKit
import com.miya.print.PrinterManager
import com.sdy.miya.moblie.component.pay.core.net.MiYaPayMobileApiClient
import com.sdy.miya.moblie.component.pay.core.net.MiyaHttpLoggingInterceptor
import com.sdy.miya.moblie.component.pay.core.utils.PayLogFileUtils
import com.tencent.mmkv.MMKV
import java.io.File
import java.util.*


class BaseApplication : MultiDexApplication() {

    companion object {
        private lateinit var instance: BaseApplication
        fun getApplication() = instance
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        ContextUtils.init(this)
        //打印机初始化
        PrinterManager.getInstance().init(this)
        //屏幕适配
        screenAdapt()
        MMKV.initialize(this)
        //日志
        logConfig()
    }

    private fun logConfig() {

        XLog.init(LogLevel.ALL);

        val config = LogConfiguration.Builder()
            .logLevel(
                if (BuildConfig.DEBUG) LogLevel.ALL // 指定日志级别，低于该级别的日志将不会被打印，默认为 LogLevel.ALL
                else LogLevel.NONE
            )
            .enableThreadInfo() // 允许打印线程信息，默认禁止
            .build()

        val androidPrinter: Printer = AndroidPrinter(true) // 通过 android.util.Log 打印日志的打印器

        val consolePrinter: Printer = ConsolePrinter() // 通过 System.out 打印日志到控制台的打印器

        val filePrinter: Printer = FilePrinter.Builder(
            applicationContext.getExternalFilesDir(null)!!
                .absolutePath
                    + File.separator + "log"
        ) // 指定保存日志文件的路径
            .fileNameGenerator(DateFileNameGenerator()) // 指定日志文件名生成器，默认为 ChangelessFileNameGenerator("log")
            .backupStrategy(NeverBackupStrategy()) // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
            .build()

        XLog.init( // 初始化 XLog
            config,  // 指定日志配置，如果不指定，会默认使用 new LogConfiguration.Builder().build()
            androidPrinter,  // 添加任意多的打印器。如果没有添加任何打印器，会默认使用 AndroidPrinter(Android)/ConsolePrinter(java)
            consolePrinter,
            filePrinter
        )


        //支付日志文件夹
        PayLogFileUtils.initLogPath(
            applicationContext.getExternalFilesDir(null)!!
                .absolutePath
                    + File.separator + "payLog"
        )

        var loggingInterceptor: MiyaHttpLoggingInterceptor? = null
        try {
            loggingInterceptor = MiyaHttpLoggingInterceptor { message ->
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(
                        ContextUtils.getContext(),
                        DateUtils.getDateStringByTimeStamp(System.currentTimeMillis())
                            .toString() + " " + message + "\n"
                    )
                }
                if (BuildConfig.DEBUG) {
                    LogUtils.d("fastcashier", message)
                }
            }
            loggingInterceptor.level = MiyaHttpLoggingInterceptor.Level.BODY
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        MiYaPayMobileApiClient.init(true, loggingInterceptor)
    }

    private fun screenAdapt() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                DensityUtils.setDensity(activity, this@BaseApplication)
                XLog.d(DateUtils.format18(Date()) + "  onActivityCreated")
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivityCreated() called with: activity = [$activity]\n")
                }
            }

            override fun onActivityStarted(activity: Activity) {
                XLog.d(DateUtils.format18(Date()) + "  onActivityStarted")
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivityStarted() called with: activity = [$activity]\n")
                }
            }

            override fun onActivityResumed(activity: Activity) {
                XLog.d(DateUtils.format18(Date()) + "  onActivityResumed")
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivityResumed() called with: activity = [$activity]\n")
                }
            }

            override fun onActivityPaused(activity: Activity) {
                XLog.d(DateUtils.format18(Date()) + "  onActivityPaused")
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivityPaused() called with: activity = [$activity]\n")
                }
            }

            override fun onActivityStopped(activity: Activity) {
                XLog.d(DateUtils.format18(Date()) + "  onActivityStopped")
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivityStopped() called with: activity = [$activity]\n")
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                XLog.d(DateUtils.format18(Date()) + "  onActivitySaveInstanceState")
                if (!LogFileUtils.isProhibitWrite) {
                    val memoryStatus = "\ttotalMemory:${Runtime.getRuntime().totalMemory()}\tfreeMemory:${Runtime.getRuntime().freeMemory()}"
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivitySaveInstanceState() called with:" +
                                " activity = [$activity]\nmemoryStatus: $memoryStatus")
                }
            }

            override fun onActivityDestroyed(activity: Activity) {
                XLog.d(DateUtils.format18(Date()) + "  onActivityDestroyed")
                if (!LogFileUtils.isProhibitWrite) {
                    LogFileUtils.writeLog(ContextUtils.getContext(),
                        "\n${DateUtils.format18(Date())}########onActivityDestroyed() called with: activity = [$activity]\n")
                }
            }
        })
    }

    fun resetConfig() {
        LocalKeyDataMKManageKit.clearCommonData()
        //清除本地订单昨天的流水信息
        OrderRecordManageKit.clearOrderDataYeaterday()
        //清除本地个人信息
        AccountService.clear()
    }
}