package com.casic.br.view

import android.content.Context
import android.os.CountDownTimer
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.amap.api.location.AMapLocation
import com.casic.br.R
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.utils.LocaleConstant
import com.casic.br.utils.LocationHelper
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.isPhoneNumber
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.tuya.smart.android.user.api.IRegisterCallback
import com.tuya.smart.android.user.bean.User
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.home.sdk.bean.HomeBean
import com.tuya.smart.home.sdk.callback.ITuyaHomeResultCallback
import com.tuya.smart.sdk.api.IResultCallback
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.android.synthetic.main.include_left_back_title.*
import java.util.*

class RegisterActivity : KotlinBaseActivity() {

    private val kTag = "RegisterActivity"
    private val context: Context = this@RegisterActivity
    private lateinit var authenticateViewModel: AuthenticateViewModel
    private lateinit var userViewModel: UserViewModel

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

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        initLayoutImmersionBar(rootView)
        leftBackView.setOnClickListener { finish() }
        titleView.text = "注册账号"
    }

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

    override fun initEvent() {
        requestCodeButton.setOnClickListener {
            if (userPhoneView.text.toString().isBlank()) {
                "请输入手机号".show(this)
                return@setOnClickListener
            }
            if (!userPhoneView.text.toString().isPhoneNumber()) {
                "手机号不正确,请检查".show(this)
                return@setOnClickListener
            }
            //发送验证码
            TuyaHomeSdk.getUserInstance().sendVerifyCodeWithUserName(
                userPhoneView.text.toString(), "", LocaleConstant.COUNTRY_CODE, 1,
                object : IResultCallback {
                    override fun onSuccess() {
                        "发送验证码成功".show(context)
                    }

                    override fun onError(code: String?, error: String?) {
                        "发送验证码失败".show(context)
                    }
                })

            //开始倒计时
            object : CountDownTimer(60 * 1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    requestCodeButton.text = String.format("${millisUntilFinished / 1000}s")
                    requestCodeButton.isEnabled = false
                }

                override fun onFinish() {
                    requestCodeButton.text = "获取验证码"
                    requestCodeButton.isEnabled = true
                }
            }.start()
        }

        registerButton.setOnClickListener {
            val userPhone = userPhoneView.text.toString()
            if (userPhone.isBlank()) {
                "请输入手机号".show(this)
                return@setOnClickListener
            }
            val smsCode = requestCodeView.text.toString()
            if (smsCode.isBlank()) {
                "请输入验证码".show(this)
                return@setOnClickListener
            }
            val userPassword = userPasswordView.text.toString()
            if (userPassword.isBlank()) {
                "请输入密码".show(this)
                return@setOnClickListener
            }

            LoadingDialogHub.show(this, "注册中，请稍后")
            LocationHelper.obtainCurrentLocation(this, object : LocationHelper.ILocationListener {
                override fun onAMapLocationGet(aMapLocation: AMapLocation?) {
                    /**
                     * 家庭是智能生活 App SDK 开发下实际场景的最大单位。
                     * IoT 设备的添加、编辑、移除、状态变化的监听基于家庭下。
                     * 用户账号下创建任意多个家庭。
                     * */
                    if (aMapLocation == null) {
                        "信号弱，注册失败".show(context)
                        LoadingDialogHub.dismiss()
                        return
                    }
                    TuyaHomeSdk.getHomeManagerInstance().createHome(
                        "${userPhone}的家", aMapLocation.longitude, aMapLocation.latitude,
                        aMapLocation.address, arrayListOf("1"), object : ITuyaHomeResultCallback {
                            override fun onSuccess(bean: HomeBean?) {
                                registerWithTuya(
                                    userPhone,
                                    userPassword,
                                    smsCode,
                                    aMapLocation,
                                    bean?.homeId.toString()
                                )
                            }

                            override fun onError(errorCode: String?, errorMsg: String?) {
                                Log.e(kTag, "errorCode: $errorCode ---- $errorMsg")
                            }
                        })

//                    TuyaHomeSdk.getHomeManagerInstance().queryHomeList(object :
//                        ITuyaGetHomeListCallback {
//                        override fun onSuccess(homeBeans: List<HomeBean>) {
//                            registerWithoutTuya(
//                                userPhone,
//                                userPassword,
//                                aMapLocation,
//                                homeBeans[0].homeId.toString()
//                            )
//                        }
//
//                        override fun onError(errorCode: String, error: String) {
//
//                        }
//                    })
                }
            })
        }
    }

    /**
     * 涂鸦+自己服务器注册
     * */
    private fun registerWithTuya(
        userPhone: String,
        userPassword: String,
        smsCode: String,
        aMapLocation: AMapLocation,
        homeId: String
    ) {
        SaveKeyValues.putValue(LocaleConstant.HOME_ID, homeId)
        TuyaHomeSdk.getUserInstance().registerAccountWithPhone(
            LocaleConstant.COUNTRY_CODE, userPhone, userPassword, smsCode,
            object : IRegisterCallback {
                override fun onSuccess(user: User?) {
                    authenticateViewModel.obtainPublicKey()
                    authenticateViewModel.keyModel.observe(this@RegisterActivity, { keyModel ->
                        if (keyModel.code == 200) {
                            val keyString = keyModel.data!!.publicKey!!
                            val publicKey = RSAUtils.keyStrToPublicKey(keyString)
                            val dataByPublicKey = RSAUtils.encryptDataByPublicKey(
                                userPassword.toByteArray(), publicKey!!
                            )

                            val clientId = SaveKeyValues.getValue(
                                LocaleConstant.PUSH_CLIENT_ID, ""
                            ) as String
                            userViewModel.register(
                                userPhone,
                                dataByPublicKey,
                                aMapLocation.longitude,
                                aMapLocation.latitude,
                                clientId,
                                aMapLocation.province,
                                homeId
                            )
                            userViewModel.registerResult.observe(this@RegisterActivity, {
                                if (it.code == 200) {
                                    LoadingDialogHub.dismiss()
                                    navigatePageTo<RegisterResultActivity>()
                                }
                            })
                        }
                    })
                }

                override fun onError(code: String?, error: String?) {
                    LoadingDialogHub.dismiss()
                    "用户注册失败".show(context)
                }
            })
    }

    private fun registerWithoutTuya(
        userPhone: String,
        userPassword: String,
        aMapLocation: AMapLocation,
        homeId: String
    ) {
        authenticateViewModel.obtainPublicKey()
        authenticateViewModel.keyModel.observe(this@RegisterActivity, { keyModel ->
            if (keyModel.code == 200) {
                val keyString = keyModel.data!!.publicKey!!
                val publicKey = RSAUtils.keyStrToPublicKey(keyString)
                val dataByPublicKey = RSAUtils.encryptDataByPublicKey(
                    userPassword.toByteArray(), publicKey!!
                )

                val clientId = SaveKeyValues.getValue(
                    LocaleConstant.PUSH_CLIENT_ID, ""
                ) as String
                userViewModel.register(
                    userPhone,
                    dataByPublicKey,
                    aMapLocation.longitude,
                    aMapLocation.latitude,
                    clientId,
                    aMapLocation.province,
                    homeId
                )
                userViewModel.registerResult.observe(this@RegisterActivity, {
                    if (it.code == 200) {
                        LoadingDialogHub.dismiss()
                        navigatePageTo<RegisterResultActivity>()
                    }
                })
            }
        })
    }

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