package com.ccwangluo.accelerator.ui.login

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.ViewModelProvider
import com.ccwangluo.accelerator.databinding.FragmentLoginPhoneBinding
import com.ccwangluo.accelerator.ui.web.BlankActivity
import com.ccwangluo.accelerator.ui.web.CommonWebViewFragment
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.github.shadowsocks.http.HttpConfig
import com.hjq.toast.ToastUtils
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xutil.common.StringUtils
import java.util.regex.Pattern

@Page(name = "phone_login")
class PhoneLoginActivity : XPageActivity() {
    private lateinit var loginViewModel: LoginViewModel
    private lateinit var binding: FragmentLoginPhoneBinding
    private var mCountTime = 60

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentLoginPhoneBinding.inflate(layoutInflater)
        loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        setContentView(binding.root)
        initViews()
        initListeners()
        DataRePortUtils.report("st_login_vercode_show")
    }

    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.phoneEt.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                DataRePortUtils.report("st_login_ph_input")
            }
        }
        binding.authCodeEt.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                DataRePortUtils.report("st_login_vercode_write")
            }
        }

        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(binding.phoneEt.text.toString())
            } else {
                binding.authCodeBtn.visibility = View.VISIBLE
                binding.authCodeWait.visibility = View.GONE
                binding.authCodeBtn.isEnabled = true
            }
        })

        loginViewModel.loginState.observe(this, {
            if (it) {
                LoginUtils.stopTimer()
                DataRePortUtils.report("role_entry", mutableMapOf("login" to "login_vercode"))
                finish()
            }
        })
        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(it)
            }
        })
        loginViewModel.timerNumber.postValue(-1)

        binding.phoneEt.setText(LoginUtils._phone)

    }


    fun initListeners() {
        binding.privacyAggreement.setOnClickListener {
            val intent = Intent(this, BlankActivity::class.java)
            intent.putExtra(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.url_privacy_policy)
            startActivity(intent)
        }

        binding.userAggreement.setOnClickListener {
            val intent = Intent(this, BlankActivity::class.java)
            intent.putExtra(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.url_user_agreement)
            startActivity(intent)
        }

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

        binding.authCodeBtn.setOnClickListener {
            DataRePortUtils.report("st_login_vercode_request_clk")
            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 {
            finish()
        }

        binding.login.setOnClickListener {
            DataRePortUtils.report("st_login_vercode_btn_clk")
            //检查验证码,手机号格式
            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(i: Int) {
        mCountTime = 60
        binding.authCodeBtn.visibility = View.VISIBLE
        binding.authCodeWait.visibility = View.GONE
        if (i == -1) {
            binding.authCodeBtn.setText("获取验证码")
        } else {
            binding.authCodeBtn.setText("重新获取验证码")
        }
        binding.authCodeBtn.isEnabled = true
    }

}