package com.zj365.dc.activity

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.MutableLiveData
import cn.jpush.android.api.JPushInterface
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.gyf.immersionbar.ImmersionBar
import com.tamsiree.rxkit.RxDeviceTool
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.umeng.commonsdk.UMConfigure
import com.xty.base.act.BaseVmAct
import com.xty.common.Const
import com.xty.common.JPushHelper
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.R
import com.xty.common.app.MyApp
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.bracelet.checkBlueConnectPermission
import com.xty.common.getImageUrl
import com.xty.common.util.CommonUtils
import com.zj365.dc.BuildConfig

import com.zj365.dc.databinding.ActWelcomeBinding
import com.zj365.dc.vm.WelcomeVm
import com.zj365.dc.weight.PrevDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class WelcomeAct : BaseVmAct<WelcomeVm>() {

    val binding by lazy { ActWelcomeBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    private var timeBack = 1
    private val timeLive by lazy { MutableLiveData<String>() }
    private var job: Job? = null
    private val prevDialog by lazy {
        PrevDialog(this, {
            startTimer()
          //  initX5()
            MMkvHelper.put("private", "")
        }) {
            finish()
        }
    }

    /**
     * 是否从启动页 或者进入的第一个界面加载
     *当前界面是否为task的根  如果不是就关闭
     */
    private fun getTaskAct() {
        if (!isTaskRoot) {
            finish()
            return
        }
    }

    override fun onResume() {
        super.onResume()
        if (!MMkvHelper.contains("private")) {
            prevDialog.showDialog()
        } else {
            startTimer()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        ImmersionBar.with(this)
            .statusBarDarkFont(isDarkBar)
            .keyboardEnable(true)
            .fullScreen(true)
            .init()
        getTaskAct()
        binding.mCard.setOnClickListener {
            job?.let {
                it.cancel()
            }
            forwardNextPage()
        }
     //   binding.mJump.text = "跳过 $timeBack"
        timeLive.observe(this) {
            --timeBack
            if (timeBack <= 0) {
                forwardNextPage()
            } else {
             //   binding.mJump.text = "跳过 $timeBack"
                startTimer()
            }
        }

       /* if (MMkvHelper.contains(Const.WELCOME_BG)) {
            getBgImage(getImageUrl(MMkvHelper.getString(Const.WELCOME_BG)))
        } else if (MMkvHelper.contains(Const.WELCOME_IMG) &&
            MMkvHelper.contains(Const.WELCOME_DESC)) {//欢迎语和logo都存在
     //       binding.mBg.setImageResource(R.mipmap.ic_welcome_bg)
            binding.mTxt.text = MMkvHelper.getString(Const.WELCOME_DESC)
            getLogoImage(getImageUrl(MMkvHelper.getString(Const.WELCOME_IMG)))
            binding.mLinInfo.visibility = View.VISIBLE
        } else if (MMkvHelper.contains(Const.WELCOME_DESC)) {//只有欢迎语
   //         binding.mBg.setImageResource(R.mipmap.ic_welcome_bg)
            binding.mTxt.text = MMkvHelper.getString(Const.WELCOME_DESC)
            binding.mLinInfo.visibility = View.VISIBLE
        } else if (MMkvHelper.contains(Const.WELCOME_IMG)) {//只有logo存在
          //  binding.mBg.setImageResource(R.mipmap.ic_welcome_bg)
            getLogoImage(getImageUrl(MMkvHelper.getString(Const.WELCOME_IMG)))
            binding.mLinInfo.visibility = View.VISIBLE
        } else {//上述都无信息，则展示默认欢迎界面
            binding.mLinInfo.visibility = View.GONE
        }*/

        if (MMkvHelper.contains(Const.Watch_Device_Type)) {
            if (CommonUtils.isBlueTooth(MMkvHelper.getInt(Const.Watch_Device_Type))) {
                if (checkBlueConnectPermission(this)) {
                    connect(MMkvHelper.getString(Const.Blue_Tooth))
                }
            }
        }
    }

    /**
     * 蓝牙链接
     */
    private fun connect(mac: String) {
        if (mac.isNullOrEmpty()) {
            return
        }

        mainScope.launch(Dispatchers.IO) {
            LogUtils.d("BlueTooth Connect!!!")
  /*          YCBBlueConnectHelper.connectionBlueTooth(mac, true) {
            }*/
        }
    }

    private fun forwardNextPage() {
//        if (MMkvHelper.contains(Const.Auth_Token)) {
            RouteManager.goAct(ARouterUrl.MAIN_ACT)
        /*} else {
            RouteManager.goAct(ARouterUrl.LOGIN_ACT)
        }*/
        finish()
    }

    private fun getBgImage(url: String) {
        Glide.with(this).asBitmap().load(url).error(R.mipmap.ic_welcome_main_bg)
            .into(object : SimpleTarget<Bitmap?>() {
                override fun onResourceReady(
                    resource: Bitmap,
                    transition: Transition<in Bitmap?>?
                ) {
                    if (resource != null) {
                        binding.mBg.setImageBitmap(resource)
                    }
                }
            })
    }

    private fun getLogoImage(url: String) {
        Glide.with(this).asBitmap().load(url).error(R.mipmap.ic_welcome_logo)
            .into(object : SimpleTarget<Bitmap?>() {
                override fun onResourceReady(
                    resource: Bitmap,
                    transition: Transition<in Bitmap?>?
                ) {
                    if (resource != null) {
                        binding.mImage.setImageBitmap(resource)
                        if (resource.width == resource.height) {
                            binding.mImage.post {
                                val screeWidth = RxDeviceTool.getScreenWidth(this@WelcomeAct)
                                val params = binding.mImage.layoutParams as ViewGroup.LayoutParams
                                params.width = screeWidth / 2
                                params.height = screeWidth / 2
                                binding.mImage.layoutParams = params
                            }
                        } else if (resource.width > resource.height || resource.height > resource.width) {
                            binding.mImage.post {
                                val screeWidth = RxDeviceTool.getScreenWidth(this@WelcomeAct)
                                val params = binding.mImage.layoutParams as ViewGroup.LayoutParams
                                params.width = screeWidth / 3 * 2
                                params.height = screeWidth / 2
                                binding.mImage.layoutParams = params
                            }
                        }
                    }
                }
            })
    }

    private fun startTimer() {
        initUMeng()
        initPush()
        job = mainScope.launch(Dispatchers.IO) {
            delay(1000)
            timeLive.postValue("")
        }
    }

    private fun initUMeng() {
        UMConfigure.submitPolicyGrantResult(MyApp.instance, true)
        UMConfigure.init(
            MyApp.instance,
            com.xty.common.BuildConfig.umengKey,
            com.xty.common.BuildConfig.umengChannelName,
            UMConfigure.DEVICE_TYPE_PHONE,
            ""
        )
    }

    private fun initPush() {
        JPushInterface.setDebugMode(!BuildConfig.isRelease)
        JPushInterface.init(MyApp.instance)
        //根据用户的设置开启或关闭消息通知
        val registrationID = JPushInterface.getRegistrationID(this)
        LogUtils.d("terry", "registrationID:$registrationID")
        val userId = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") ""
        else MMkvHelper.getLong(Const.USER_ID).toString()
        if (!userId.isNullOrEmpty()){
            Log.i("terry", "useId:$userId")
            JPushInterface.setAlias(this,userId.toInt(),"user_release_${userId}")
        }
    //    JPushHelper(this).stopOrResumeJPush(MMkvHelper.getBoolean(Const.NOTICE_FLAG))
    }



    override fun onDestroy() {
        job?.let {
            it.cancel()
        }
        super.onDestroy()
    }

    override fun liveObserver() {
    }
}