package com.adealink.weparty.ui

import android.location.Location
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.IError
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.locale.location.OnLocationListener
import com.adealink.frame.log.Log
import com.adealink.frame.push.manager.pushService
import com.adealink.frame.statistics.BaseStatEvent
import com.adealink.frame.util.runOnUiThread
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.config.globalConfigManager
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.push.PushStatEvent
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 anchorViewModel by fastLazy {
//        if (activity?.isUiValid() == true) {
//            AnchorModule.getAnchorViewModel(requireActivity())
//        } else {
//            null
//        }
//    }

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

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

        App.instance.logService.subscribeNotify()
        AccountModule.refreshToken()
//        ProfileModule.reportPhoneModel(FromScene.STARTUP.scene)
//        MessageModule.activityOnCreateMainTask()
//        RoomModule.init()
//        GameModule.checkPlayingGame()

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

    // 启动后，交给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.fetchCurrency()
//        WalletModule.queryAndHandleUnDealPurchases()
//        LevelModule.pullLevelConfigs()
//        CoupleModule.pullCoupleConfig()
//        WalletModule.init()
//        ProfileModule.pullUserNoteNameData()
//        walletViewModel?.addGlobalConfigListener()
//        walletViewModel?.getUserChargeNotify()
        globalConfigManager.getAllGlobalConfig(true)
//        GameModule.initRocket()


        // TODO: 测试经纬度
        runOnUiThread {
            activity?.let {
                App.instance.locationManager.init(it)
            }
            App.instance.locationManager.getLocation(object : OnLocationListener {
                override fun onFailed(error: IError) {
                    Log.d("zhangfei", "getLocation fail, ${error.serverCode}, ${error.msg}")
                }

                override fun onSuccess(location: Location) {
                    Log.d(
                        "zhangfei",
                        "getLocation success, longitude: ${location.longitude}, latitude: ${location.latitude}"
                    )
                }
            })
        }


        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")
//        GiftModule.getGifts(true)
//        EmotionModule.getEmotionPackages(true)
//        MedalModule.init()
//        SkinModule.getCurrentSkin(true)
//        PreloadWebViewWorker.startPreloadWorker(AppUtil.appContext)
//        ProfileModule.checkChatAchievement()
//        UserTaskManager.init()
//        InviteRewardManager.init()
//        RoomTaskMonitor.init()
//        HeadlineModule.init()
//        OperationModule.checkSuperSupporterWhatsAppFillStatus()
//        familyInfoViewModel?.getApplyJoinFamilyUnHandleNum()
        reportPushSwitch()
        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()
            }
        }
    }

}