package com.dlc.eboard.ui.auth

import android.content.Intent
import android.os.*
import android.view.KeyEvent
import androidx.viewbinding.ViewBinding
import com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.AuthTypeConfig
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.databinding.ActivityAuthDualBinding
import com.dlc.eboard.mqtt.MqttManager
import com.dlc.eboard.serial.OnSerialScanListener
import com.dlc.eboard.serial.SerialPortHelper
import com.dlc.eboard.ui.MainActivity
import com.dlc.eboard.ui.auth.fragment.CardAuthFragment
import com.dlc.eboard.ui.auth.fragment.FaceAuthFragment
import com.dlc.eboard.ui.auth.fragment.PasswordAuthFragment
import com.dlc.eboard.ui.common.BaseCountDownActivity
import com.dlc.eboard.ui.common.TabFragmentPagerAdapter
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.dlc.laboratory.ui.things.SelectAuthMethodActivity
import com.rc.core.log.RcLog
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.UserVo
import java.lang.ref.WeakReference

/**
 * 身份验证：人脸+密码、人脸+刷卡、刷卡+密码
 *
 * @author ReiChin_
 */
class DualAuthActivity :
    BaseCountDownActivity<ActivityAuthDualBinding>(),
    OnAuthResultListener {
    private val weakHandler by lazy {  WeakReferenceHandler(this) }
    override fun createViewBinding() = ActivityAuthDualBinding.inflate(layoutInflater)

    override val mTitleBar: TitleBar by lazy { viewBinding.titleBar }
    override val mNavView: NavViewCompat by lazy { viewBinding.navView }

    private lateinit var mAuthTypeConfig: String

    private var mFirstUser: UserVo? = null

    override fun initViews(savedInstanceState: Bundle?) {
        if (null == LabApp.sLabConfig) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return
        }
        mAuthTypeConfig = LabApp.sLabConfig!!.authType

        super.initViews(savedInstanceState)

        initLabelText()

        tabArray()?.let {
            val adapter = TabFragmentPagerAdapter(supportFragmentManager, it)
            viewBinding.viewPager.adapter = adapter
        }

        if (AuthTypeConfig.CARD_PASSWORD.type == mAuthTypeConfig) {
            if (intent.getBooleanExtra("card_auth", false)) {
                val user: UserVo = intent.getParcelableExtra("user")!!
                onAuthSuccess(AuthType.CARD, user)
            }

            mockSchoolCard()
        }
    }

    private var mCardAuthFragment: CardAuthFragment? = null
    private var mPasswordAuthFragment: PasswordAuthFragment? = null

    private fun tabArray(): MutableList<out RcBaseFragment<out ViewBinding>>? {
        return when (mAuthTypeConfig) {
            AuthTypeConfig.FACE_PASSWORD.type -> {
                mPasswordAuthFragment = PasswordAuthFragment.newInstance()
                mutableListOf(FaceAuthFragment.newInstance(), mPasswordAuthFragment!!)
            }
            AuthTypeConfig.FACE_CARD.type -> {
                mCardAuthFragment = CardAuthFragment.newInstance(smaller = true)
                mutableListOf(FaceAuthFragment.newInstance(), mCardAuthFragment!!)
            }
            AuthTypeConfig.CARD_PASSWORD.type -> {
                mCardAuthFragment = CardAuthFragment.newInstance(smaller = true)
                mPasswordAuthFragment = PasswordAuthFragment.newInstance()
                mutableListOf(mCardAuthFragment!!, mPasswordAuthFragment!!)
            }
            else -> null
        }
    }

    private fun initLabelText() {
        when (mAuthTypeConfig) {
            AuthTypeConfig.FACE_PASSWORD.type -> {
                viewBinding.step1Text.text = "人脸识别"
                viewBinding.step2Text.text = "密码验证"
            }
            AuthTypeConfig.FACE_CARD.type -> {
                viewBinding.step1Text.text = "人脸识别"
                viewBinding.step2Text.text = "刷卡验证"
            }
            AuthTypeConfig.CARD_PASSWORD.type -> {
                viewBinding.step1Text.text = "刷卡验证"
                viewBinding.step2Text.text = "密码验证"
            }
        }
    }

    private val mSerialPortHelper by lazy {
        SerialPortHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                mCardAuthFragment?.let {
                    if (it.isResumed) dispatchReadCardResult(content)
                }
            }
        })
    }

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

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

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        mSerialPortHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

    private fun dispatchReadCardResult(username: String) {
        if (null == LabApp.sLabConfig) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return
        }

        showLoading()
        val disposable = ApiRepository.authCard(LabApp.sLabConfig!!.labId, username)
            .subscribe({ userVo ->
                dismissLoading()
                onAuthSuccess(AuthType.CARD, userVo)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    override fun enabledBackCountDown() = true

    override fun onAuthSuccess(authType: AuthType, userVo: UserVo): Boolean {
        when (mAuthTypeConfig) {
            AuthTypeConfig.FACE_PASSWORD.type -> {
                if (authType == AuthType.FACE) {
                    showStep2()
                    mPasswordAuthFragment?.preUser(userVo)
                } else {
                    authSuccess(userVo)
                }
            }
            AuthTypeConfig.FACE_CARD.type -> {
                if (authType == AuthType.FACE) {
                    mFirstUser = userVo
                    showStep2()
                    mockSchoolCard()
                } else {
                    if (mFirstUser?.userId != userVo.userId) {
                        showToast("人员不一致")
                        return false
                    }
                    authSuccess(userVo)
                }
            }
            AuthTypeConfig.CARD_PASSWORD.type -> {
                if (authType == AuthType.CARD) {
                    showStep2()
                    mPasswordAuthFragment?.preUser(userVo)
                } else {
                    authSuccess(userVo)
                }
            }
        }
        return true
    }

    private fun showStep2() {
        viewBinding.step1Image.setImageResource(R.mipmap.icon_sfyz_cg)
        viewBinding.step2Image.setImageResource(R.mipmap.icon_sfyz_deb)
        viewBinding.viewPager.currentItem = 1
    }

    private fun authSuccess(userVo: UserVo) {
        RcLog.info("DualAuthActivity#onAuthSuccess() configAuthType=${mAuthTypeConfig}, userVo=${userVo}")
        LabApp.sUserVo = userVo
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    private fun mockSchoolCard() {
        if (Constants.Mock.SCHOOL_NUM_TEST) {
//            object : Handler(Looper.getMainLooper()) {
//
//                override fun handleMessage(msg: Message) {
////                    dispatchReadCardResult(Constants.Mock.SCHOOL_NUM)
//
//                }
//            }.
            weakHandler.sendEmptyMessageDelayed(1, 1500)
        }
    }
    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: DualAuthActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<DualAuthActivity> = WeakReference(obj)
        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                dispatchReadCardResult(Constants.Mock.SCHOOL_NUM)
            }
        }
    }

    override fun onDestroy() {
        weakHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }
}