package com.casic.br.view

import android.content.Context
import com.casic.br.R
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.utils.LocaleConstant
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.extensions.toJson
import com.pengxh.kt.lite.utils.PageNavigationManager
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.tuya.smart.android.user.api.ILoginCallback
import com.tuya.smart.android.user.bean.User
import com.tuya.smart.home.sdk.TuyaHomeSdk
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_login.userPhoneView
import kotlinx.android.synthetic.main.activity_register.*

class LoginActivity : KotlinBaseActivity() {

    private val context: Context = this@LoginActivity

    override fun initLayoutView(): Int = R.layout.activity_login

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun initData() {

    }

    override fun observeRequestState() {

    }

    override fun initEvent() {
        registerView.setOnClickListener {
            navigatePageTo<RegisterActivity>()
        }

        loginButton.setOnClickListener {
            val userPhone = userPhoneView.text.toString()
            if (userPhone.isBlank()) {
                "请输入手机号".show(this)
                return@setOnClickListener
            }
            val userPassword = passwordView.text.toString()
            if (userPassword.isBlank()) {
                "请输入密码".show(this)
                return@setOnClickListener
            }

            LoadingDialogHub.show(this, "登录中，请稍后")
            TuyaHomeSdk.getUserInstance()
                .loginWithPhonePassword("86", userPhone, userPassword, object : ILoginCallback {
                    override fun onSuccess(user: User?) {
                        SaveKeyValues.putValue(LocaleConstant.USER_IS_LOGIN, true)
                        SaveKeyValues.putValue(LocaleConstant.USER_MODEL, user!!.toJson())
                        LoadingDialogHub.dismiss()
                        navigatePageTo<MainActivity>()
                        PageNavigationManager.finishAllActivity()
                    }

                    override fun onError(code: String?, error: String?) {
                        SaveKeyValues.putValue(LocaleConstant.USER_IS_LOGIN, false)
                        LoadingDialogHub.dismiss()
                        "登录失败".show(context)
                    }
                })
        }
    }
}