package com.casic.br.fragment

import android.graphics.Typeface
import android.os.Handler
import android.util.Log
import com.casic.br.R
import com.casic.br.adapter.AddedDeviceAdapter
import com.casic.br.adapter.RecommendAdapter
import com.casic.br.extensions.diffDate
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.model.AddedDeviceModel
import com.casic.br.model.RecommendModel
import com.casic.br.utils.LocaleConstant
import com.casic.br.view.AddDeviceActivity
import com.casic.br.view.AllDeviceActivity
import com.casic.br.view.device.CookerActivity
import com.casic.br.view.device.FireplaceActivity
import com.casic.br.view.device.RangeHoodActivity
import com.casic.br.view.device.WaterHeaterActivity
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.navigatePageTo
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.bean.DeviceBean
import kotlinx.android.synthetic.main.fragment_device.*
import kotlinx.android.synthetic.main.include_main_title.*
import java.util.*


class DevicePageFragment : KotlinBaseFragment() {

    private val kTag = "DevicePageFragment"
    private lateinit var weakReferenceHandler: WeakReferenceHandler
    private lateinit var addedDeviceAdapter: AddedDeviceAdapter
    private var dataBeans: MutableList<AddedDeviceModel> = ArrayList()
    private var isRefresh = false

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

    override fun setupTopBarLayout() {
        requireContext().initLayoutImmersionBar(rootView)
        leftTitleView.text = "设备"
        leftTitleView.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
    }

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

        //热门推荐
        //TODO 模拟数据 只显示前三个设备
        val recommendModels = ArrayList<RecommendModel>()
        for (i in 0..2) {
            val model = RecommendModel()
            model.imageLink = "https://img95.699pic.com/photo/40006/1412.jpg_wh860.jpg"

            recommendModels.add(model)
        }
        val recommendAdapter = RecommendAdapter(requireContext(), recommendModels)
        recommendRecyclerView.adapter = recommendAdapter
        recommendAdapter.setOnItemClickListener(object : RecommendAdapter.OnItemClickListener {

            override fun onItemClick(position: Int) {

            }
        })
    }

    override fun observeRequestState() {

    }

    override fun initEvent() {
        showAllDeviceButton.setOnClickListener {
            requireContext().navigatePageTo<AllDeviceActivity>()
        }
    }

    override fun onResume() {
        super.onResume()
        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
                    val deviceModels = ArrayList<AddedDeviceModel>()
                    deviceList.forEach {

                        val model = AddedDeviceModel()
                        model.deviceId = it.devId
                        when (it.deviceCategory) {
                            "yyj" -> model.deviceName = "万家乐油烟机"
                        }
                        model.isOnline = it.isOnline
                        model.deviceImage = it.iconUrl
                        model.deviceModel = it.name
                        model.deviceType = it.deviceCategory
                        model.deviceUsedTime = "已使用${it.time.toString().diffDate()}天"
                        deviceModels.add(model)
                    }

                    //TODO 测试
                    val model = AddedDeviceModel()
                    model.deviceId = ""
                    model.deviceName = "万家乐热水器"
                    model.isOnline = false
                    model.deviceImage = ""
                    model.deviceModel = ""
                    model.deviceType = ""
                    model.deviceUsedTime = "已使用0天"
                    deviceModels.add(model)

                    when {
                        isRefresh -> {
                            dataBeans.clear()
                            dataBeans = deviceModels
                            isRefresh = false
                        }
                        else -> {
                            dataBeans = deviceModels
                        }
                    }
                    weakReferenceHandler.sendEmptyMessage(2022091901)
                }

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

    private val callback = Handler.Callback {
        if (it.what == 2022091901) {
            if (isRefresh) {
                addedDeviceAdapter.notifyDataSetChanged()
            } else {
                addedDeviceAdapter = AddedDeviceAdapter(requireContext(), dataBeans)
                deviceRecyclerView.adapter = addedDeviceAdapter
                addedDeviceAdapter.setOnItemClickListener(object :
                    AddedDeviceAdapter.OnItemClickListener {
                    override fun onAddDeviceClick() {
                        requireContext().navigatePageTo<AddDeviceActivity>()
                    }

                    override fun onItemClick(position: Int) {
                        // 需要根据设备类型显示不同的页面
                        val deviceModel = dataBeans[position]
                        when {
                            deviceModel.deviceName.contains("热水器") -> {
                                requireContext().navigatePageTo<WaterHeaterActivity>(deviceModel.deviceName)
                            }
                            deviceModel.deviceName.contains("油烟机") -> {
                                requireContext().navigatePageTo<RangeHoodActivity>(deviceModel.deviceId)
                            }
                            deviceModel.deviceName.contains("壁挂炉") -> {
                                requireContext().navigatePageTo<FireplaceActivity>()
                            }
                            deviceModel.deviceName.contains("燃气灶") -> {
                                requireContext().navigatePageTo<CookerActivity>()
                            }
                        }
                    }

                    override fun onButtonClick(position: Int) {

                    }
                })
            }
        }
        true
    }
}