package com.dlc.exam.ui.login

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.dlc.exam.ExamApp
import com.dlc.exam.common.CommonUtils
import com.dlc.exam.common.Constants
import com.dlc.exam.databinding.FragmentStudentCardBinding
import com.dlc.exam.ui.common.FaceMatchingFragment
import com.rc.core.log.RcLog
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import com.rc.httpcore.vo.response.LearnLoginVo

/**
 * info
 *
 * @author ReiChin_
 */
class StudentCardFragment : RcBaseFragment<FragmentStudentCardBinding>() {

    companion object {

        const val FRAGMENT_TAG = "StudentCardFragment"

        fun newInstance() = StudentCardFragment()
    }

    private var isLogin: String = "0"

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentStudentCardBinding {
        return FragmentStudentCardBinding.inflate(inflater, container, false)
    }

    private var mFragmentCallback: LoginFragmentCallback? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mFragmentCallback = context as? LoginFragmentCallback
    }

    override fun onDetach() {
        super.onDetach()
        mFragmentCallback = null
    }

    override fun initViews(savedInstanceState: Bundle?) {
    }

    fun dispatchReadCardResult(username: String) {
//        showLoading("查询中...")
        showToast("查询中...")
        val disposable = ApiRepository.cardNum(username)
            .subscribe({ data ->
                ExamApp.sLearnLoginVo = data
                if (Constants.Mock.JUMP_LOGON_FACE) {
                    // 跳过登录人脸检测
                    callLearnLoginApi(username) {
                        requireActivity().apply {
                            setResult(Activity.RESULT_OK)
                            finish()
                        }
                    }
                } else {
                    // 切换到人脸比对画面
                    val fragment =
                        requireFragmentManager().findFragmentByTag(FaceMatchingFragment.FRAGMENT_TAG)
                                as? FaceMatchingFragment
                            ?: FaceMatchingFragment.newInstance(FaceMatchingFragment.TYPE_LOGIN,
                                username)
                    fragment.arguments = Bundle().apply {
                        putInt("type", FaceMatchingFragment.TYPE_LOGIN)
                        putString("username", username)
                        putString("islogin", isLogin)
                    }
                    mFragmentCallback?.switchFragment(fragment)
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)

//        val disposable = ApiRepository.learnLogin(username,
//            CommonUtils.getAndroidId(requireContext()),
//            true,
//            isLogin)
//            .subscribe({
//                dismissLoading()
//                ExamApp.sLearnLoginVo = it
//                if (Constants.Mock.JUMP_LOGON_FACE) {
//                    // 跳过登录人脸检测
//                    callLearnLoginApi(username) {
//                        requireActivity().apply {
//                            setResult(Activity.RESULT_OK)
//                            finish()
//                        }
//                    }
//                } else {
//                    // 切换到人脸比对画面
//                    val fragment =
//                        requireFragmentManager().findFragmentByTag(FaceMatchingFragment.FRAGMENT_TAG)
//                                as? FaceMatchingFragment
//                            ?: FaceMatchingFragment.newInstance(FaceMatchingFragment.TYPE_LOGIN,
//                                username)
//                    fragment.arguments = Bundle().apply {
//                        putInt("type", FaceMatchingFragment.TYPE_LOGIN)
//                        putString("username", username)
//                        putString("islogin", isLogin)
//                    }
//                    mFragmentCallback?.switchFragment(fragment)
//                }
//
//            }) { throwable ->
//                dismissLoading()
//                if (throwable != null) {
//                    val netException = throwable as NetException
//                    if (netException != null && netException.code == "4466") {
//                        netException.message?.let { alertAialogMsg(username, it) }
//                    }
//                }else{
//                    throwable!!.printStackTrace()
//                    showNetError(throwable)
//                }
//
//
//            }
//        addDisposable(disposable)


    }

    private fun callLearnLoginApi(username: String, callback: () -> Unit) {
        showLoading("查询中...")
        val disposable = ApiRepository.learnLogin(username,
            CommonUtils.getAndroidId(requireContext()),
            true,
            isLogin)
            .subscribe({ data ->
                dismissLoading()
                ExamApp.sLearnLoginVo = data
                callback.invoke()
            }, { throwable ->
                dismissLoading()
                val netException = throwable as NetException
                if (netException.code == "4466") {
                    netException.message?.let { alertAialogMsg(username, it) }
                } else {
                    throwable.printStackTrace()
                    showNetError(throwable)
                }
            })
        addDisposable(disposable)
    }

    private fun alertAialogMsg(username: String, expiresIn: String) {
        val alertAialog: AlertDialog
        val builder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
            .setTitle("用户操作")
            .setMessage(expiresIn)
            .setPositiveButton("确认", DialogInterface.OnClickListener { dialog, which ->
                dialog.dismiss() // 关闭对话框
                isLogin = "1"
                dispatchReadCardResult(username)

            }) // 添加取消按钮
            .setNegativeButton("取消",
                DialogInterface.OnClickListener { dialog, which -> // 点击取消，对话框消失
                    dialog.dismiss()
                })
        alertAialog = builder.create()
        alertAialog.show()
    }
}