package com.casic.br.view.device

import android.os.Handler
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.casic.br.R
import com.casic.br.adapter.TabPagerAdapter
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.selectCategory
import com.casic.br.extensions.toBatteryImage
import com.casic.br.fragment.th.HumidityPageFragment
import com.casic.br.fragment.th.TemperaturePageFragment
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.LocaleConstant
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
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_t_h_senser.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*
import kotlin.collections.HashMap

/**
 * 温湿度传感器
 * TODO 数据上报暂缓
 * */
class TAndHSensorActivity : KotlinBaseActivity() {

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

    override fun initLayoutView(): Int = R.layout.activity_t_h_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 == "wsdcg") {
                                    //温湿度传感器
                                    val msg = weakReference.obtainMessage()
                                    msg.what = 2022112001
                                    msg.obj = it
                                    weakReference.sendMessage(msg)
                                }
                            }
                        }

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

        fragmentPages.add(TemperaturePageFragment())
        fragmentPages.add(HumidityPageFragment())
        viewPager.adapter =
            TabPagerAdapter(fragmentPages, LocaleConstant.T_H_PAGE_TITLE, supportFragmentManager)
        tabLayout.setupWithViewPager(viewPager)
    }

    private val callback = Handler.Callback { message ->
        if (message.what == 2022112001) {
            if (!this.isDestroyed) {
                val it = message.obj as DeviceBean
                deviceStateView.text = if (it.isOnline) {
                    "设备在线"
                } else {
                    "设备已离线"
                }
                titleView.text = String.format(it.name + "传感器")

                val dataMap = HashMap<String, Any>()
                if (it.isOnline) {
                    val h = it.dps["101"].toString()
                    //温湿度的值需要缩小100倍
                    humidityView.text = if (h.isBlank()) {
                        "0%"
                    } else {
                        "${h.toDouble() / 100}%"
                    }
                    dataMap["humidity"] = humidityView.text.toString().replace("%", "")

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

                    val t = it.dps["103"].toString()
                    //{"unit":"℃","min":-2000,"max":10000,"scale":2,"step":1,"type":"value"}
                    temperatureView.text = if (h.isBlank()) {
                        "0${resources.getString(R.string.temperature_unit)}"
                    } else {
                        "${t.toDouble() / 100}${resources.getString(R.string.temperature_unit)}"
                    }
                    dataMap["temperature"] = temperatureView.text.toString().replace("°C", "")
                } else {
                    batteryView.setBackgroundResource("0".toBatteryImage())
                    batteryValueView.text = "0%"

                    temperatureView.text = "已离线"

                    humidityView.text = "已离线"
                }

                dataLinkedList.add(dataMap)
            }
        }
        true
    }

    override fun initEvent() {

    }

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