package com.casic.br.view

import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.amap.api.location.AMapLocation
import com.casic.br.R
import com.casic.br.base.BaseApplication
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.utils.LocationHelper
import com.casic.br.vm.DeviceViewModel
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.utils.Constant
import com.pengxh.kt.lite.vm.LoadState
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.home.sdk.builder.ActivatorBuilder
import com.tuya.smart.sdk.api.ITuyaActivatorGetToken
import com.tuya.smart.sdk.api.ITuyaSmartActivatorListener
import com.tuya.smart.sdk.bean.DeviceBean
import com.tuya.smart.sdk.enums.ActivatorModelEnum
import kotlinx.android.synthetic.main.activity_connect_device.*
import kotlinx.android.synthetic.main.include_left_back_title.*
import java.util.*

class ConnectDeviceActivity : KotlinBaseActivity() {

    private val kTag = "ConnectDeviceActivity"
    private lateinit var params: ArrayList<String>
    private lateinit var deviceViewModel: DeviceViewModel

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

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        initLayoutImmersionBar(rootView)
        leftBackView.setOnClickListener { finish() }
        titleView.visibility = View.GONE
    }

    override fun initData() {
        params = intent.getStringArrayListExtra(Constant.INTENT_PARAM)!!
        deviceViewModel = ViewModelProvider(this)[DeviceViewModel::class.java]
    }

    override fun initEvent() {
        nextStepButton.setOnClickListener {
            if (!confirmCheckBox.isChecked) {
                "请确认设备指示灯是否闪烁".show(this)
                return@setOnClickListener
            }
            LoadingDialogHub.show(this, "设备配网中，请稍后")
            val userModel = DeserializeModel.getUserModel()!!
            LocationHelper.obtainCurrentLocation(this, object : LocationHelper.ILocationListener {
                override fun onAMapLocationGet(aMapLocation: AMapLocation?) {
                    if (aMapLocation == null) {
                        "信号弱，添加设备失败".show(BaseApplication.obtainInstance())
                        LoadingDialogHub.dismiss()
                        return
                    }
                    TuyaHomeSdk.getActivatorInstance()
                        .getActivatorToken(DeserializeModel.getHomeId(),
                            object : ITuyaActivatorGetToken {
                                override fun onSuccess(token: String) {
                                    //调用 配网接口 需要提供路由器的 SSID（即 Wi-Fi 名称）、密码、从云端获取的 Token 等。
                                    val builder = ActivatorBuilder().apply {
                                        this.ssid = params[0]
                                        this.context = this@ConnectDeviceActivity
                                        this.password = params[1]
                                        this.activatorModel = ActivatorModelEnum.TY_EZ
                                        this.timeOut = 100
                                        this.token = token
                                        this.listener = object : ITuyaSmartActivatorListener {
                                            override fun onError(
                                                errorCode: String?,
                                                errorMsg: String?
                                            ) {
                                                Log.d(kTag, "errorMsg: $errorMsg")
                                                "添加设备超时".show(this@ConnectDeviceActivity)
                                                LoadingDialogHub.dismiss()
                                            }

                                            override fun onActiveSuccess(devResp: DeviceBean?) {
                                                //将绑定的设备存入自己的数据库
                                                deviceViewModel.addDevice(
                                                    devResp!!,
                                                    userModel,
                                                    "1",
                                                    aMapLocation
                                                )
                                            }

                                            override fun onStep(step: String?, data: Any?) {
                                                LoadingDialogHub.dismiss()
                                            }
                                        }
                                    }
                                    TuyaHomeSdk.getActivatorInstance().newMultiActivator(builder)
                                        .start()
                                }

                                override fun onFailure(s: String, s1: String) {
                                    Log.e(kTag, "onFailure: $s")
                                    LoadingDialogHub.dismiss()
                                }
                            })
                }
            })
        }
    }

    override fun observeRequestState() {
        deviceViewModel.loadState.observe(this, {
            when (it) {
                LoadState.Success -> {
                    LoadingDialogHub.dismiss()
                    navigatePageTo<AddDeviceResultActivity>()
                }
                else -> {
                    "添加失败，请重置设备重新绑定".show(this)
                    LoadingDialogHub.dismiss()
                }
            }
        })
    }
}