package com.quyunshuo.module.home.activity.main

import android.content.Context
import android.util.Log
import androidx.activity.viewModels
import androidx.navigation.findNavController
import com.alibaba.android.arouter.facade.annotation.Route
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.constant.RouteUrl
import com.quyunshuo.androidbaseframemvvm.common.constant.RouteUrl.Home.SettingActivity
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseActivity
import com.quyunshuo.androidbaseframemvvm.common.util.AppManager
import com.quyunshuo.androidbaseframemvvm.base.utils.LanguageUtil
import com.quyunshuo.androidbaseframemvvm.common.util.MyContextWrapper
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.databinding.HomeActivityMainBinding
import com.quyunshuo.module.home.utils.GeTuiUtil
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 首页
 *
 * @author Qu Yunshuo
 * @since 5/22/21 2:26 PM
 */
@RegisterEventBus
@Route(path = RouteUrl.Main.MainActivity)
@AndroidEntryPoint
class MainActivity : BaseActivity<HomeActivityMainBinding, MainViewModel>() {
    private var backPressedTime: Long = 0
    private val TAG = "MainActivity"

    /**
     * 通过 viewModels() + Hilt 获取 ViewModel 实例
     */
    override val mViewModel by viewModels<MainViewModel>()

    override fun createVB() = HomeActivityMainBinding.inflate(layoutInflater)

    override fun HomeActivityMainBinding.initView() {
        LanguageUtil.setLanguage()
        // mViewModel.initProductData()
        GeTuiUtil(this@MainActivity).geTui()
       // isShowSar(true)
    }

    override fun onStart() {
        super.onStart()
        devState()

    }
    /* fun isShowSar(flag: Boolean) {
        if (flag) {
            @SuppressLint("WrongConstant") val manager =
                getSystemService("xzjh_server") as XzjhSystemManager
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {  // Build.VERSION_CODES.R corresponds to Android 11
                ZtlManager.GetInstance().openSystemBar(ZtlManager.GetInstance().isSystemBarOpen)
                if (manager != null) {

                        manager.xzjhSetSystemBarEnable(!manager.xzjhGetSystemBarEnable())

                }
            } else {
                ZtlManager.GetInstance().openSystemBar(!ZtlManager.GetInstance().isSystemBarOpen)
                if (manager != null) {
                        manager.xzjhSetSystemBarEnable(manager.xzjhGetSystemBarEnable())

                }
            }
        } else {
           // ToastUtil.showToast(UiUtil.getStringRes(R.string.modified_failed))
        }
    }*/
    /**
     * 设备状态，如果是休眠，直接休眠，如果是锁机，直接锁机
     */
    private fun devState() {
        if (SpUtils.getBoolean(MMKVName.BLOCK, false) == true) {
            //开启休眠
            val navController = findNavController(mBinding.homeFragmentcontainerview.id)
            navController.navigate(R.id.home_blockfragment)
            return
        }

        if (SpUtils.getBoolean(MMKVName.SLEEP, false) == true) {
            //开启休眠
            val navController = findNavController(mBinding.homeFragmentcontainerview.id)
            navController.navigate(R.id.home_sleepfragment)
        }


    }

    override fun initObserve() {
        observeLiveData(mViewModel.data, ::processData)
    }

    private fun processData(data: String) {
    }

    override fun initRequestData() {
        // 模拟获取数据
        mViewModel.getData()
    }

    override fun onBackPressed() {
       /* val navController = findNavController(mBinding.homeFragmentcontainerview.id)
        val fragmentPopped = navController.popBackStack()
        Log.d("fragmentPopped", "onBackPressed: " + fragmentPopped)

        // 如果popBackStack()返回false，意味着没有Fragment可以返回了
        // 这里你可以假设已经回到了最开始的Fragment，或者根本就没有Fragment在栈中
        if (!fragmentPopped) {
            // 没有任何Fragment可以返回了，结束Activity
            // 获取当前时间戳


            val currentTime = System.currentTimeMillis()

            // 判断与上一次点击返回键的时间间隔是否小于1秒
            if (currentTime - backPressedTime < 1000) {
                super.onBackPressed() // 执行默认的返回键操作（退出Activity）
            } else {
                Toast.makeText(
                    this,
                    UiUtil.getStringRes(R.string.home_quit_app),
                    Toast.LENGTH_SHORT
                ).show()
                backPressedTime = currentTime // 更新上一次点击返回键的时间戳
            }
        }*/
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: ")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop: ")
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(message: ApiMessageEvent) {
        when (message.name) {
            MqName.IS_SLEEP -> {
                Log.d(TAG, "我收到了要开关机:" + message.data)
                if (message.data == "0") {
                    Log.d(TAG, "11event: IS_SLEEP:" + message.data)
                    //关掉休眠
                    SpUtils.putBoolean(MMKVName.SLEEP, false)
                    val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                    navController.navigate(R.id.home_action_home_sleepfragment_to_home_buyfragment)

                } else {
                    Log.d(TAG, "12event: IS_SLEEP:" + message.data)
                    AppManager.getAppManager().finishActivity(SettingActivity::class.java)
                    //开启休眠
                    val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                    navController.navigate(R.id.home_sleepfragment)
                }
            }

            MqName.initialization -> {
                val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                navController.navigate(R.id.home_action_home_sleepfragment_to_home_buyfragment)
            }

            MqName.BLOCK -> {
                if (message.data == "0") {
                    Log.d(TAG, "关掉锁机P:" + message.data)
                    //关掉锁机
                    SpUtils.putBoolean(MMKVName.BLOCK, false)
                    val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                    navController.navigate(R.id.home_action_home_blockfragment_to_home_buyfragment)
                } else {
                    Log.d(TAG, "开启锁机:" + message.data)
                    //开启锁机
                    val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                    navController.navigate(R.id.home_blockfragment)
                }
            }

            else -> {}
        }
    }


}