package com.casic.br.view.device

import android.graphics.Color
import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.createCommand
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.toChineseTypeName
import com.casic.br.utils.CommandManager
import com.casic.br.utils.TuyaDeviceListener
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.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.IGetOtaInfoCallback
import com.tuya.smart.sdk.api.IResultCallback
import com.tuya.smart.sdk.api.ITuyaDevice
import com.tuya.smart.sdk.api.ITuyaOta
import kotlinx.android.synthetic.main.activity_power_strip.*
import kotlinx.android.synthetic.main.include_device_title.*

/**
 * 电源插排
 * TODO 数据上报暂缓
 * */
class PowerStripActivity : KotlinBaseActivity() {

    private val context = this@PowerStripActivity
    private val kTag = "PowerStripActivity"
    private lateinit var tuyaOTA: ITuyaOta
    private lateinit var deviceInstance: ITuyaDevice

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

    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)!!
        tuyaOTA = TuyaHomeSdk.newOTAInstance(deviceId)
        //控制设备前必须初始家庭化数据，每次 App 活跃期间，初始化一次即可。
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)

        val deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(deviceId)
        if (deviceBean == null) {
            "查询设备信息失败，请检查设备是否已离线".show(this)
            return
        }
        titleView.text = deviceBean.toChineseTypeName()
        deviceBean.dpName.entries.forEach {
            when (it.key) {
                "1" -> firstTurnOffCheckBox.text = it.value
                "2" -> secondTurnOffCheckBox.text = it.value
                "3" -> thirdTurnOffCheckBox.text = it.value
            }
        }
        deviceBean.dps.entries.forEach {
            when (it.key) {
                "1" -> firstTurnOffCheckBox.isChecked = it.value as Boolean
                "2" -> secondTurnOffCheckBox.isChecked = it.value as Boolean
                "3" -> thirdTurnOffCheckBox.isChecked = it.value as Boolean
            }
        }
        turnOffCheckBox.isChecked =
            firstTurnOffCheckBox.isChecked || secondTurnOffCheckBox.isChecked || thirdTurnOffCheckBox.isChecked

        firstTurnOffImageView.alpha = if (firstTurnOffCheckBox.isChecked) {
            1f
        } else {
            .5f
        }
        secondTurnOffImageView.alpha = if (secondTurnOffCheckBox.isChecked) {
            1f
        } else {
            .5f
        }
        thirdTurnOffImageView.alpha = if (thirdTurnOffCheckBox.isChecked) {
            1f
        } else {
            .5f
        }

        deviceInstance.registerDevListener(object : TuyaDeviceListener() {
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d(kTag, "onDpUpdate: $dpStr")
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {
                            firstTurnOffCheckBox.isChecked = parseObject[it] as Boolean
                            firstTurnOffImageView.alpha = if (firstTurnOffCheckBox.isChecked) {
                                1f
                            } else {
                                .5f
                            }
                        }
                        "2" -> {
                            secondTurnOffCheckBox.isChecked = parseObject[it] as Boolean
                            secondTurnOffImageView.alpha = if (secondTurnOffCheckBox.isChecked) {
                                1f
                            } else {
                                .5f
                            }
                        }
                        "3" -> {
                            thirdTurnOffCheckBox.isChecked = parseObject[it] as Boolean
                            thirdTurnOffImageView.alpha = if (thirdTurnOffCheckBox.isChecked) {
                                1f
                            } else {
                                .5f
                            }
                        }
                    }
                }
            }
        })
    }

    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()
        }

        turnOffCheckBox.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "1".createCommand(isChecked))
            CommandManager.sendTuyaDp(deviceInstance, "2".createCommand(isChecked))
            CommandManager.sendTuyaDp(deviceInstance, "3".createCommand(isChecked))
        }

        firstTurnOffCheckBox.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "1".createCommand(isChecked))
        }

        secondTurnOffCheckBox.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "2".createCommand(isChecked))
        }

        thirdTurnOffCheckBox.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "3".createCommand(isChecked))
        }
    }

    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()
    }
}