package com.dlc.eboard.ui.common

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.viewbinding.ViewBinding
import com.dlc.eboard.LabApp
import com.dlc.eboard.mqtt.event.NoticeMsgEvent
import com.dlc.eboard.ui.HomeActivity
import com.dlc.eboard.ui.finger.EnrollAuthActivity
import com.dlc.eboard.ui.notice.NoticeActivity
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.ITitleBar
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.core.util.FastClickDelegate
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * info
 *
 * @author ReiChin_
 */
abstract class BaseCountDownActivity<VB : ViewBinding> :
    RcBaseActivity<VB>(),
    ITitleBar.TitleListener,
    NavViewCompat.NavListener {

    protected abstract val mTitleBar: ITitleBar?
    protected abstract val mNavView: NavViewCompat?

    override fun initViews(savedInstanceState: Bundle?) {
        mTitleBar?.setTitleInfoFromSp()
        mTitleBar?.updateNotice(LabApp.sNoticeList)
        mTitleBar?.setTitleListener(this)
        mNavView?.setNavListener(this)
    }

    protected fun startCountDown() {
        if (enabledLogoutCountDown()) {
            mLogoutCounter = 0
            mCountDownHandler.removeMessages(WHAT_COUNT_DOWN_LOGOUT)
            mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN_LOGOUT)
        }

        if (enabledBackCountDown()) {
            mBackCounter = 0
            mCountDownHandler.removeMessages(WHAT_COUNT_DOWN_BACK)
            mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN_BACK)
        }
    }

    protected fun stopCountDown() {
        mLogoutCounter = 0
        mBackCounter = 0
        mCountDownHandler.removeMessages(WHAT_COUNT_DOWN_LOGOUT)
        mCountDownHandler.removeMessages(WHAT_COUNT_DOWN_BACK)
    }

    protected open fun enabledLogoutCountDown() = false

    protected open fun enabledBackCountDown() = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onResume() {
        super.onResume()
        startCountDown()
    }

    override fun onPause() {
        stopCountDown()
        super.onPause()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        mCountDownHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    override fun onUserInteraction() {
        startCountDown()
    }

    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            if (isDestroyed) return

            if (WHAT_COUNT_DOWN_BACK == msg.what) {
                val configTime = LabApp.sLabConfig?.returnTime ?: 0
                val maxTime = if (configTime <= 0) MAX_TIME_BACK else configTime
                val countDown = maxTime - mBackCounter
                if (countDown <= 0) {
                    backCountDownFinish()
                } else {
                    refreshBackCountDownView(countDown)
                    sendEmptyMessageDelayed(WHAT_COUNT_DOWN_BACK, 1000)
                }
                mBackCounter++
            } else if (WHAT_COUNT_DOWN_LOGOUT == msg.what) {
                val configTime = LabApp.sLabConfig?.logoutTime ?: 0
                val maxTime = if (configTime <= 0) MAX_TIME_LOGOUT else configTime
                val countDown = maxTime - mLogoutCounter
                if (countDown <= 0) {
                    logoutCountDownFinish()
                } else {
                    refreshLogoutCountDownView(countDown)
                    sendEmptyMessageDelayed(WHAT_COUNT_DOWN_LOGOUT, 1000)
                }
                mLogoutCounter++
            }
        }
    }

    protected open fun backCountDownFinish() {
        finish()
    }

    protected open fun refreshBackCountDownView(countDown: Int) {
        mNavView?.refreshCountDownView(countDown)
    }

    protected open fun logoutCountDownFinish() {
        callLogoutApi {
            LabApp.sUserVo = null
            startActivity(Intent(this@BaseCountDownActivity, HomeActivity::class.java))
//            CommonUtils.restartApp(applicationContext)
        }
    }

    protected open fun refreshLogoutCountDownView(countDown: Int) {
        mTitleBar?.refreshCountDownView(countDown)
    }

    protected fun callLogoutApi(callback: ((success: Boolean) -> Unit)? = null) {
//        showLoading("退出中...")
//        val disposable = ApiRepository.loginOut()
//            .subscribe({
//                dismissLoading()
        callback?.invoke(true)
//            }, {
//                dismissLoading()
//                callback?.invoke(false)
//            })
//        addDisposable(disposable)
    }

    private var mLogoutCounter = 0
    private var mBackCounter = 0

    companion object {
        private const val MAX_TIME_LOGOUT = 180
        private const val MAX_TIME_BACK = 120

        private const val WHAT_COUNT_DOWN_LOGOUT = 1
        private const val WHAT_COUNT_DOWN_BACK = 2
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNoticeMsgEvent(event: NoticeMsgEvent) {
        mTitleBar?.updateNotice(LabApp.sNoticeList)
    }

    override fun onNoticeViewClicked() {
        FastClickDelegate {
            val intent = Intent(this, NoticeActivity::class.java)
            startActivity(intent)
        }.dispatchFastClick()
    }

    override fun onHomeViewClicked() {
        logoutCountDownFinish()
    }

    override fun onBackViewClicked() {
        backCountDownFinish()
    }

    override fun onFingerEnrollViewClicked() {
        val intent = Intent(this, EnrollAuthActivity::class.java)
        startActivity(intent)
    }

}