package com.casic.br.fragment.waterheater

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Handler
import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.diffDate
import com.casic.br.utils.LocaleConstant
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.SaveKeyValues
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.api.ITuyaDevice
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.fragment_device_rangehood_status.*
import kotlinx.android.synthetic.main.fragment_device_waterheater_status.*
import kotlinx.android.synthetic.main.fragment_device_waterheater_status.deviceUsedTimeView

class StatusPageFragment(private val deviceInstance: ITuyaDevice) : KotlinBaseFragment() {

    companion object {
        lateinit var weakReference: WeakReferenceHandler
    }

    private val kTag = "StatusPageFragment"
    private val wifi by lazy { requireContext().applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager }
    private var isDeviceWorking = false

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

    override fun setupTopBarLayout() {

    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)

        val homeId = SaveKeyValues.getValue(LocaleConstant.HOME_ID, "") as String
        if (homeId == "") {
            return
        }
        TuyaHomeSdk.newHomeInstance(homeId.toLong())
            .getHomeDetail(object : ITuyaHomeResultCallback {
                override fun onSuccess(bean: HomeBean) {
                    val deviceList: List<DeviceBean> = bean.deviceList
                    deviceList.forEach {
                        if (it.deviceCategory == "rs") {
                            deviceUsedTimeView.text =
                                String.format("${it.time.toString().diffDate()}天")
                        }
                        return@forEach
                    }
                }

                override fun onError(errorCode: String, errorMsg: String) {
                    Log.d(kTag, "onError: $errorMsg")
                }
            })
    }

    private val callback = Handler.Callback { message ->
        if (message.what == 2022092602) {
            val parseObject = JSONObject.parseObject(message.obj as String)
            parseObject.keys.forEach {
                when (it) {
                    "1" -> {//开关机
                        isDeviceWorking = parseObject[it] as Boolean
                    }
                    "2" -> {//模式，[shushiyu, suiwengan, chufang]
                        workModeView.text = when (parseObject[it] as String) {
                            "shushiyu" -> "舒适浴"
                            "suiwengan" -> "随温感"
                            else -> "厨房"
                        }
                    }
                    "10" -> {
                        currentTempView.text = String.format(
                            "${parseObject[it]}${
                                requireContext().resources.getString(R.string.temperature_unit)
                            }"
                        )
                    }
                }
            }
        }
        true
    }

    override fun onResume() {
        super.onResume()
        wifiStatusSwitch.isChecked = !wifi.connectionInfo.ssid.contains("unknown ssid")
        deviceStatusSwitch.isChecked = isDeviceWorking
    }

    override fun observeRequestState() {

    }

    override fun initEvent() {
        wifiStatusSwitch.setOnClickListener {
            "状态显示页仅显示设备状态，不可控制设备".show(requireContext())
        }

        deviceStatusSwitch.setOnClickListener {
            "状态显示页仅显示设备状态，不可控制设备".show(requireContext())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceInstance.unRegisterDevListener()
        deviceInstance.onDestroy()
    }
}