package com.casic.br.view.device

import android.graphics.Color
import android.os.Handler
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.adapter.AddedDeviceAdapter
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.selectCategory
import com.casic.br.extensions.toChineseTypeName
import com.casic.br.view.ScanZigbeeActivity
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.pengxh.kt.lite.widget.dialog.AlertControlDialog
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
import com.tuya.smart.android.device.bean.UpgradeInfoBean
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.*
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.activity_gateway.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

/**
 * 智能网关
 * TODO 数据上报暂缓
 * */
class SmartGatewayActivity : KotlinBaseActivity() {

    private val kTag = "SmartGatewayActivity"
    private val context = this@SmartGatewayActivity
    private var dataBeans: MutableList<DeviceBean> = ArrayList()
    private var isRefresh = false
    private lateinit var deviceId: String
    private lateinit var weakReferenceHandler: WeakReferenceHandler
    private lateinit var deviceAdapter: AddedDeviceAdapter
    private lateinit var tuyaOTA: ITuyaOta
    private lateinit var deviceInstance: ITuyaDevice //网关本身
    private lateinit var deviceSubInstance: ITuyaGateway //网关下属设备

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

    override fun observeRequestState() {

    }

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

        leftBackView.setOnClickListener { finish() }
    }

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

        weakReferenceHandler = WeakReferenceHandler(callback)

        val deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(deviceId)
        if (deviceBean == null) {
            "查询设备信息失败，请检查设备是否已离线".show(this)
            return
        }
        deviceStateView.text = if (deviceBean.isOnline) {
            "设备在线"
        } else {
            "设备已离线"
        }
        titleView.text = deviceBean.toChineseTypeName()
        Glide.with(this)
            .load(deviceBean.iconUrl)
            .apply(RequestOptions.circleCropTransform())
            .placeholder(R.mipmap.load_image_error)
            .into(deviceLogoView)
    }

    override fun onResume() {
        super.onResume()
        deviceSubInstance.getSubDevList(object : ITuyaDataCallback<MutableList<DeviceBean>> {
            override fun onSuccess(result: MutableList<DeviceBean>) {
                when {
                    isRefresh -> {
                        dataBeans.clear()
                        dataBeans = result
                        isRefresh = false
                    }
                    else -> {
                        dataBeans = result
                    }
                }
                weakReferenceHandler.sendEmptyMessage(2022101901)
            }

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

    private val callback = Handler.Callback {
        if (it.what == 2022101901) {
            if (isRefresh) {
                deviceAdapter.notifyDataSetChanged()
            } else {
                deviceAdapter = AddedDeviceAdapter(this, dataBeans)
                deviceRecyclerView.adapter = deviceAdapter
                deviceAdapter.setOnItemClickListener(object :
                    AddedDeviceAdapter.OnItemClickListener {
                    override fun onAddDeviceClick() {
                        navigatePageTo<ScanZigbeeActivity>(deviceId)
                    }

                    override fun onItemClick(position: Int) {
                        // 需要根据设备类型显示不同的页面
                        val deviceModel = dataBeans[position]
                        val selectedCategory = deviceModel.selectCategory()
                        Log.d(kTag, "设备类型: $selectedCategory")
                        when {
                            selectedCategory.contains("0204") -> {
                                //人体传感器
                                navigatePageTo<MotionSensorActivity>()
                            }
//                            selectedCategory.contains("yyj") -> {
//                                //油烟机
//                                navigatePageTo<RangeHoodActivity>(deviceModel.devId)
//                            }
//                            selectedCategory.contains("bgl") -> {
//                                //壁挂炉
//                                navigatePageTo<FireplaceActivity>(deviceModel.devId)
//                            }
//                            selectedCategory.contains("rqz") -> {
//                                //燃气灶
//                                navigatePageTo<CookerActivity>(deviceModel.devId)
//                            }
//                            selectedCategory.contains("pc") -> {
//                                //排插
//                                navigatePageTo<PowerStripActivity>(deviceModel.devId)
//                            }
//                            selectedCategory.contains("cz") -> {
//                                //插座
//                                navigatePageTo<SingleStripActivity>(deviceModel.devId)
//                            }
//                            selectedCategory.contains("wg2") -> {
//                                //网关
//                                navigatePageTo<SmartGatewayActivity>(deviceModel.devId)
//                            }
                        }
                    }

                    override fun onButtonClick(position: Int) {
                        moreOperate(position)
                    }
                })
            }
        }
        true
    }

    private fun moreOperate(clickPosition: Int) {
        BottomActionSheet.Builder()
            .setContext(this)
            .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)
                                    deviceAdapter.notifyItemRemoved(clickPosition)
                                    deviceAdapter.notifyItemRangeChanged(
                                        clickPosition, dataBeans.size - clickPosition
                                    )
                                }
                            })
                    }
                }
            }).build().show()
    }

    override fun initEvent() {
        rightOperateView.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(arrayListOf("固件升级", "移除设备"))
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        when (position) {
                            0 -> {
                                tuyaOTA.getOtaInfo(object : IGetOtaInfoCallback {
                                    override fun onSuccess(upgradeInfoBeans: MutableList<UpgradeInfoBean>?) {
                                        if (upgradeInfoBeans.isNullOrEmpty()) {
                                            "无新版本可用".show(context)
                                        }
                                        val mainModel = upgradeInfoBeans!![0]
                                        when (mainModel.upgradeStatus) {
                                            1 -> updateVersion()
                                            2 -> {

                                            }
                                            else -> "主联网模组无新版本可用".show(context)
                                        }

                                        val mcuModel = upgradeInfoBeans[1]
                                        when (mcuModel.upgradeStatus) {
                                            1 -> updateVersion()
                                            2 -> {

                                            }
                                            else -> "MCU模块无新版本可用".show(context)
                                        }
                                    }

                                    override fun onFailure(code: String?, error: String?) {

                                    }
                                })
                            }
                            1 -> deviceInstance.removeDevice(object : IResultCallback {
                                override fun onError(code: String?, error: String?) {
                                    Log.d(kTag, "onError: $error")
                                }

                                override fun onSuccess() {
                                    finish()
                                }
                            })
                        }
                    }
                })
                .build().show()
        }
    }

    private fun updateVersion() {
        AlertControlDialog.Builder()
            .setContext(this)
            .setTitle("版本升级")
            .setMessage("有新版本可以升级，是否升级？")
            .setNegativeButton("取消")
            .setPositiveButton("确定")
            .setOnDialogButtonClickListener(object :
                AlertControlDialog.OnDialogButtonClickListener {
                override fun onCancelClick() {
                    tuyaOTA.startOta()
                }

                override fun onConfirmClick() {

                }
            })
            .build().show()
    }

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

        deviceSubInstance.unRegisterSubDevListener()
        deviceSubInstance.onDestroy()
    }
}