package com.zhangxin.starlight

import android.app.Activity
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.multidex.MultiDex
import com.heytap.msp.push.HeytapPushManager
import com.huawei.hms.push.HmsMessaging
import com.meizu.cloud.pushsdk.PushManager
import com.tencent.android.tpush.XGPushConfig
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMManager
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import com.vivo.push.PushClient
import com.xiaomi.mipush.sdk.MiPushClient
import com.ym.chat.utils.TUIUtils
import com.zlw.main.recorderlib.RecordManager
import com.zhangxin.starlight.utils.AndroidDeviceUtils
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.ApplicationAsLibrary
import com.zxhl.cms.common.Config
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NotifyInfo
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.utils.*
import com.zxhl.cms.utils.EventUtils.onEvent
import java.util.*

/**
 * Created by gaoleichao on 2018/12/26
 */
class Appli : Application() {
    private val mChildApplicationList = ArrayList<ApplicationAsLibrary>()

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

    override fun onCreate() {
        super.onCreate()
        AppContext.init(applicationContext)
        UMConfigure.setLogEnabled(false)

        Utils.checkDebugMode(this)
        initIMSDK()
      PlatformConfig.setWeixin(Constant.WX_APPID, Constant.WX_APPKEY)
//        UMConfigure.setLogEnabled(true);
        if (!SettingPreference.getFirstApp()) {
            Config.init(this)
            UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "")
        }

        RecordManager.getInstance().init(this, true)
        //  getOaid()
        //initByteDance()
        CrashReport.initCrashReport(this, "7b18be6a65", true)
        XGPushConfig.enableDebug(this, true)
        XGPushConfig.enableOtherPush(this, true)
        if (AndroidDeviceUtils.isXiaoMiDevice()) {
            //小米
            MiPushClient.registerPush(this, "2882303761520127006", "5572012714006")
        }
        //oppo
        HeytapPushManager.init(this, true)
        if (HeytapPushManager.isSupportPush()) {
            createNotificationChannel(this)
        }
        //vivo
        PushClient.getInstance(this).initialize()
        //魅族
        PushManager.register(this, "146291", "d4e3507a70df42e7a649826409df52ab")
        //华为
        HmsMessaging.getInstance(this).isAutoInitEnabled = true
        HmsMessaging.getInstance(this).turnOnPush()
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    Log.i("1111", "turnOnPush Complete")
                } else {
                    Log.e("1111", "turnOnPush failed: ret=" + task.exception.message)
                }
            }

//        val helper = AppFrontBackHelper();
//
//        helper.register(this, object : AppFrontBackHelper.OnAppStatusListener {
//            //应用切到前台处理
//            override fun onFront() {
//
//            }
//
//            //应用切到后台处理
//            override fun onBack() {
//
//            }
//        })
        registerActivityLifecycleCallbacks(StatisticActivityLifecycleCallback())
    }

    private fun getOaid() {
        MiitHelper(appIdsUpdater).getDeviceIds(AppContext.mAppContext)
    }

    private val appIdsUpdater: MiitHelper.AppIdsUpdater = object : MiitHelper.AppIdsUpdater {
        override fun OnIdsAvalid(ids: String) {
            if (!TextUtils.isEmpty(ids)) {
                SettingPreference.setOaid(ids)
                onEvent("tab_imp", "获取到oaid$ids")
            }
        }
    }

    private fun initByteDance() {
        TTAdManagerHolder.init(this)
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
//        for (app in mChildApplicationList) {
//            app.onTrimMemoryAsLibrary(this, level)
//        }
    }

    override fun onLowMemory() {
        super.onLowMemory()
//        for (app in mChildApplicationList) {
//            app.onLowMemoryAsLibrary(this)
//        }
    }

    private fun initIMSDK() {
        TUIUtils.init(this, Constant.SDKAPPID, null, null)
    }

    inner class StatisticActivityLifecycleCallback : Application.ActivityLifecycleCallbacks {
        private var foregroundActivities = 0
        private var isChangingConfiguration = false
        private var unReadCount: Long = 0
        private val mUnreadWatcher: V2TIMConversationListener =
            object : V2TIMConversationListener() {
                override fun onNewConversation(conversationList: MutableList<V2TIMConversation>?) {
                    super.onNewConversation(conversationList)
                    if (!conversationList.isNullOrEmpty()) {
                        conversationList.forEach {
                            if (null != it.lastMessage) {
                                val notifyInfo = NotifyInfo()
                                notifyInfo.title = it.lastMessage.nickName
                                notifyInfo.content = it.lastMessage.textElem.text
                                NotificationUtil.notifyNotification(
                                    this@Appli,
                                    it.lastMessage.userID.toInt(),
                                    notifyInfo
                                )
                            }
                        }
                    }
                }

                override fun onTotalUnreadMessageCountChanged(totalUnreadCount: Long) {
                    super.onTotalUnreadMessageCountChanged(totalUnreadCount)
                    unReadCount = totalUnreadCount
                    V2TIMManager.getOfflinePushManager()
                        .doBackground(unReadCount.toInt(), object : V2TIMCallback {
                            override fun onError(code: Int, desc: String) {
                                LogUtils.e("doBackground err = $code, desc = $desc")
                            }

                            override fun onSuccess() {
                                LogUtils.i("doBackground success")
                            }
                        })
                }

                override fun onConversationChanged(conversationList: MutableList<V2TIMConversation>?) {
                    super.onConversationChanged(conversationList)
                    if (!conversationList.isNullOrEmpty()) {
                        conversationList.forEach {
                            if (null != it.lastMessage) {
                                val notifyInfo = NotifyInfo()
                                notifyInfo.title = it.lastMessage.nickName
                                notifyInfo.content = it.lastMessage.textElem.text
                                NotificationUtil.notifyNotification(
                                    this@Appli,
                                    it.lastMessage.userID.toInt(),
                                    notifyInfo
                                )
                            }
                        }
                    }
                }
            }

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        }

        override fun onActivityStarted(activity: Activity) {
            foregroundActivities++
            if (foregroundActivities == 1 && !isChangingConfiguration) {
                // 应用切到前台
                LogUtils.i("application enter foreground")
                V2TIMManager.getOfflinePushManager().doForeground(object : V2TIMCallback {
                    override fun onError(code: Int, desc: String) {
                        LogUtils.e("doForeground err = $code, desc = $desc")
                    }

                    override fun onSuccess() {
                        LogUtils.i("doForeground success")
                    }
                })
                V2TIMManager.getConversationManager().removeConversationListener(mUnreadWatcher)
            }
            isChangingConfiguration = false
        }

        override fun onActivityResumed(activity: Activity) {
        }

        override fun onActivityPaused(activity: Activity) {
        }

        override fun onActivityStopped(activity: Activity) {
            foregroundActivities--
            if (foregroundActivities == 0) {
                // 应用切到后台
                LogUtils.i("application enter background")
                V2TIMManager.getConversationManager().addConversationListener(mUnreadWatcher)
            }
            isChangingConfiguration = activity.isChangingConfigurations
        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        }

        override fun onActivityDestroyed(activity: Activity) {
        }

    }

    fun createNotificationChannel(context: Context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name: CharSequence = "StarLight"
            val description = "StarLight"
            val importance: Int = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel("starlightchattuikit", name, importance)
            channel.description = description
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            val notificationManager: NotificationManager = context.getSystemService(
                NotificationManager::class.java
            )
            notificationManager.createNotificationChannel(channel)
        }
    }
}