package com.rdiot.yx485.ui.login

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.drake.net.utils.TipUtils
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.base.LoginViewModelFactory
import com.rdiot.yx485.databinding.FraLoginSmsBinding
import com.rdiot.yx485.net.SmsLimit
import com.rdiot.yx485.net.getSms
import com.rdiot.yx485.net.loginViaSMS
import com.rdiot.yx485.ui.login.model.LoginRecord
import com.rdiot.yx485.ui.login.model.LoginType
import com.rdiot.yx485.ui.login.model.LoginViewModel
import com.rdiot.yx485.ui.main.MainActivity
import com.rdiot.yx485.ui.web.WebActivity
import com.rdiot.yx485.util.*
import kotlinx.coroutines.delay

/**
 * 短信登录
 * @author mR2hao
 * @date 2022/11/15
 */
class LoginSmsFragment : BaseFragment<FraLoginSmsBinding>(), ClickLimitListener {
    override fun getLayoutId() = R.layout.fra_login_sms
    private val loginViewModel: LoginViewModel by activityViewModels { LoginViewModelFactory() }

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        binding.vm = loginViewModel
        loginViewModel.smsCode.set("")
        loginViewModel.phone.set(LocalData.lastLoginRecord?.phone)

        binding.btnGetSms.setClickLimitListener(this)
        binding.btnLogin.setClickLimitListener(this)
        binding.tvSa.setClickLimitListener(this)
        binding.tvPp.setClickLimitListener(this)
        binding.llReadPolicy.setClickLimitListener(this)

        binding.nb.setRightClickListener {
            loginViewModel.isRead.postValue(false)
            loginViewModel.phone.get()?.let { phone ->
                loginViewModel.clear(phone.length != 11)
            }
            findNavController().navigate(R.id.action_loginSmsFragment_to_loginPwdFragment)
        }


    }

    /** 获取短信验证码 */
    private fun getSmsCode() {
        LogUtils.w("getSmsCode: 无短信频率限制!!!!!!!!!!!!!!!")
        LocalData.lastGetCodeTime = curTime
        scopeNetLife {
            val resp = getSms(loginViewModel.phone.get(), SmsLimit.LOGIN).await()
            if (resp.isSucceed()) {
                LocalData.lastGetCodeTime = curTime
                TipUtils.toast(getString(R.string.sms_has_been_sent))
            }
        }
    }

    /** 登录 */
    private fun login() {
        loginViewModel.isRead.value?.let { isRead ->
            if (isRead) {
                scopeDialog(cancelable = BuildConfig.DEBUG) {
                    //防闪屏
                    delay(500)
                    loginViaSMS(loginViewModel.phone.get(), loginViewModel.smsCode.get())
                        .await()
                        .saveLocal()
                    (act as LoginActivity).isTokenInvalid = false

                    //保存登录记录
                    LocalData.lastLoginRecord = LoginRecord(
                        loginViewModel.phone.get(),
                        null,
                        LoginType.SMS
                    )

                    act.finishGoTo(MainActivity::class.java)
                }
            } else {
                TipUtils.toast(getString(R.string.please_read))
            }

        }

    }

    override fun onClickLimit(view: View) {
        when (view) {
            binding.btnGetSms -> {
                getSmsCode()
            }

            binding.btnLogin -> {
                login()
            }

            binding.llReadPolicy -> {
                loginViewModel.isRead.postValue(!loginViewModel.isRead.value!!)
            }

            binding.tvSa -> {
                act.clearGoTo(
                    WebActivity.getNewWebIntent(
                        act,
                        "https://app.yongxulvjian.com/#/ServiceAgreement",
                        "用户协议"
                    )
                )
            }

            binding.tvPp -> {
                act.clearGoTo(
                    WebActivity.getNewWebIntent(
                        act,
                        "https://app.yongxulvjian.com/#/PrivacyPolicy",
                        "隐私政策"
                    )
                )
            }
        }
    }
}