package com.casic.br.view

import android.content.Context
import androidx.lifecycle.ViewModelProvider
import com.casic.br.R
import com.casic.br.utils.AuthenticationHelper
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.utils.LocaleConstant
import com.casic.br.utils.RSAUtils
import com.casic.br.vm.AuthenticateViewModel
import com.casic.br.vm.UserViewModel
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.*

class LoginActivity : KotlinBaseActivity() {

    private val context: Context = this@LoginActivity
    private lateinit var authenticateViewModel: AuthenticateViewModel
    private lateinit var userViewModel: UserViewModel

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

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

    override fun initData() {
        userPhoneView.setText(SaveKeyValues.getValue(LocaleConstant.ACCOUNT, "") as String)
        passwordView.setText(SaveKeyValues.getValue(LocaleConstant.PASSWORD, "") as String)

        authenticateViewModel = ViewModelProvider(this)[AuthenticateViewModel::class.java]
        userViewModel = ViewModelProvider(this)[UserViewModel::class.java]
    }

    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
            }
            SaveKeyValues.putValue(LocaleConstant.ACCOUNT, userPhone)
            SaveKeyValues.putValue(LocaleConstant.PASSWORD, userPassword)

            LoadingDialogHub.show(this, "登录中，请稍后")
            TuyaHomeSdk.getUserInstance().loginWithPhonePassword(
                LocaleConstant.COUNTRY_CODE, userPhone, userPassword, object : ILoginCallback {
                    override fun onSuccess(user: User?) {
                        if (user == null) {
                            SaveKeyValues.putValue(LocaleConstant.USER_IS_LOGIN, false)
                            LoadingDialogHub.dismiss()
                            "登录失败".show(context)
                        }
                        loginWithTuya(userPhone, userPassword)
                    }

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

    private fun loginWithTuya(userPhone: String, userPassword: String) {
        authenticateViewModel.obtainPublicKey()
        authenticateViewModel.keyModel.observe(this, { keyModel ->
            if (keyModel.code == 200) {
                val keyString = keyModel.data!!.publicKey!!
                /**
                 * 修改密码需要用到key，先存着
                 * */
                AuthenticationHelper.savePublicKey(keyString)
                val publicKey = RSAUtils.keyStrToPublicKey(keyString)

                val dataByPublicKey = RSAUtils.encryptDataByPublicKey(
                    userPassword.toByteArray(), publicKey!!
                )
                userViewModel.enter(keyModel.data!!.sid!!, userPhone, dataByPublicKey)
                userViewModel.loginResult.observe(this, {
                    if (it.code == 200) {
                        AuthenticationHelper.saveToken(it.data!!.token!!)
                        userViewModel.obtainUserDetail(userPhone)
                        userViewModel.userDetailResult.observe(this, { user ->
                            if (user.code == 200) {
                                SaveKeyValues.putValue(LocaleConstant.USER_IS_LOGIN, true)
                                SaveKeyValues.putValue(LocaleConstant.USER_MODEL, user.toJson())
                                SaveKeyValues.putValue(LocaleConstant.HOME_ID, user.data.syncDeptid)
                                LoadingDialogHub.dismiss()
                                PageNavigationManager.finishAllActivity()
                                navigatePageTo<MainActivity>()
                            }
                        })
                    }
                })
            }
        })
    }

    override fun observeRequestState() {
        userViewModel.loadState.observe(this, {
            LoadingDialogHub.dismiss()
        })
    }
}