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.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.casic.br.view.device.robot.RobotSettingsActivity
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.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_sweeping_robot.*
import kotlinx.android.synthetic.main.include_device_title.*

/**
 * 智能扫地机器人
 * TODO 数据上报暂缓
 * */
class SweepingRobotActivity : KotlinBaseActivity() {

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

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

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

        deviceInstance.registerDevListener(object : TuyaDeviceListener() {
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d("Casic", "SweepingRobotActivity => onDpUpdate: $dpStr")
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {//设备开关，不是工作开关

                        }
                        "11" -> {
                            //故障
                        }
                        "14" -> {
                            //剩余电量
                            batteryValueView.text = "${parseObject[it]}%"
                        }
                        "25" -> {
                            //Power on button，工作开关
                            turnOffRadioButton.isChecked = parseObject[it] as Boolean
                        }
                        "26" -> {
                            //清扫方向

                        }
                        "27" -> {
                            //工作模式
                            when (parseObject[it]) {
                                "0" -> turnOffRadioButton.isChecked = parseObject[it] as Boolean
                                "1" -> autoRadioButton.isChecked = true
                                "2" -> pointRadioButton.isChecked = true
                                "3" -> {}
                                "4" -> edgeRadioButton.isChecked = true
                                "5" -> rechargeRadioButton.isChecked = true
                                "6" -> {}
                                "7" -> {}
                                "8" -> {}
                                "9" -> {}
                                "10" -> {}
                                "11" -> {}
                                "12" -> {}
                                "13" -> {}
                                "14" -> {}
                                "15" -> {}
                            }
                        }
                        "29" -> {
                            //打扫速度
                        }
                        "30" -> {
                            //工作状态
                            workStateView.text = when (parseObject[it]) {
                                "1" -> "工作中"
                                "2" -> "停止中"
                                "3" -> "充电中"
                                "4" -> "找回充电"
                                "5" -> "休眠中"
                                "6" -> "报错中"
                                "7" -> "升级中"
                                "8" -> "寻回机器中"
                                "9" -> "功能演示中"
                                else -> "备用中"
                            }
                        }
                        "31" -> {
                            //UV灯
                        }
                        "32" -> {
                            //语言包
                        }
                        "33" -> {
                            //静音模式
                        }
                        "34" -> {
                            //寻回
                        }
                        "35" -> {
                            //机器时间同步
                        }
                        "38" -> {
                            //清扫时间
                            workingTimeView.text = "${parseObject[it]}min"
                        }
                        "43" -> {
                            //声音
                        }
                        "44" -> {
                            //清扫强度
                        }
                        "45" -> {
                            //清扫记录
                        }
                        "46" -> {
                            //累计面积
                        }
                        "47" -> {
                            //累计次数
                        }
                        "48" -> {
                            //累计时间
                        }
                        "49" -> {
                            //耗材使用
                        }
                    }
                }
            }
        })

        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.autoRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "27".createCommand("1"))
                }
                R.id.pointRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "27".createCommand("2"))
                }
                R.id.edgeRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "27".createCommand("4"))
                }
                R.id.rechargeRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "27".createCommand("5"))
                }
                R.id.cycleRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "34".createCommand(true))
                }
            }
        }

        timeConfigLayout.setOnClickListener {
            "此功能待后续完善".show(context)
        }

        cleanRecordLayout.setOnClickListener {
            "此功能待后续完善".show(context)
        }

        settingsLayout.setOnClickListener {
            navigatePageTo<RobotSettingsActivity>(deviceId)
        }
    }

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

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

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

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