package com.abbidot.tracker.ui.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import cn.jpush.android.api.JPushInterface
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.constant.KeyNames
import com.abbidot.tracker.databinding.ActivitySplashBinding
import com.abbidot.tracker.dialog.PrivacyPolicyDialog
import com.abbidot.tracker.retrofit2.INetworkService
import com.abbidot.tracker.util.ThirdPartyUtil
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.vm.CountDownTimerViewModel
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.hjq.toast.Toaster
import com.qmuiteam.qmui.arch.QMUIActivity
import com.stripe.android.PaymentConfiguration
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.openapi.IWXAPI
import java.util.Calendar


/**
 * 入口，启动页
 *
 *适配不同Android版本的启动动画,Android 12强制有启动图片 https://www.yii666.com/blog/282005.html
 * 新的ActivityResultContract替换onActivityResult https://www.jianshu.com/p/da4c0e87d8b4
 *
 */
class SplashActivity : QMUIActivity() {

    private lateinit var mContext: Context

    private lateinit var mViewBinding: ActivitySplashBinding

    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()

    // IWXAPI 是第三方 app 和微信通信的 openApi 接口
    private lateinit var mApi: IWXAPI

    //微信启动广播
    private var mWXAppBroadcastReceiver: BroadcastReceiver? = null

    @SuppressLint("WrongThread")
    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.onCreate(savedInstanceState)
        //禁用屏幕旋转 代码设置无效
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        mViewBinding = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)

        mContext = this

        //清除角标数字
        JPushInterface.setBadgeNumber(mContext, 0)
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // 清除所有通知,角标数字
        notificationManager.cancelAll()

        Utils.SECRET_KEY = Util.getMetadata(applicationContext, KeyNames.HTTP_REQUEST_KEY)
        INetworkService.apply {
            //国内外服务器切换域名
            BASE_URL = if (AppUtils.isChina()) {
                BASE_URL_CN
            } else {
                BASE_URL_ABROAD
            }
        }

        SRBleUtil.instance.init(application)

        val cd = Calendar.getInstance()
        val year = cd[Calendar.YEAR]
        mViewBinding.ivSplashName.apply {
            text = getString(R.string.system_txt_copyright, year)
            ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
                val bars = insets.getInsets(WindowInsetsCompat.Type.navigationBars())
                v.setPadding(bars.left, bars.top, bars.right, bars.bottom)
                insets
            }
        }

        if (AppUtils.isDebug()) {
            mViewBinding.ivSplashDebug.visibility = View.VISIBLE
        }

        mCountDownTimerViewModel.mCountDownEndLiveData.observe(this) {
            mViewBinding.splashLottieAnimationView.cancelAnimation()
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            if (TextUtils.isEmpty(userId)) {
                startActivity(Intent(mContext, SayHelloActivity::class.java))
            } else {
                startActivity(Util.checkBindDeviceAndPetGoActivity(mContext))
            }
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
            finish()
        }


        mViewBinding.splashLottieAnimationView.apply {
            setAnimation("lottie/logo_loader.json")
            addAnimatorListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    mViewBinding.splashLogoIv.visibility = View.VISIBLE
                    mCountDownTimerViewModel.startCountDown(2)
                }
            })
        }

        val firstOpen = MMKVUtil.getBoolean(MMKVKey.FirstOpen, true)
        if (firstOpen) {
            //隐私协议弹窗
            showPrivacyPolicyDialog()
        } else {
            acceptPrivacyPolicy()
        }
    }

    // 字体大小不跟随系统
    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(getConfigurationContext(newBase))
    }

    // 字体大小不跟随系统
    private fun getConfigurationContext(context: Context): Context {
        val configuration = context.resources.configuration
        configuration.fontScale = 1F
        return context.createConfigurationContext(configuration)
    }

    /**
     * 显示隐私协议弹窗
     */
    private fun showPrivacyPolicyDialog() {
        val privacyPolicyDialog = PrivacyPolicyDialog(this@SplashActivity)
        privacyPolicyDialog.apply {
            show()
            agreePrivacyPolicyCallback {
                if (!isAgree()) {
                    Toaster.show(R.string.register_txt_agree)
                    return@agreePrivacyPolicyCallback
                }
                dismiss()
                MMKVUtil.putBoolean(MMKVKey.FirstOpen, false)
                acceptPrivacyPolicy()
            }
        }
    }

    /**
     * 同意隐私协议操作
     */
    private fun acceptPrivacyPolicy() {
//        mViewBinding.splashLottieAnimationView.apply {
//            postDelayed({
//                playAnimation()
//            }, 600)
//        }
        mViewBinding.splashLogoIv.visibility = View.VISIBLE
        mCountDownTimerViewModel.startCountDown(1)

        init()
    }

    private fun init() {
        LogUtil.e("isDebug=${AppUtils.isDebug()}")
        JPushInterface.setDebugMode(AppUtils.isDebug())
        JPushInterface.init(this)

        //同意协议
        SDKInitializer.setAgreePrivacy(application, true)
//             LocationClient.setAgreePrivacy(true);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        SDKInitializer.initialize(application)
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
        SDKInitializer.setCoordType(CoordType.GCJ02)

        if (AppUtils.isChina()) {
            regToWx()
        } else {
            initMapbox()
            try {
                //stripe支付
                val stripeKey = Util.getMetadata(applicationContext, KeyNames.STRIPE_TEST_KEY)
                LogUtil.e("stripeKey=$stripeKey")
                PaymentConfiguration.init(
                    applicationContext, stripeKey
                )
            } catch (e: Exception) {
                LogUtil.e("stripeSdk initialize初始化异常,${e.message}")
            }
        }

        if (AppUtils.isDebug()) {
            //方便调试测试只使用谷歌地图情况
            initMapbox()
        }

        //腾讯bugly初始化
//        val buglyKey = Util.getMetadata(applicationContext, KeyNames.BUG_LY_KEY_NAME)
//        CrashReport.initCrashReport(applicationContext, buglyKey, AppUtils.isDebug())
    }

    private fun initMapbox() {
//        try {
//            val mapboxAccessToken =
//                Util.getMetadata(applicationContext, KeyNames.MAPBOX_ACCESS_TOKEN)
//            MapboxSearchSdk.initialize(
//                application, mapboxAccessToken, LocationEngineProvider.getBestLocationEngine(this)
//            )
//        } catch (e: Exception) {
//            LogUtil.e("MapboxSearchSdk initialize多次初始化异常")
//        }
    }

    /**
     * 注册到微信
     */
    private fun regToWx() {
        mApi = ThirdPartyUtil.mApi
        // 将应用的 appId 注册到微信
//        mApi.registerApp(ThirdPartyUtil.wXAppID)

        mWXAppBroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                // 将该 app 注册到微信
                mApi.registerApp(ThirdPartyUtil.WXAppID)
            }
        }
        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(mWXAppBroadcastReceiver, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    override fun onDestroy() {
        super.onDestroy()
        mWXAppBroadcastReceiver?.let {
            unregisterReceiver(it)
        }
    }

}