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.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_ch4_senser.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

/**
 * 可燃气体探测器
 * TODO 数据上报暂缓
 * */
class GasSensorActivity : 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_ch4_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)
        //每隔5s传一次数据到服务器
        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 == "rqbj") {
                                    val msg = weakReference.obtainMessage()
                                    msg.what = 2022102101
                                    msg.obj = it
                                    weakReference.sendMessage(msg)
                                }
                            }
                        }

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

    private val callback = Handler.Callback { message ->
        if (message.what == 2022102101) {
            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)

                val dataMap = HashMap<String, Any>()
                if (it.isOnline) {
                    /**
                     * {"11":0,"1":"normal"}
                     *
                     * {"fault":{"id":"11","name":"故障告警"},"gas_sensor_state":{"id":"1","name":"燃气检测状态"}}
                     * */
                    val f = it.dps["11"]
                    faultAlarmView.text = if (f == 0) {
                        "正常"
                    } else {
                        "异常"
                    }
                    faultAlarmTimeView.text = if (faultAlarmView.text.toString() == "异常") {
                        System.currentTimeMillis().timestampToCompleteDate()
                    } else {
                        "--:--:--"
                    }

                    val s = it.dps["1"] as String
                    fireAlarmView.text = if (s == "normal") {
                        "正常"
                    } else {
                        "异常"
                    }
                    fireAlarmTimeView.text = if (fireAlarmView.text.toString() == "异常") {
                        System.currentTimeMillis().timestampToCompleteDate()
                    } else {
                        "--:--:--"
                    }
                } else {
                    faultAlarmView.text = "已离线"
                    faultAlarmTimeView.text = "--:--:--"

                    fireAlarmView.text = "已离线"
                    fireAlarmTimeView.text = "--:--:--"
                }
                dataLinkedList.add(dataMap)
            }
        }
        true
    }

    override fun initEvent() {

    }

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