package com.dlc.eboard.ui.auth.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.dlc.eboard.LabApp
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.FragmentAuthPasswordBinding
import com.dlc.eboard.ui.auth.AuthType
import com.dlc.eboard.ui.auth.OnAuthResultListener
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.AuthPwdReq
import com.rc.httpcore.vo.response.UserVo

/**
 * 输入密码
 *
 * @author ReiChin_
 */
class PasswordAuthFragment :
    RcBaseFragment<FragmentAuthPasswordBinding>() {

    companion object {
        const val TAG = "PasswordAuthFragment"

        fun newInstance() = PasswordAuthFragment()
    }

    private var mUserVo: UserVo? = null

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

    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.clear.setOnClickListener { viewBinding.input.text = null }
        viewBinding.confirm.setOnClickListener {
            generateAuthParam()?.let { callPasswordAuthApi(it) }
        }
    }

    private fun callPasswordAuthApi(param: AuthPwdReq) {
        showLoading()
        val disposable = ApiRepository.authPassword(param)
            .subscribe({ userVo ->
                dismissLoading()
                val activity = requireActivity()
                if (activity is OnAuthResultListener) {
                    activity.onAuthSuccess(AuthType.PASSWORD, userVo)
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun generateAuthParam(): AuthPwdReq? {
        if (null == LabApp.sLabConfig) {
            showToast("暂无实验室信息，即将重新获取")
//            CommonUtils.restartApp(requireContext().applicationContext)
            CommonUtils.restartApp(requireActivity())
            return null
        }

        val password = viewBinding.input.text.toString().trim()
        if (password.isEmpty()) {
            showToast("密码不能为空")
            return null
        }

        if (null == mUserVo) {
            showToast("核验失败，未获取到人员")
            return null
        }
        return AuthPwdReq().apply {
            num = CommonUtils.getAndroidId()
            labId = LabApp.sLabConfig!!.labId
            userId = mUserVo!!.userId
            pwd = password
        }
    }

    fun preUser(userVo: UserVo) {
        this.mUserVo = userVo
    }

}