package com.casic.br.view.device

import android.graphics.Typeface
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.casic.br.R
import com.casic.br.adapter.TabPagerAdapter
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.fragment.rangehood.ControlPageFragment
import com.casic.br.fragment.rangehood.ServicePageFragment
import com.casic.br.fragment.rangehood.StatusPageFragment
import com.casic.br.utils.CommandManager
import com.casic.br.utils.LocaleConstant
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.Constant
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.IDevListener
import com.tuya.smart.sdk.api.ITuyaDevice
import kotlinx.android.synthetic.main.activity_range_hood.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

/**
 * 油烟机
 * */
class RangeHoodActivity : KotlinBaseActivity() {

    private val kTag = "RangeHoodActivity"
    private val inflater by lazy { LayoutInflater.from(this) }
    private var fragmentPages: ArrayList<Fragment> = ArrayList()
    private lateinit var deviceInstance: ITuyaDevice
    private var isWorking = false
    private var isDelayed = false

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

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        initLayoutImmersionBar(rootView)
        ImmersionBar.with(this).statusBarDarkFont(true).init()

        leftBackView.setOnClickListener { finish() }
    }

    override fun initData() {
        val deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        //控制设备前必须初始家庭化数据，每次 App 活跃期间，初始化一次即可。
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)

        val deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(deviceId)
        if (deviceBean == null) {
            "查询设备信息失败，请检查设备是否已离线".show(this)
            return
        }
        titleView.text = "万家乐油烟机"
        Glide.with(this)
            .load(deviceBean.iconUrl)
            .placeholder(R.mipmap.load_image_error)
            .into(deviceLogoView)

        fragmentPages.add(ControlPageFragment(deviceInstance))
        fragmentPages.add(StatusPageFragment(deviceInstance))
        fragmentPages.add(ServicePageFragment())

        deviceInstance.registerDevListener(object : IDevListener {

            /**
             * DP 数据更新
             *
             * @param devId 设备 ID
             * @param dpStr 设备发生变动的功能点，为 JSON 字符串，数据格式：{"101": true}
             */
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d(kTag, "onDpUpdate: $dpStr")
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {
                            isWorking = parseObject[it] as Boolean
                        }
                        "2" -> {
                            isDelayed = parseObject[it] as Boolean
                        }
                        "105" -> {
                            if (isWorking) {
                                delayTimeView.text = if (isDelayed) {
                                    String.format("${parseObject[it].toString()}s")
                                } else {
                                    "0s"
                                }
                            } else {
                                delayTimeView.text = "未开启"
                            }
                        }
                    }
                }

                val controlMsg = ControlPageFragment.weakReference.obtainMessage()
                controlMsg.what = 2022092301
                controlMsg.obj = dpStr
                ControlPageFragment.weakReference.sendMessage(controlMsg)

                val statusMsg = StatusPageFragment.weakReference.obtainMessage()
                statusMsg.what = 2022092302
                statusMsg.obj = dpStr
                StatusPageFragment.weakReference.sendMessage(statusMsg)
            }

            /**
             * 设备移除回调
             *
             * @param devId 设备id
             */
            override fun onRemoved(devId: String?) {

            }

            /**
             * 设备上下线回调。如果设备断电或断网，服务端将会在3分钟后回调到此方法。
             *
             * @param devId  设备 ID
             * @param online 是否在线，在线为 true
             */
            override fun onStatusChanged(devId: String?, online: Boolean) {

            }

            /**
             * 网络状态发生变动时的回调
             *
             * @param devId  设备 ID
             *  @param status 网络状态是否可用，可用为 true
             */
            override fun onNetworkStatusChanged(devId: String?, status: Boolean) {

            }

            /**
             * 设备信息更新回调
             *
             * @param devId  设备 ID
             */
            override fun onDevInfoUpdate(devId: String?) {

            }
        })
    }

    override fun onResume() {
        super.onResume()
        //每次获取焦点都查询设备的开关机状态
        CommandManager.getTuyaDp(deviceInstance, "1")
    }

    override fun initEvent() {
        rightOperateView.setOnClickListener {

        }

        deviceViewPager.adapter =
            TabPagerAdapter(fragmentPages, LocaleConstant.DEVICE_PAGE_TITLE, supportFragmentManager)
        deviceTabLayout.setupWithViewPager(deviceViewPager)
        deviceTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val textView = inflater.inflate(R.layout.item_top_tab, null) as TextView
                textView.textSize = 16f
                textView.typeface = Typeface.DEFAULT_BOLD
                textView.text = tab!!.text
                tab.customView = textView
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.customView = null
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })
    }

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