package com.bc_chat.account.fragment

import android.view.View
import com.bc_chat.account.R
import com.bc_chat.account.contract.ForPwdContract
import com.bc_chat.account.databinding.FragmentStep2ForgetpwdBinding
import com.bc_chat.account.presenter.ForgetPresenter
import com.zhaohaoting.framework.abs.AbsV4Fragment
import com.zhaohaoting.framework.utils.ToastUtils
import java.lang.Exception

/**
 * author：Created by zhaohaoting on 2019/2/21
 * email：526309416@qq.com
 * desc：忘记密码第二步
 */
class Step2ForgetPwdFragment : AbsV4Fragment<ForgetPresenter>(), View.OnClickListener, ForPwdContract.View {


    private val binding by lazy {
        rootDataBinding as FragmentStep2ForgetpwdBinding
    }
    private var phone: String? = null
    private var verCode: String? = null

    override fun initPresenter(): ForgetPresenter? {
        return ForgetPresenter(this)
    }

    fun setConfirmListener(listener: (password: String) -> Unit) {
        confirmListener = object : OnConfirmListener {
            override fun confirm(password: String) {
                listener(password)
            }
        }
    }

    override fun initialize() {
        binding.onClickEvent = this
        arguments?.let {
            phone = it.getString("phone")
            verCode = it.getString("verCode")
        }
    }

    override fun showLoading(vararg task: Any?) {
        super.showLoading(*task)
        binding.btnConfirm.isEnabled = false
    }

    override fun forPadSuccess() {
        confirmListener?.confirm(binding.etPassword.text.toString().trim())
        binding.btnConfirm.isEnabled = true
    }

    override fun forPadFailure(exception: Exception?) {
        binding.btnConfirm.isEnabled = true
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_confirm -> {
                val password = binding.etPassword.text.toString().trim()
                val confirmPassword = binding.etConfirmPassword.text.toString().trim()
                if (password.isNullOrEmpty() || password.length < 6) {
                    ToastUtils.show("输入的原密码不能少于六位")
                    return
                }
                if (confirmPassword.isNullOrEmpty() || confirmPassword.length < 6) {
                    ToastUtils.show("输入的新密码不能少于六位")
                    return
                }
                if (!password.equals(confirmPassword)) {
                    ToastUtils.show("两次输入的密码不相同")
                    return
                }
                presenter.regetPwd(phone, password)
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.fragment_step2_forgetpwd
    }

    private var confirmListener: OnConfirmListener? = null

    interface OnConfirmListener {
        fun confirm(password: String)
    }
}

