package com.casic.br.fragment

import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.casic.br.R
import com.casic.br.adapter.AddedDeviceAdapter
import com.casic.br.adapter.OtherDeviceAdapter
import com.casic.br.adapter.RecommendAdapter
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.selectCategory
import com.casic.br.model.OtherDeviceListModel
import com.casic.br.model.RecommendModel
import com.casic.br.utils.DeserializeModel
import com.casic.br.view.AddDeviceActivity
import com.casic.br.view.AllDeviceActivity
import com.casic.br.view.device.*
import com.casic.br.vm.DeviceViewModel
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
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.api.IResultCallback
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 lateinit var otherDeviceAdapter: OtherDeviceAdapter
    private lateinit var deviceViewModel: DeviceViewModel
    private var dataBeans: MutableList<DeviceBean> = ArrayList()
    private var dataModes: MutableList<OtherDeviceListModel.DataModel.RowsModel> = 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)
        deviceViewModel = ViewModelProvider(this)[DeviceViewModel::class.java]
        deviceViewModel.listModel.observe(this, {
            if (it.code == 200) {
                val deviceBeans = it.data?.rows!!
                when {
                    isRefresh -> {
                        dataModes.clear()
                        dataModes = deviceBeans
                        isRefresh = false
                    }
                    else -> {
                        dataModes = deviceBeans
                    }
                }
                weakReferenceHandler.sendEmptyMessage(2022112301)
            }
        })

        //TODO 热门推荐
        val imageArray = arrayOf(
            "https://img.alicdn.com/imgextra/i1/810471546/O1CN01zwi8SS1NI76hAXxOh_!!810471546.jpg",
            "https://img.alicdn.com/imgextra/i1/810471546/O1CN01dBqH051NI76dqVg8e_!!810471546.jpg",
            "https://img.alicdn.com/imgextra/i4/810471546/O1CN01NJ4Xh81NI76ZuU7lh_!!810471546.jpg"
        )
        val recommendModels = ArrayList<RecommendModel>()
        for (i in 0..2) {
            val model = RecommendModel()
            model.imageLink = imageArray[i]

            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()
        isRefresh = true
        TuyaHomeSdk.newHomeInstance(DeserializeModel.getHomeId())
            .getHomeDetail(object : ITuyaHomeResultCallback {
                override fun onSuccess(bean: HomeBean) {
                    val deviceModels = bean.deviceList
                    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")
                }
            })
        deviceViewModel.obtainOtherDeviceListByPage()
    }

    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]
                        val selectedCategory = deviceModel.selectCategory()
                        Log.d(kTag, "设备类型: $selectedCategory")
                        when (selectedCategory) {
                            "rs" -> {
                                //热水器
                                requireContext().navigatePageTo<WaterHeaterActivity>(deviceModel.devId)
                            }
                            "yyj" -> {
                                //油烟机
                                requireContext().navigatePageTo<RangeHoodActivity>(deviceModel.devId)
                            }
                            "bgl" -> {
                                //壁挂炉
                                requireContext().navigatePageTo<FireplaceActivity>(deviceModel.devId)
                            }
                            "rq" -> {
                                //燃气灶
                                requireContext().navigatePageTo<CookerActivity>(deviceModel.devId)
                            }
                            "pc" -> {
                                //排插
                                requireContext().navigatePageTo<PowerStripActivity>(deviceModel.devId)
                            }
                            "cz" -> {
                                //插座
                                requireContext().navigatePageTo<SingleStripActivity>(deviceModel.devId)
                            }
                            "wg2" -> {
                                //网关
                                requireContext().navigatePageTo<SmartGatewayActivity>(
                                    deviceModel.devId
                                )
                            }
                            //TODO 人体传感器设备类型待确认
                            "0204" -> {
                                //人体传感器
                                requireContext().navigatePageTo<MotionSensorActivity>()
                            }
                            "wsdcg" -> {
                                //温湿度传感器
                                requireContext().navigatePageTo<TAndHSensorActivity>()
                            }
                            "ywbj" -> {
                                //火灾报警器
                                requireContext().navigatePageTo<FireSensorActivity>()
                            }
                            "rqbj" -> {
                                //燃气报警器
                                requireContext().navigatePageTo<GasSensorActivity>()
                            }
                            "cobj" -> {
                                //一氧化碳报警器
                                requireContext().navigatePageTo<CoSensorActivity>()
                            }
                            "yinsj" -> {
                                //即热式台式饮水机
                                requireContext().navigatePageTo<WaterDispenserActivity>(deviceModel.devId)
                            }
                            "kj" -> {
                                //空气净化器
                                requireContext().navigatePageTo<AirCleanerActivity>(deviceModel.devId)
                            }
                            "sd" -> {
                                //智能扫地机器人
                                requireContext().navigatePageTo<SweepingRobotActivity>(deviceModel.devId)
                            }
                        }
                    }

                    override fun onButtonClick(position: Int) {
                        moreOperate(position)
                    }
                })
            }
        } else if (it.what == 2022112301) {
            if (isRefresh) {
                otherDeviceAdapter.notifyDataSetChanged()
            } else {
                otherDeviceAdapter = OtherDeviceAdapter(requireContext(), dataModes)
                otherDeviceRecyclerView.adapter = otherDeviceAdapter
                otherDeviceAdapter.setOnItemClickListener(object :
                    OtherDeviceAdapter.OnItemClickListener {
                    override fun onItemClick(position: Int) {
                        requireContext().navigatePageTo<HWGasAlarmActivity>(dataModes[position].id)
                    }
                })
            }
        }
        true
    }

    private fun moreOperate(clickPosition: Int) {
        BottomActionSheet.Builder()
            .setContext(requireContext())
            .setActionItemTitle(arrayListOf("删除设备"))
            .setItemTextColor(Color.BLUE)
            .setOnActionSheetListener(object :
                BottomActionSheet.OnActionSheetListener {
                override fun onActionItemClick(position: Int) {
                    when (position) {
                        0 -> TuyaHomeSdk.newDeviceInstance(dataBeans[clickPosition].devId)
                            .removeDevice(object : IResultCallback {
                                override fun onError(code: String?, error: String?) {
                                    Log.d(kTag, "onError: $error")
                                }

                                override fun onSuccess() {
                                    dataBeans.removeAt(clickPosition)
                                    addedDeviceAdapter.notifyItemRemoved(clickPosition)
                                    addedDeviceAdapter.notifyItemRangeChanged(
                                        clickPosition, dataBeans.size - clickPosition
                                    )
                                }
                            })
                    }
                }
            }).build().show()
    }
}