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.casic.br.view.device.waterdispenser.WaterConfigActivity
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_water_dispenser.*
import kotlinx.android.synthetic.main.include_device_title.*

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

    private val context: Context = this@WaterDispenserActivity
    private lateinit var deviceId: String
    private lateinit var tuyaOTA: ITuyaOta
    private lateinit var deviceInstance: ITuyaDevice

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

    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)

        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", "WaterDispenserActivity => onDpUpdate: $dpStr")
                //{"10":0,"101":29,"102":300,"103":false,"104":"300ml","105":"milk","106":true,"3":45,"7":30}
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "3" -> {
                            //目标水温度
                            targetWaterTempView.text = String.format(
                                "${parseObject[it]}${resources.getString(R.string.temperature_unit)}"
                            )
                        }
                        "7" -> {
                            //当前水温
                        }
                        "10" -> {
                            //故障
                        }
                        "101" -> {
                            //进水水温
                            importWaterTempView.text = String.format(
                                "${parseObject[it]}${resources.getString(R.string.temperature_unit)}"
                            )
                        }
                        "102" -> {}
                        "103" -> {
                            //出水开关
                            switchCheckBox.isChecked = parseObject[it] as Boolean
                        }
                        "104" -> {
                            //出水量
                            outputWaterView.text = when (parseObject[it]) {
                                "wuxian" -> "无限"
                                else -> parseObject[it] as String
                            }
                        }
                        "105" -> {
                            //水温模式
                            waterModeView.text = when (parseObject[it]) {
                                "normal" -> "常温"
                                "milk" -> "冲牛奶"
                                "coffee" -> "冲咖啡"
                                "boiling_water" -> "开水"
                                else -> "自定义"
                            }

                            when (parseObject[it]) {
                                "normal" -> normalRadioButton.isChecked = true
                                "milk" -> milkRadioButton.isChecked = true
                                "coffee" -> coffeeRadioButton.isChecked = true
                                "boiling_water" -> boiledRadioButton.isChecked = true
                                else -> customRadioButton.isChecked = true
                            }
                        }
                        "106" -> {
                            childCheckBox.isChecked = parseObject[it] as Boolean
                        }
                    }
                }
            }
        })
    }

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

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

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

        modeRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.normalRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "105".createCommand("normal"))
                }
                R.id.milkRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "105".createCommand("milk"))
                }
                R.id.coffeeRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "105".createCommand("coffee"))
                }
                R.id.boiledRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "105".createCommand("boiling_water"))
                }
                R.id.customRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "105".createCommand("customize"))
                }
            }
        }

        childCheckBox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                //童锁状态下不能出水
                switchCheckBox.isEnabled = false
                CommandManager.sendTuyaDp(deviceInstance, "106".createCommand(true))
            } else {
                switchCheckBox.isEnabled = true
                CommandManager.sendTuyaDp(deviceInstance, "106".createCommand(false))

                switchCheckBox.setOnCheckedChangeListener { _, switchIsChecked ->
                    if (switchIsChecked) {
                        CommandManager.sendTuyaDp(deviceInstance, "103".createCommand(true))
                    } else {
                        CommandManager.sendTuyaDp(deviceInstance, "103".createCommand(false))
                    }
                }
            }
        }

        settingsCheckBox.setOnClickListener {
            navigatePageTo<WaterConfigActivity>(deviceId)
        }
    }

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