package com.casic.br.fragment.rangehood

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_rangehood_status.*
import java.util.*

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

    companion object {
        lateinit var weakReference: WeakReferenceHandler
    }

    private val kTag = "StatusPageFragment"
    private var isDeviceWorking = false
    private var isDelayed = false
    private val wifi by lazy { requireContext().applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager }
    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_rangehood_status

    override fun setupTopBarLayout() {

    }

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

    override fun onResume() {
        super.onResume()
        //每次获取焦点都查询设备的开关机状态
        deviceStateView.text = if (!isDeviceWorking) {
            "已关机"
        } else {
            "工作中"
        }
        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() {
                val obj = org.json.JSONObject()
                obj.put("cookerHoodInfo", paramObject)
                deviceViewModel.addDeviceData(obj)
            }
        }, 0, 5000)
    }

    private val callback = Handler.Callback { message ->
        when (message.what) {
            2022092302 -> {
                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"
                            }
                            paramObject.put("switchStatus", switchStatus)
                        }
                        "2" -> {
                            isDelayed = parseObject[it] as Boolean
                        }
                        "11" -> {//设备状态，[off, low, high, strong, air, fangdaoguan, wash, delay, xunhang]
                            deviceStateView.text = when (parseObject[it] as String) {
                                "low" -> "低档"
                                "high" -> "高档"
                                "strong" -> "爆炒"
                                "air" -> "假日通风"
                                "fangdaoguan" -> "防倒灌"
                                "wash" -> "清洁"
                                "delay" -> "延迟关机"
                                "xunhang" -> "巡航"
                                else -> "OFF"
                            }
                            paramObject.put("workStatus", deviceStateView.text)
                        }
                        "12" -> {//累计工作时间
                            workingTimeView.text = if (isDeviceWorking) {
                                "${parseObject[it]}分"
                            } else {
                                "0分"
                            }
                            paramObject.put("runTime", workingTimeView.text)
                        }
                        "105" -> {
                            if (isDeviceWorking) {
                                delayTimeView.text = if (isDelayed) {
                                    String.format("${parseObject[it].toString()}s")
                                } else {
                                    "0s"
                                }
                            } else {
                                delayTimeView.text = "未开启"
                            }
                        }
                        "106" -> {//烟灶联动
                            if (parseObject[it] as Boolean) {
                                linkageView.text = "开"
                                paramObject.put("smokeStove", "1")
                            } else {
                                linkageView.text = "关"
                                paramObject.put("smokeStove", "0")
                            }
                        }
                        "107" -> {//倒油提醒
                            if (parseObject[it] as Boolean) {
                                pourOilView.text = "开"
                                paramObject.put("oilPouringReminder", "1")
                            } else {
                                pourOilView.text = "关"
                                paramObject.put("oilPouringReminder", "0")
                            }
                        }
                    }
                }
            }
            2022092303 -> {
                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 onDestroy() {
        super.onDestroy()
        deviceInstance.unRegisterDevListener()
        deviceInstance.onDestroy()
        dataTimer.cancel()
    }
}