package com.dlc.eboard.ui.auth

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import com.dlc.eboard.LabApp
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.databinding.ActivityAuthFourChoiceBinding
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.FingerAuthFragment
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.rc.core.log.RcLog
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.UserVo
import java.lang.ref.WeakReference

/**
 * 身份验证：人脸/指纹/刷卡/密码  四选一认证
 *
 * @author ReiChin_
 */
class FourChoiceAuthActivity :
    BaseCountDownActivity<ActivityAuthFourChoiceBinding>(),
    OnAuthResultListener {
    private val weakHandler by lazy {  WeakReferenceHandler(this) }
    override fun createViewBinding() = ActivityAuthFourChoiceBinding.inflate(layoutInflater)

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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)

        val tabArray = mutableListOf(
            FaceAuthFragment.newInstance(),
            FingerAuthFragment.newInstance(),
            CardAuthFragment.newInstance()/*,
            PasswordAuthFragment.newInstance()*/
        )

        val adapter = TabFragmentPagerAdapter(supportFragmentManager, tabArray)
        viewBinding.viewPager.adapter = adapter

        viewBinding.faceAuth.setOnClickListener {
            viewBinding.viewPager.currentItem = 0
        }
        viewBinding.fingerAuth.setOnClickListener {
            viewBinding.viewPager.currentItem = 1
        }
        viewBinding.cardAuth.setOnClickListener {
            viewBinding.viewPager.currentItem = 2
            mockSchoolCard()
        }
//        viewBinding.passwordAuth.setOnClickListener {
//            viewBinding.viewPager.currentItem = 3
//        }
    }

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

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

    override fun enabledBackCountDown() = true

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

    private val mSerialPortHelper by lazy {
        SerialPortHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (2 == viewBinding.viewPager.currentItem) {
                    dispatchReadCardResult(content)
                }
            }
        })
    }

    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 onAuthSuccess(authType: AuthType, userVo: UserVo): Boolean {
        RcLog.info("FourChoiceAuthActivity#onAuthSuccess() authType=${authType}, configAuthType=${LabApp.sLabConfig?.authType}, userVo=${userVo}")
        LabApp.sUserVo = userVo
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
        return true
    }

    private fun mockSchoolCard() {
        if (Constants.Mock.SCHOOL_NUM_TEST) {
//            object : Handler(Looper.getMainLooper()) {
//
//                override fun handleMessage(msg: Message) {
//                    dispatchReadCardResult(Constants.Mock.SCHOOL_NUM)
//                }
//            }.sendEmptyMessageDelayed(1, 1500)
            weakHandler.sendEmptyMessageDelayed(1, 1500)
        }
    }


    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: FourChoiceAuthActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<FourChoiceAuthActivity> = WeakReference(obj)
        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                dispatchReadCardResult(Constants.Mock.SCHOOL_NUM)
            }
        }
    }

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