package com.zj365.mime.act

import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.base.act.BaseVmAct
import com.xty.common.arouter.ARouterUrl
import com.xty.common.util.CommonToastUtils
import com.zj365.mime.databinding.ActHeartLowBinding
import com.zj365.mime.vm.WearManagerVm
import com.xty.network.model.WearManagerBean
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 心动过缓提醒
 */
@Route(path = ARouterUrl.HEART_LOW_REMIND)
class HeartLowRemindAct : BaseVmAct<WearManagerVm>() {
    val binding by lazy { ActHeartLowBinding.inflate(layoutInflater) }

    var heartRate: WearManagerBean.HeartRate? = null

    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
        isDarkBar = true
        val serializable = intent.extras!!.getSerializable("heartRate")
        heartRate = if (null == serializable) null else  serializable as WearManagerBean.HeartRate

    }

    override fun initView() {
        super.initView()

        statusBar(binding.title.mView)
        binding.mSwitchBtn.isChecked = heartRate?.state == 0
        binding.title.mIvBack.setOnClickListener {
            bundle.clear()
            bundle.putSerializable("heartRate", heartRate)
            intent.putExtras(bundle)
            setResult(RESULT_OK, intent)
            finish()
        }
        binding.title.mTvTitle.text = "心动过缓提醒"

        binding.mSwitchBtn.apply {//勿扰模式开关
            setOnCheckedChangeListener { _, isChecked ->
                heartRate?.let { mViewModel.heartRateSetting(if (isChecked) 0 else 1, it) }
                clickFast()
            }
        }

    }

    override fun onBackPressed() {
        bundle.clear()
        bundle.putSerializable("heartRate", heartRate)
        intent.putExtras(bundle)
        setResult(RESULT_OK, intent)
        finish()
    }

    /**
     * 一秒之内不能点击
     */
    fun clickFast() {
        binding.mSwitchBtn.isEnabled = false
        mainScope.launch {
            delay(1000)
            binding.mSwitchBtn.isEnabled = true
        }
    }

    override fun liveObserver() {
        mViewModel.settingLive.observe(this){
            heartRate?.state = if (binding.mSwitchBtn.isChecked) 0 else 1
            CommonToastUtils.showSucceedToast("设置成功")
        }
    }
}