package com.ccwangluo.accelerator.ui.login

import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.ccwangluo.accelerator.databinding.FragmentLoginPhoneBinding
import com.ccwangluo.accelerator.utils.LoginUtils
import com.hjq.toast.ToastUtils
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.utils.TitleBar
import com.xuexiang.xutil.common.StringUtils
import java.util.regex.Pattern


/**
 * A simple [Fragment] subclass.
 * Use the [PhoneLoginFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
@Page(name = "登录")
class PhoneLoginFragment : XPageFragment() {

    override fun initTitleBar(): TitleBar? {
        return null
    }

    private val mHandler: Handler = Handler(Looper.getMainLooper());
    private var mCountTime = 60
    private lateinit var loginViewModel: LoginViewModel


    private lateinit var binding: FragmentLoginPhoneBinding

    override fun inflateView(inflater: LayoutInflater?, container: ViewGroup?): View {
        binding = FragmentLoginPhoneBinding.inflate(inflater!!, container, false)
        loginViewModel = ViewModelProvider(requireActivity()).get(LoginViewModel::class.java)
        return binding.root
    }

    override fun initViews() {
        binding.phoneEt.addTextChangedListener {
            val phone = it.toString().trim()
            val authCdoe = binding.authCodeEt.text.toString()
            if (phone.length > 0) {
                binding.authCodeBtn.isEnabled = true
            } else {
                binding.authCodeBtn.isEnabled = false
            }
            if (isPhone(phone) && authCdoe.length > 0) {
                binding.login.isEnabled = true
            } else {
                binding.login.isEnabled = false
            }
        }

        binding.authCodeEt.addTextChangedListener {
            val authCdoe = it.toString().trim()
            val phone = binding.phoneEt.text.toString()
            if (isPhone(phone) && authCdoe.length > 0) {
                binding.login.isEnabled = true
            } else {
                binding.login.isEnabled = false
            }
            if (isPhone(phone) && authCdoe.length == 6 && binding.cbProtocol.isChecked) {
                loginViewModel.login(phone, authCdoe)
            }
        }

        loginViewModel.sendCodeState.observe(this, {
            if (it) {
                LoginUtils.startTimer()
            } else {
                binding.authCodeBtn.visibility = View.VISIBLE
                binding.authCodeWait.visibility = View.GONE
                binding.authCodeBtn.isEnabled = true
            }
        })

        loginViewModel.loginState.observe(this, {
            if (it) {
                popToBack()
            }
        })
        loginViewModel.timerNumber.observe(this, {
            if (it > 0) {
                binding.authCodeBtn.visibility = View.GONE
                binding.authCodeWait.visibility = View.VISIBLE
                binding.authCodeBtn.isEnabled = false
                binding.authCodeWait.setText("${it}秒后重新获得验证码")
            } else {
                resetCounter()
            }
        })
    }

    override fun initListeners() {
        binding.privacyAggreement.setOnClickListener({

        })

        binding.userAggreement.setOnClickListener {

        }

        binding.phoneClear.setOnClickListener {
            binding.phoneEt.setText("")
        }

        binding.authCodeBtn.setOnClickListener {
            val phone = binding.phoneEt.text.toString()
            if (StringUtils.isEmpty(phone) || !isPhone(phone)) {
                ToastUtils.show("输入正确的手机号")
                return@setOnClickListener
            }
            binding.authCodeBtn.isEnabled = false
            loginViewModel.getAuthCode(phone)
        }

        binding.btnBack.setOnClickListener {
            popToBack()
        }

        binding.login.setOnClickListener {
            //检查验证码,手机号格式
            val phone = binding.phoneEt.text.toString()
            val authCdoe = binding.authCodeEt.text.toString()

            if (StringUtils.isEmpty(phone) || !isPhone(phone)) {
                ToastUtils.show("输入正确的手机号")
                return@setOnClickListener
            }
            if (StringUtils.isEmpty(authCdoe) || authCdoe.length < 6) {
                ToastUtils.show("请输入验证码")
                return@setOnClickListener
            }
            //检查ck
            if (!binding.cbProtocol.isChecked) {
                ToastUtils.show("先勾选协议哦")
                return@setOnClickListener
            }

            loginViewModel.login(phone, authCdoe)
        }
    }

    fun isPhone(phone: String): Boolean {
        // 开头的"1"代表第一位为数字1，"[3-9]"代表第二位可以为3、4、5、6、7、8、9其中之一，"\\d{9}"代表后面是9位数字
        val regex = "1[3-9]\\d{9}"
        return Pattern.matches(regex, phone)
    }

    override fun onResume() {
        super.onResume()
        LoginUtils.registerTimerCallBack {
            loginViewModel.timerNumber.postValue(it)
        }
    }

    override fun onPause() {
        super.onPause()
        LoginUtils.unRegisterTimerCallBack()
    }

    //重置按钮状态
    fun resetCounter() {
        mCountTime = 60
        binding.authCodeBtn.visibility = View.VISIBLE
        binding.authCodeWait.visibility = View.GONE
        binding.authCodeBtn.setText("重新获取验证码")
        binding.authCodeBtn.isEnabled = true
    }
}