package com.adealink.weparty.ui

import android.os.Bundle
import android.os.SystemClock
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.lifecycleScope
import com.adealink.frame.aab.AAB
import com.adealink.frame.base.fastLazy
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.log.Log
import com.adealink.frame.statistics.BaseStatEvent
import com.adealink.frame.util.safeToLong
import com.adealink.weparty.App
import com.adealink.weparty.BuildConfig
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.isUiValid
import com.adealink.weparty.config.approvingVersionManager
import com.adealink.weparty.location.viewmodel.LocationReporter
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.module.gift.GiftModule
import com.adealink.weparty.module.order.OrderModule
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.room.RoomModule
import com.adealink.weparty.module.setting.SettingModule
import com.adealink.weparty.module.wallet.WalletModule
import com.adealink.weparty.stat.RegisterEvent
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.crashlytics.ktx.setCustomKeys
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 主界面初始化
 */
class MainStartUpFragment : BaseFragment() {

    //    private val roomAttrViewModel by fastLazy {
//        if (activity?.isUiValid() == true) {
//            RoomModule.getRoomAttrViewModel(this.requireActivity())
//        } else {
//            null
//        }
//    }
//    private val familyInfoViewModel by fastLazy {
//        if (activity?.isUiValid() == true) {
//            FamilyModule.getFamilyInfoViewModel(this.requireActivity())
//        } else {
//            null
//        }
//    }
//    private val countryViewModel by fastLazy {
//        if (activity?.isUiValid() == true) {
//            ProfileModule.getCountryViewModel(this)
//        } else {
//            null
//        }
//    }
//    private val walletViewModel by fastLazy {
//        if (activity?.isUiValid() == true) {
//            WalletModule.getWalletViewModel(requireActivity())
//        } else {
//            null
//        }
//    }
    private val settingViewModel by fastLazy {
        if (activity?.isUiValid() == true) {
            SettingModule.getSettingViewModel(requireActivity())
        } else {
            null
        }
    }

    private suspend fun importantTask() {
        withContext(Dispatcher.WENEXT_THREAD_POOL) {
            importantLoad()
        }
        withContext(Dispatcher.UI) {
            importLoadInUIThread()
        }
    }

    private fun importantLoad() {
        val startTs = SystemClock.elapsedRealtime()
        Log.d(TAG, "importantLoad-start")
        if (AccountModule.isLogin()) {
            AccountModule.checkRemoteVirtualAppConfig()
//            AttributionModule.reportAttributionData()
            BaseStatEvent.setUserId(ProfileModule.getMyUid().safeToLong())
//            pushService.getPushTokenAndReport()
            Firebase.crashlytics.setCustomKeys {
                key("uid", AccountModule.uid)
                key("BuildType", BuildConfig.BUILD_TYPE)
                key("IS_RELEASE", BuildConfig.IS_RELEASE)
            }
            LocationReporter.reportLocation(activity)

            /*登录注册*/
            RegisterEvent().send()
        }

        AccountModule.refreshToken()
        approvingVersionManager.refreshApproving()
        installDynamicModule()
        Log.d(TAG, "importantLoad-end, cost:${SystemClock.elapsedRealtime() - startTs}ms")
    }


    private fun importLoadInUIThread() {
    }

    // 启动后，交给Google Play，延迟安装所有模块（后台自动下载）
    private fun installDynamicModule() {
        AAB.deferredInstall(
            listOf(
//                CertificationModule.featureName
            )
        )
    }

    private suspend fun minorTask() {
        withContext(Dispatcher.WENEXT_THREAD_POOL) {
            minorLoad()
        }
    }

    private fun minorLoad() {
        val startTs = SystemClock.elapsedRealtime()
        Log.d(TAG, "minorLoad-start")
        WalletModule.init()
        WalletModule.fetchCurrency()
        WalletModule.queryAndHandleUnDealPurchases()

        OrderModule.queryDiscountInfo()
        RoomModule.init()
        RoomModule.checkRoomPermission()

        GiftModule.getGiftResource(true)
        Log.d(TAG, "minorLoad-end, cost:${SystemClock.elapsedRealtime() - startTs}ms")
    }

    private suspend fun otherTask() {
        withContext(Dispatcher.WENEXT_THREAD_POOL) {
            otherLoad()
        }
    }

    private fun otherLoad() {
        val startTs = SystemClock.elapsedRealtime()
        Log.d(TAG, "otherLoad-start")
        reportPushSwitch()
        settingViewModel?.reportLanguage(App.instance.languageManager.getLanguage())
        Log.d(TAG, "otherLoad-end, cost:${SystemClock.elapsedRealtime() - startTs}ms")
    }

    private fun reportPushSwitch() {
        val activity = activity ?: return
        val manager: NotificationManagerCompat = NotificationManagerCompat.from(activity)
        val isOpen = manager.areNotificationsEnabled()
//        PushStatEvent(PushStatEvent.Action.SWITCH).apply {
//            switch to if (isOpen) 1 else 0
//        }.send()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        Log.i(TAG, "StartUpFragment.onCreate()")
        lifecycleScope.launch {
            importantTask()
        }
        lifecycleScope.launch {
            delay(2000L)
            minorTask()
        }
        lifecycleScope.launch {
            delay(3000L)
            otherTask()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "StartUpFragment.onDestroy()")
    }

    companion object {
        private const val TAG = "StartUpFragment"

        @JvmStatic
        fun inject(activity: BaseActivity) {
            val manager = activity.supportFragmentManager
            if (manager.findFragmentByTag(TAG) == null) {
                manager.beginTransaction().add(MainStartUpFragment(), TAG).commitAllowingStateLoss()
                manager.executePendingTransactions()
            }
        }
    }

}