package com.dlc.laboratory.ui.leave

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.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.event.OnlineUserEvent
import com.dlc.eboard.iflytek.AudioPlayerManager
import com.dlc.eboard.serial.OnSerialScanListener
import com.dlc.eboard.serial.SerialPortHelper
import com.dlc.eboard.ui.auth.fragment.CardAuthFragment
import com.dlc.eboard.ui.dialog.CheckResultDialog
import com.dlc.eboard.ui.dialog.ResultEnum
import com.dlc.eboard.ui.dialog.SafetyCheckResultDialog
import com.dlc.eboard.ui.leave.LeaveActivity
import com.dlc.eboard.ui.widget.TitleBar
import com.rc.httpcore.client.ApiRepository
import org.greenrobot.eventbus.EventBus
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

/**
 * info
 *
 * @author ReiChin_
 */
class ExLeaveActivity : LeaveActivity() {
    private val weakHandler by lazy { WeakReferenceHandler(this) }
    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)

        viewBinding.titleBar.setSigned(false)
        viewBinding.titleBar.setShowNotice(false)
        viewBinding.navView.setShowHome(false)
    }

    override fun showDefaultFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(
            R.id.container,
            CardAuthFragment.newInstance(),
            CardAuthFragment.TAG
        )
        transaction.commitAllowingStateLoss()
    }

    override fun initData() {
        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)
        }
    }

    override fun enabledLogoutCountDown() = false

    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 val mSerialPortHelper by lazy {
        SerialPortHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (Constants.Mock.JUMP_FACE_AUTH) {
                    callStudentCheckApi(content)
                } else {
                    dispatchReadCardResult(content)
                }
            }
        })
    }

    private fun cardAuthIsTopFragment(): Boolean {
        return supportFragmentManager.findFragmentByTag(CardAuthFragment.TAG)?.isResumed ?: false
    }

    private fun dispatchReadCardResult(username: String) {
        // 判断顶部Fragment是否是CardAuthFragment
        if (!cardAuthIsTopFragment()) return

        supportFragmentManager.beginTransaction().apply {
            val fragment = ExLeaveFaceMatchingFragment.newInstance(username)
            replace(R.id.container, fragment, ExLeaveFaceMatchingFragment.TAG)
            commitAllowingStateLoss()
        }
    }

    /**
     * step1) 获取离开人员
     */
    private fun callStudentCheckApi(username: String) {
        val labConfig = LabApp.sLabConfig
        if (null == labConfig) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return
        }

        showLoading("查询中...")
        val disposable = ApiRepository.signOutCheck(false, labConfig.labId, username)
            .subscribe({ data ->
                if (data.state) {
                    callLeaveApi(data.code)
                } else {
                    dismissLoading()
                    // 弹出核验结果的Dialog，5秒后关闭Dialog
                    CheckResultDialog().apply {
                        setSuccess(false)
                        isCancelable = false
                        setFinishOnTouchOutside(false)
                    }.show(supportFragmentManager, CheckResultDialog::class.java.simpleName)
                }
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    /**
     * 2) 离开API
     */
    private fun callLeaveApi(code: String) {
        val disposable = ApiRepository.signOut(code)
            .subscribe({ success ->
                if (success) {
                    dismissLoading()
                    EventBus.getDefault().post(OnlineUserEvent())
                    val message = "离开成功"
                    AudioPlayerManager.speakVoice(R.raw.audio_success_leave)
                    SafetyCheckResultDialog(
                        this,
                        ResultEnum.SUCCESS,
                        message,
                        3000
                    ).apply {
                        setCancelable(false)
                        setCanceledOnTouchOutside(false)
                        setOnDismissListener { finish() }
                        show()
                    }
                }
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    class WeakReferenceHandler(obj: ExLeaveActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<ExLeaveActivity> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {

            }
        }
    }

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