package com.dlc.exam.ui.exam

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.dlc.exam.ExamApp
import com.dlc.exam.R
import com.dlc.exam.common.ExamType
import com.dlc.exam.databinding.ActivityExamBinding
import com.dlc.exam.ui.MainActivity
import com.dlc.exam.ui.common.BaseCountDownActivity
import com.dlc.exam.ui.common.FaceMatchingFragment
import com.dlc.exam.ui.me.PersonalCenterActivity
import com.dlc.exam.ui.score.PaperQuViewModel
import com.dlc.exam.ui.widget.TitleBar
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.HandPaperReq
import com.rc.httpcore.vo.response.ExamTopic
import com.rc.httpcore.vo.response.ExamVerify

/**
 * 考试
 *
 * @author ReiChin_
 */
class ExamActivity : BaseCountDownActivity<ActivityExamBinding>(), ExamFragmentCallback,
    TitleBar.TitleListener {

    override fun createViewBinding() = ActivityExamBinding.inflate(LayoutInflater.from(this))

    private val viewModel by lazy {
        ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(
            PaperQuViewModel::class.java
        )
    }

    private lateinit var mExamType: String
    private lateinit var mExamId: String
    private var mExamTopic: ExamTopic? = null // 考卷信息

    private var mInExam = false // 是否正在考试中

    override fun initListener() {
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo?.nickName)
    }

    override fun initViews(savedInstanceState: Bundle?) {
        mExamType = intent.getStringExtra("exam_type")!!
        mExamId = intent.getStringExtra("examId") ?: "-1"
    }

    override fun initData() {
        super.initData()
        examStartVerify()
    }

    private var mExamVerify: ExamVerify? = null

    /**
     * 考试前后是否需要人脸验证
     */
    private fun examStartVerify() {
        showLoading("加载中...")
        val disposable = ApiRepository.examStartVerify(mExamType, mExamId)
            .subscribe({
                mExamVerify = it
                if (1 == it.preFaceVerify) {
                    // 需要
                    dismissLoading()
                    preFaceMatching(true)
                } else {
                    // 不需要
                    preFaceMatching(false)
                    queryExamTopic()
                }
            }, { throwable ->
                mExamVerify = null
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    /**
     * 生成考卷
     */
    private fun queryExamTopic() {
        val disposable = ApiRepository.examStart(mExamType, mExamId)
            .subscribe({
                dismissLoading()
                mInExam = true
                mExamTopic = it
                viewModel.setExamTopic(it)
            }, { throwable ->
                mExamTopic = null
                mInExam = false
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun preFaceMatching(match: Boolean) {
        if (match) {
            val transaction = supportFragmentManager.beginTransaction()
            transaction.add(
                R.id.container,
                FaceMatchingFragment.newInstance(FaceMatchingFragment.TYPE_PRE_EXAM),
                FaceMatchingFragment.FRAGMENT_TAG
            )
            transaction.commit()
        } else {
            val transaction = supportFragmentManager.beginTransaction()
            transaction.add(
                R.id.container,
                ExamFragment.newInstance(mExamType),
                ExamFragment.FRAGMENT_TAG
            )
            transaction.commit()
        }
    }

    override fun switchFragment(fragment: RcBaseFragment<out ViewBinding>, fragmentTag: String?) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, fragment, fragmentTag)
        transaction.commit()
    }

    /**
     * 考前人脸验证成功
     */
    override fun preFaceMatchingSuccess() {
        queryExamTopic()
        switchFragment(ExamFragment.newInstance(mExamType), ExamFragment.FRAGMENT_TAG)
    }

    /**
     * 交卷
     *
     * @param faceMatched true：已经通过了人脸验证
     */
    override fun submitExam(faceMatched: Boolean) {
        if (null == mExamTopic || null == mExamVerify) return
        if (mExamTopic!!.id.isNullOrEmpty()) return

        if (1 == mExamVerify!!.endFaceVerify && !faceMatched) {
            // 考后人脸验证
            switchFragment(
                FaceMatchingFragment.newInstance(FaceMatchingFragment.TYPE_END_EXAM),
                FaceMatchingFragment.FRAGMENT_TAG
            )
        } else {
            callSubmitExamApi()
        }
    }

    /**
     * 调用交卷API
     */
    private fun callSubmitExamApi() {
        showLoading("保存中..")
        val param = HandPaperReq().apply {
            id = mExamTopic!!.id
        }
        val disposable = ApiRepository.examHandPaper(param)
            .subscribe({
                mInExam = false
                dismissLoading()
                // 切换到结束画面
                it.examType = ExamType.decodeDescByType(mExamType)
                it.paperId = param.id
                viewModel.setHandPaper(it)
                switchFragment(
                    ExamCompletedFragment.newInstance(),
                    ExamCompletedFragment.FRAGMENT_TAG
                )
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    override fun onHomeViewClicked(view: View) {
        showInExamDialog {
            startActivity(Intent(this, MainActivity::class.java))
        }
    }

    override fun onLogoutViewClicked(view: View) {
        showInExamDialog {
            callLogoutApi {
                showToast("已退出登录")

                ExamApp.sLearnLoginVo = null
                HttpClient.token = null

                startActivity(Intent(this, MainActivity::class.java))
            }
        }
    }

    override fun onBackViewClicked(view: View) {
        onBackPressed()
    }

    override fun onUserViewClicked(view: View) {
        showInExamDialog {
            startActivity(Intent(this, PersonalCenterActivity::class.java))

            finish()
        }
    }

    override fun onBackPressed() {
        showInExamDialog {
            super.onBackPressed()
        }
    }

    private fun showInExamDialog(callback: () -> Unit) {
        if (!mInExam) {
            // 不在考试中，不弹窗
            callback.invoke()
            return
        }
        AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage("正在考试中，是否退出考试？")
            .setPositiveButton("退出") { _, _ ->
                callback.invoke()
            }.setNegativeButton("取消", null)
            .show()
    }

}