package com.casic.br.view.device

import android.content.Context
import android.graphics.Color
import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.extensions.*
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.convertColor
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_air_cleaner.*
import kotlinx.android.synthetic.main.include_device_title.*

/**
 * 空气净化器
 * TODO 数据上报暂缓
 * */
class AirCleanerActivity : KotlinBaseActivity() {

    private val context: Context = this@AirCleanerActivity
    private lateinit var tuyaOTA: ITuyaOta
    private lateinit var deviceInstance: ITuyaDevice

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

    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()
        Glide.with(this)
            .load(deviceBean.iconUrl)
            .apply(RequestOptions.circleCropTransform())
            .placeholder(R.mipmap.load_image_error)
            .into(deviceLogoView)

        deviceInstance.registerDevListener(object : TuyaDeviceListener() {
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d("Casic", "AirCleanerActivity => onDpUpdate: $dpStr")
                //{"1":true,"11":false,"19":"cancle","2":6,"20":0,"22":"1","3":"1","4":"1","5":99,"6":true,"7":false}
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {
                            //设备开关
                            turnOffRadioButton.isChecked = parseObject[it] as Boolean
                        }
                        "2" -> {
                            //pm2.5
                            particulateView.text = parseObject[it].toString()
                        }
                        "3" -> {
                            //模式
                            when (parseObject[it]) {
                                "0" -> manualRadioButton.isChecked = true
                                "1" -> autoRadioButton.isChecked = true
                                "2" -> sleepRadioButton.isChecked = true
                                "3" -> potentRadioButton.isChecked = true
                            }
                        }
                        "4" -> {
                            //风速
                            when (parseObject[it]) {
                                "1" -> lowSpeedRadioButton.isChecked = true
                                "2" -> mediumSpeedRadioButton.isChecked = true
                                "3" -> highSpeedRadioButton.isChecked = true
                            }
                        }
                        "5" -> {
                            //滤芯剩余量
                            filterElementView.text = "${parseObject[it]}%"
                        }
                        "6" -> {
                            //负离子
                            anionStatusSwitch.isChecked = parseObject[it] as Boolean
                        }
                        "7" -> {
                            //童锁
                            val c = parseObject[it] as Boolean
                            childStatusSwitch.isChecked = c
                            if (c) {
                                turnOffRadioButton.disableView()
                                modeRadioGroup.disableView(
                                    manualRadioButton,
                                    autoRadioButton,
                                    sleepRadioButton,
                                    potentRadioButton
                                )
                                speedRadioGroup.disableView(
                                    lowSpeedRadioButton,
                                    mediumSpeedRadioButton,
                                    highSpeedRadioButton
                                )
                                anionLayout.disableView(anionStatusSwitch)
                                countDownLayout.disableView()
                                resetFilterLayout.disableView()
                            } else {
                                turnOffRadioButton.enableView()
                                modeRadioGroup.enableView(
                                    manualRadioButton,
                                    autoRadioButton,
                                    sleepRadioButton,
                                    potentRadioButton
                                )
                                speedRadioGroup.enableView(
                                    lowSpeedRadioButton,
                                    mediumSpeedRadioButton,
                                    highSpeedRadioButton
                                )
                                anionLayout.enableView(anionStatusSwitch)
                                countDownLayout.enableView()
                                resetFilterLayout.enableView()
                            }
                        }
                        "11" -> {
                            //滤芯复位
                        }
                        "19" -> {
                            //倒计时
                        }
                        "20" -> {
                            //倒计时剩余
                        }
                        "22" -> {
                            //空气质量
                            when (parseObject[it]) {
                                "1" -> {
                                    airQualityView.text = "优"
                                    airQualityView.setTextColor(
                                        R.color.greenColor.convertColor(
                                            context
                                        )
                                    )
                                }
                                "2" -> {
                                    airQualityView.text = "良"
                                    airQualityView.setTextColor(
                                        R.color.mainThemeColor.convertColor(
                                            context
                                        )
                                    )
                                }
                                else -> {
                                    airQualityView.text = "差"
                                    airQualityView.setTextColor(
                                        R.color.redTextColor.convertColor(
                                            context
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
        })
    }

    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("Casic", "AirCleanerActivity => onError: $error")
                                }

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

        turnOffRadioButton.setOnClickListener {
            if (turnOffRadioButton.isChecked) {
                CommandManager.sendTuyaDp(deviceInstance, "1".createCommand(true))
            } else {
                CommandManager.sendTuyaDp(deviceInstance, "1".createCommand(false))
            }
        }

        modeRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.manualRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "3".createCommand("0"))
                }
                R.id.autoRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "3".createCommand("1"))
                }
                R.id.sleepRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "3".createCommand("2"))
                }
                R.id.potentRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "3".createCommand("3"))
                }
            }
        }

        speedRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.lowSpeedRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "4".createCommand("1"))
                }
                R.id.mediumSpeedRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "4".createCommand("2"))
                }
                R.id.highSpeedRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "4".createCommand("3"))
                }
            }
        }

        anionStatusSwitch.setOnClickListener {
            if (anionStatusSwitch.isChecked) {
                CommandManager.sendTuyaDp(deviceInstance, "6".createCommand(true))
            } else {
                CommandManager.sendTuyaDp(deviceInstance, "6".createCommand(false))
            }
        }

        childStatusSwitch.setOnClickListener {
            if (childStatusSwitch.isChecked) {
                CommandManager.sendTuyaDp(deviceInstance, "7".createCommand(true))
            } else {
                CommandManager.sendTuyaDp(deviceInstance, "7".createCommand(false))
            }
        }

        countDownLayout.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(arrayListOf("不设置定时", "1h", "2h", "4h", "8h"))
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        //cancle,1,2,3,4
                        val value = when (position) {
                            0 -> "cancle"
                            1 -> "1"
                            2 -> "2"
                            3 -> "3"
                            4 -> "4"
                            else -> "cancle"
                        }
                        CommandManager.sendTuyaDp(deviceInstance, "19".createCommand(value))
                    }
                })
                .build().show()
        }

        resetFilterLayout.setOnClickListener {
            AlertControlDialog.Builder()
                .setContext(this)
                .setTitle("滤芯复位")
                .setMessage("确定要复位滤芯么？")
                .setNegativeButton("取消")
                .setPositiveButton("确定")
                .setOnDialogButtonClickListener(object :
                    AlertControlDialog.OnDialogButtonClickListener {
                    override fun onCancelClick() {

                    }

                    override fun onConfirmClick() {
                        CommandManager.sendTuyaDp(deviceInstance, "11".createCommand(true))
                    }
                })
                .build().show()
        }
    }

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

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