package com.dlc.eboard.ui.finger

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 android.widget.Toast
import com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.databinding.ActivityFingerEnrollAuthBinding
import com.dlc.eboard.mqtt.MqttManager
import com.dlc.eboard.serial.OnSerialScanListener
import com.dlc.eboard.serial.SerialPortHelper
import com.dlc.eboard.ui.auth.AuthType
import com.dlc.eboard.ui.auth.OnAuthResultListener
import com.dlc.eboard.ui.auth.fragment.CardAuthFragment
import com.dlc.eboard.ui.auth.fragment.FaceAuthFragment
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.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.UserVo
import java.lang.ref.WeakReference

/**
 * 指纹录入前人员认证（刷卡+人脸）
 *
 * @author ReiChin_
 */
class EnrollAuthActivity :
    BaseCountDownActivity<ActivityFingerEnrollAuthBinding>(),
    OnAuthResultListener {
    private val weakHandler by lazy { WeakReferenceHandler(this) }
    override fun createViewBinding() = ActivityFingerEnrollAuthBinding.inflate(layoutInflater)

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

    private var mCardAuthFragment: CardAuthFragment? = null

    private var mFirstUser: UserVo? = null

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

        mCardAuthFragment = CardAuthFragment.newInstance(smaller = true)
        val fragments = mutableListOf(mCardAuthFragment!!, FaceAuthFragment.newInstance())
        val adapter = TabFragmentPagerAdapter(supportFragmentManager, fragments)
        viewBinding.viewPager.adapter = adapter

        mockSchoolCard()
    }

    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 {
        if (AuthType.CARD == authType) {
            mFirstUser = userVo
            showStep2()
        } else {
            if (mFirstUser?.userId != userVo.userId) {
                showToast("人员不一致")
                return false
            }

            // 人脸认证成功
            val intent = Intent(this, SelectFingerActivity::class.java)
            intent.putExtra("userId", userVo.userId)
            intent.putExtra("userName", userVo.userName)
            intent.putExtra("userType", userVo.userType)
            startActivity(intent)
            finish()
        }
        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 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: EnrollAuthActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<EnrollAuthActivity> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                dispatchReadCardResult(Constants.Mock.SCHOOL_NUM)
            }
        }
    }

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