package com.casic.br.fragment.fireplace

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.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_fireplace_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_fireplace_status

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {

    }

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

    private val callback = Handler.Callback { message ->
        when (message.what) {
            2022092802 -> {
                val parseObject = JSONObject.parseObject(message.obj as String)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {//开关机
                            isDeviceWorking = parseObject[it] as Boolean
                            val workStatus = if (isDeviceWorking) {
                                "1"
                            } else {
                                "0"
                            }
                            paramObject.put("workStatus", workStatus)
                        }
                        "4" -> {
                            showerTempView.text = String.format(
                                "${parseObject[it]}${
                                    requireContext().resources.getString(R.string.temperature_unit)
                                }"
                            )
                            paramObject.put("bathroomTemp", showerTempView.text)
                        }
                        "6" -> {
                            heaterTempView.text = String.format(
                                "${parseObject[it]}${
                                    requireContext().resources.getString(R.string.temperature_unit)
                                }"
                            )
                            paramObject.put("heatingTemp", heaterTempView.text)
                        }
                        "10" -> {
                            if (parseObject[it] as Boolean) {
                                heaterStateView.text = "已开启"
                                paramObject.put("heatingStatus", "1")
                            } else {
                                heaterStateView.text = "已关闭"
                                paramObject.put("heatingStatus", "0")
                            }
                        }
                        "11" -> {
                            if (parseObject[it] as Boolean) {
                                showerStateView.text = "已开启"
                                paramObject.put("bathroomStatus", "1")
                            } else {
                                showerStateView.text = "已关闭"
                                paramObject.put("bathroomStatus", "0")
                            }
                        }
                        "103" -> {
                            if (parseObject[it] as Boolean) {
                                antifreezeStateView.text = "已开启"
                                paramObject.put("antifreezeStatus", "1")
                            } else {
                                antifreezeStateView.text = "已关闭"
                                paramObject.put("antifreezeStatus", "0")
                            }
                        }
                        "102" -> {
                            if (parseObject[it] as Boolean) {
                                ventilatorStateView.text = "已开启"
                                paramObject.put("fanStatus", "1")
                            } else {
                                ventilatorStateView.text = "已关闭"
                                paramObject.put("fanStatus", "0")
                            }
                        }
                        "101" -> {
                            if (parseObject[it] as Boolean) {
                                pumpStateView.text = "已开启"
                                paramObject.put("fanStatus", "1")
                            } else {
                                pumpStateView.text = "已关闭"
                                paramObject.put("fanStatus", "0")
                            }
                        }
                    }
                }
            }
            2022092803 -> {
                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 initEvent() {
        //每隔5s传一次数据到服务器
        dataTimer.schedule(object : TimerTask() {
            override fun run() {
                val obj = org.json.JSONObject()
                obj.put("hangingFurnaceInfo", paramObject)
                deviceViewModel.addDeviceData(obj)
            }
        }, 0, 5000)
    }

    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")
        }
        deviceStateView.text = if (!isDeviceWorking) {
            "已关机"
        } else {
            "工作中"
        }
    }

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