package com.casic.br.view.device

import android.os.Handler
import android.util.Log
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.selectCategory
import com.casic.br.extensions.toBatteryImage
import com.casic.br.utils.DeserializeModel
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.timestampToCompleteDate
import com.pengxh.kt.lite.utils.WeakReferenceHandler
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.bean.DeviceBean
import kotlinx.android.synthetic.main.activity_co_senser.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

class CoSensorActivity : KotlinBaseActivity() {

    private val dataTimer by lazy { Timer() }//数据上传Timer
    private val dataLinkedList = LinkedList<HashMap<String, Any>>()
    private lateinit var weakReference: WeakReferenceHandler

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

    override fun observeRequestState() {

    }

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

        leftBackView.setOnClickListener { finish() }
        rightOperateView.visibility = View.GONE
    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)
        dataTimer.schedule(object : TimerTask() {
            override fun run() {
                TuyaHomeSdk.newHomeInstance(DeserializeModel.getHomeId())
                    .getHomeDetail(object : ITuyaHomeResultCallback {
                        override fun onSuccess(bean: HomeBean) {
                            bean.deviceList.forEach {
                                val selectedCategory = it.selectCategory()
                                if (selectedCategory == "cobj") {
                                    //一氧化碳报警器
                                    val msg = weakReference.obtainMessage()
                                    msg.what = 2022102003
                                    msg.obj = it
                                    weakReference.sendMessage(msg)
                                }
                            }
                        }

                        override fun onError(errorCode: String, errorMsg: String) {
                            Log.d("Casic", "TAndHSensorActivity => onError: $errorMsg")
                        }
                    })
            }
        }, 0, 5000)
    }

    private val callback = Handler.Callback { message ->
        if (message.what == 2022102003) {
            if (!this.isDestroyed) {
                val it = message.obj as DeviceBean
                deviceStateView.text = if (it.isOnline) {
                    "设备在线"
                } else {
                    "设备已离线"
                }
                titleView.text = it.name
                Glide.with(this)
                    .load(it.iconUrl)
                    .apply(RequestOptions.circleCropTransform())
                    .placeholder(R.mipmap.load_image_error)
                    .into(deviceLogoView)

                /**
                 * {"11":0,"1":"2","15":100}
                 *
                 * 11 - 故障告警
                 * 1 - CO检测状态
                 * 15 - 电池电量
                 * */
                val dataMap = HashMap<String, Any>()
                if (it.isOnline) {
                    val value = it.dps["15"].toString()
                    batteryView.setBackgroundResource(value.toBatteryImage())
                    batteryValueView.text = "${value}%"

                    val f = it.dps["11"]
                    faultAlarmView.text = if (f == 0) {
                        "正常"
                    } else {
                        "异常"
                    }
                    faultAlarmTimeView.text = if (faultAlarmView.text.toString() == "异常") {
                        System.currentTimeMillis().timestampToCompleteDate()
                    } else {
                        "--:--:--"
                    }

                    val c = it.dps["1"] as String
                    coAlarmView.text = if (c == "2") {
                        "正常"
                    } else {
                        "异常"
                    }
                    coAlarmTimeView.text = if (coAlarmView.text.toString() == "异常") {
                        System.currentTimeMillis().timestampToCompleteDate()
                    } else {
                        "--:--:--"
                    }
                } else {
                    batteryView.setBackgroundResource("0".toBatteryImage())
                    batteryValueView.text = "0%"

                    faultAlarmView.text = "已离线"
                    faultAlarmTimeView.text = "--:--:--"

                    coAlarmView.text = "已离线"
                    coAlarmTimeView.text = "--:--:--"
                }

                dataLinkedList.add(dataMap)
            }
        }
        true
    }

    override fun initEvent() {

    }

    override fun onDestroy() {
        super.onDestroy()
        dataTimer.cancel()
    }
}