package com.cheng.blzb.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.window.OnBackInvokedDispatcher
import androidx.activity.addCallback
import androidx.core.os.BuildCompat
import androidx.fragment.app.Fragment
import com.bytedance.ads.convert.BDConvert
import com.cheng.blzb.BuildConfig
import com.cheng.blzb.R
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.LoginManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.dialog.PrivacyPolicyDialog
import com.cheng.blzb.utils.ChannelUtils
import com.example.base.dialog.LoadingDialog
import com.example.base.ui.BaseActivity
import com.example.base.utils.L
import com.example.base.utils.Utils
import com.g.gysdk.GYManager
import com.g.gysdk.GYResponse
import com.g.gysdk.GyCallBack
import com.g.gysdk.GyConfig
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.igexin.sdk.PushManager
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import org.jetbrains.anko.startActivity


/**
 * 闪屏页
 */
class LauncherActivity : BaseActivity() {

    private val privacyPolicyDialog by lazy {
        PrivacyPolicyDialog()
    }

    private val loadingDialog by lazy {
        LoadingDialog(this)
    }

    override fun getFragment() = Fragment(R.layout.activity_launcher)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
        backApp()

        if (UserConfigManager.isAgree()) {
            loadingDialog.show()
            UserConfigManager.saveBDVID()
            UserConfigManager.getServerTime {
                EventReportManager.eventReport(EventConstants.APP_LAUNCH, "", "")
                loadingDialog.dismiss()
                initUM()
                initBD()
                initGT()
                intentMain()
            }
        } else {
            privacyDialog()
        }
    }

    private fun privacyDialog() {
        privacyPolicyDialog.setOnSelectListener {
            if (it == DialogEnum.CLICK_OK) {
                loadingDialog.show()
                UserConfigManager.saveAgree()
                UserConfigManager.saveBDVID()
                UserConfigManager.getServerTime {
                    EventReportManager.eventReport(EventConstants.APP_LAUNCH, "", "")
                    loadingDialog.dismiss()
                    initUM()
                    initBD()
                    initGT()
                    intentMain()
                }
            } else {
                finish()
            }
        }
        privacyPolicyDialog.show(supportFragmentManager, null)
    }

    private fun intentMain() {
        if (UserConfigManager.isFirstUseApp()) {
            UserConfigManager.saveFirstUseApp(false)
            if (UserConfigManager.getGuideEnable()) {
                startActivity<GuideActivity>()
            } else {
                if (!LoginManager.isLogin()) {
                    if (TextUtils.isEmpty(LoginManager.getLastLoginType())) {
                        startActivity<MainActivity>()
                    } else {
                        LoginActivity.start(this@LauncherActivity)
                    }
                } else {
                    startActivity<MainActivity>()
                }
            }
            finish()
        } else {
            if (!LoginManager.isLogin()) {
                if (TextUtils.isEmpty(LoginManager.getLastLoginType())) {
                    startActivity<MainActivity>()
                } else {
                    LoginActivity.start(this@LauncherActivity)
                }
            } else {
                startActivity<MainActivity>()
            }
            finish()
        }
    }

    /**
     * 初始化友盟
     */
    private fun initUM() {
        UMConfigure.preInit(Utils.getApp(), Constants.UmengAppkey, ChannelUtils.getChannel())
        UMConfigure.init(this, Constants.UmengAppkey, ChannelUtils.getChannel(), UMConfigure.DEVICE_TYPE_PHONE, "")
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
    }

    /**
     * 巨量融合初始化
     */
    private fun initBD() {
        BDConvert.init(Utils.getApp(), this)
    }

    /**
     * 个推初始化
     */
    private fun initGT() {
        GYManager.getInstance().preInit(this) //个验SDK初始化
        GYManager.getInstance().init(
            GyConfig.with(this)
                .preLoginUseCache(true)//预取号使用缓存，可以提高预取号的成功率，建议设置为true
                .channel(ChannelUtils.getChannel())//应用渠道
                .eLoginDebug(BuildConfig.DEBUG)//运营商debug调试模式
                .debug(BuildConfig.DEBUG)//个验debug调试模式
                .callBack(object : GyCallBack {
                    override fun onSuccess(gyResponse: GYResponse) {
                        L.d("TAG-->>GYManager init onSuccess =${gyResponse.code}")
                    }

                    override fun onFailed(gyResponse: GYResponse) {
                        L.d("TAG-->>GYManager init onFailed =${gyResponse.code}")
                    }
                }).build()
        )
        //预登录
        GYManager.getInstance().ePreLogin(8000, object : GyCallBack {
            override fun onSuccess(gyResponse: GYResponse) {
                L.d("TAG-->>GYManager ePreLogin onSuccess =${gyResponse.code}")
            }

            override fun onFailed(gyResponse: GYResponse) {
                L.d("TAG-->>GYManager ePreLogin onFailed =${gyResponse.code}")
            }
        })

        PushManager.getInstance().preInit(this)
        PushManager.getInstance().initialize(this)
    }

    @SuppressLint("UnsafeOptInUsageError")
    private fun backApp() {
        if (BuildCompat.isAtLeastT()) {
            onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) {
            }
        } else {
            onBackPressedDispatcher.addCallback(this) {
            }
        }
    }
}