package com.casic.br.fragment.waterheater

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Handler
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.diffDate
import com.casic.br.utils.CommandManager
import com.casic.br.vm.DeviceViewModel
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.tuya.smart.sdk.api.ITuyaDevice
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.fragment_device_waterheater_status.*
import java.util.*

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
    private val paramObject by lazy { org.json.JSONObject() }//数据Json对象
    private val dataTimer by lazy { Timer() }//数据上传Timer
    private lateinit var deviceViewModel: DeviceViewModel

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

    override fun setupTopBarLayout() {

    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)
        deviceViewModel = ViewModelProvider(this)[DeviceViewModel::class.java]
    }

    private val callback = Handler.Callback { message ->
        when (message.what) {
            2022092602 -> {
                val parseObject = JSONObject.parseObject(message.obj as String)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {//开关机
                            isDeviceWorking = parseObject[it] as Boolean
                            val switchStatus = if (isDeviceWorking) {
                                "1"
                            } else {
                                "0"
                            }
                            deviceStatusSwitch.isChecked = isDeviceWorking
                            deviceStateView.text = if (isDeviceWorking) {
                                "已开机"
                            } else {
                                "已关机"
                            }
                            paramObject.put("workStatus", switchStatus)
                            paramObject.put("switchStatus", switchStatus)
                        }
                        "2" -> {//模式，[shushiyu, suiwengan, chufang]
                            workModeView.text = when (parseObject[it] as String) {
                                "shushiyu" -> "舒适浴"
                                "suiwengan" -> "随温感"
                                else -> "厨房"
                            }
                            paramObject.put("workMode", workModeView.text)
                        }
                        "10" -> {
                            currentTempView.text = String.format(
                                "${parseObject[it]}${
                                    requireContext().resources.getString(R.string.temperature_unit)
                                }"
                            )
                            paramObject.put("currentTemperature", currentTempView.text)
                        }
                        "13" -> {
                            deviceStateView.text = when (parseObject[it] as String) {
                                "guanji" -> "已关机"
                                "gongzuozhong" -> "工作中"
                                "guzhang" -> "故障"
                                else -> "已开机"
                            }
                        }
                        "105" ->
                            paramObject.put(
                                "recentWaterConsumption",
                                String.format("${parseObject[it] as Int}L")
                            )
                        "106" ->
                            paramObject.put(
                                "totalWaterConsumption",
                                String.format("${parseObject[it] as Int}t")
                            )
                        "103" ->
                            paramObject.put(
                                "recentGasConsumption",
                                String.format(
                                    "${parseObject[it] as Int}${
                                        resources.getString(R.string.volume_unit)
                                    }"
                                )
                            )
                        "104" ->
                            paramObject.put(
                                "totalGasConsumption",
                                String.format(
                                    "${parseObject[it] as Int}${
                                        resources.getString(R.string.volume_unit)
                                    }"
                                )
                            )
                    }
                }
            }
            2022092603 -> {
                val deviceBean = message.obj as DeviceBean
                deviceUsedTimeView.text = String.format("${deviceBean.time.toString().diffDate(false)}天")
                ipAddressView.text = deviceBean.ip

                paramObject.put("usageTime", deviceUsedTimeView.text)
                paramObject.put("deviceId", deviceBean.devId)
            }
        }
        true
    }

    override fun onResume() {
        super.onResume()
        wifiStatusSwitch.isChecked = !wifi.connectionInfo.ssid.contains("unknown ssid")
        if (wifiStatusSwitch.isChecked) {
            wifiLayout.visibility = View.VISIBLE
            wifiNameView.text = wifi.connectionInfo.ssid.replace("\"", "")

            paramObject.put("wifiStatus", "ON")
            paramObject.put("wifiName", wifiNameView.text)
        } else {
            wifiLayout.visibility = View.GONE
            paramObject.put("wifiStatus", "OFF")
        }
    }

    override fun observeRequestState() {

    }

    override fun initEvent() {
        //每隔5s传一次数据到服务器
        dataTimer.schedule(object : TimerTask() {
            override fun run() {
                CommandManager.getTuyaDp(deviceInstance, "105")
                CommandManager.getTuyaDp(deviceInstance, "106")
                CommandManager.getTuyaDp(deviceInstance, "103")
                CommandManager.getTuyaDp(deviceInstance, "104")

                val obj = org.json.JSONObject()
                obj.put("heaterInfo", paramObject)
                deviceViewModel.addDeviceData(obj)
            }
        }, 0, 5000)
    }

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