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.*
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.activity_fire_senser.*
import kotlinx.android.synthetic.main.activity_fire_senser.batteryValueView
import kotlinx.android.synthetic.main.activity_fire_senser.batteryView
import kotlinx.android.synthetic.main.activity_fire_senser.deviceLogoView
import kotlinx.android.synthetic.main.activity_fire_senser.deviceStateView
import kotlinx.android.synthetic.main.activity_fire_senser.faultAlarmTimeView
import kotlinx.android.synthetic.main.activity_fire_senser.faultAlarmView
import kotlinx.android.synthetic.main.activity_fire_senser.rootView
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

/**
 * 火灾报警器
 * TODO 数据上报暂缓
 * */
class FireSensorActivity : 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_fire_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 == "ywbj") {
                                    //火灾报警器
                                    val msg = weakReference.obtainMessage()
                                    msg.what = 2022102002
                                    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 == 2022102002) {
            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","15":100,"4":false}
                     *
                     * {"11":{"name":"故障告警"},"1":{"name":"烟雾检测状态"},"4":{"name":"防拆报警"},"15":{"name":"电池电量"}}
                     * */

                    val b = it.dps["15"].toString()
                    batteryView.setBackgroundResource(b.toBatteryImage())
                    batteryValueView.text = "${b}%"

                    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 {
                        "--:--:--"
                    }

                    val t = it.dps["4"] as Boolean
                    tamperAlarmView.text = if (!t) {
                        "正常"
                    } else {
                        "异常"
                    }
                    tamperAlarmTimeView.text = if (tamperAlarmView.text.toString() == "异常") {
                        System.currentTimeMillis().timestampToCompleteDate()
                    } else {
                        "--:--:--"
                    }
                } else {
                    batteryView.setBackgroundResource("0".toBatteryImage())
                    batteryValueView.text = "0%"

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

                    fireAlarmView.text = "已离线"
                    fireAlarmTimeView.text = "--:--:--"

                    tamperAlarmView.text = "已离线"
                    tamperAlarmTimeView.text = "--:--:--"
                }
//            dataMap["temperature"] = temperatureView.text.toString().replace("°C", "")
                dataLinkedList.add(dataMap)
            }
        }
        true
    }

    override fun initEvent() {
        createSceneLayout.setOnClickListener {
            "后续功能待完善".show(this)
        }
    }

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