package com.casic.br.view.device.waterdispenser

import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.createCommand
import com.casic.br.utils.CommandManager
import com.casic.br.utils.SliderCallback
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.utils.Constant
import com.pengxh.kt.lite.utils.ImmerseStatusBarUtil
import com.qmuiteam.qmui.widget.QMUISlider
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.ITuyaDevice
import kotlinx.android.synthetic.main.activity_add_water_config.*
import kotlinx.android.synthetic.main.include_left_back_title.*
import kotlin.math.abs

class WaterConfigActivity : KotlinBaseActivity() {

    private val minTemp = 40
    private var maxTemp = 100
    private var currentProgress = 0
    private val volumeScope = intArrayOf(150, 300, 1000)
    private var currentTimeProgress = 0
    private lateinit var deviceInstance: ITuyaDevice

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

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        ImmerseStatusBarUtil.setColor(this, R.color.mainBackColor.convertColor(this))

        leftBackView.setOnClickListener { finish() }
        titleView.text = "即热式台式饮水机"
    }

    override fun initData() {
        val deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)

        setTemperatureScope()
        setVolumeScope()

        CommandManager.getTuyaDp(deviceInstance, "3")
        CommandManager.getTuyaDp(deviceInstance, "104")
        deviceInstance.registerDevListener(object : TuyaDeviceListener() {
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "3" -> {
                            //目标水温度
                            val tempValue = parseObject[it] as Int
                            currentTempView.text = String.format(
                                "$tempValue${resources.getString(R.string.temperature_unit)}"
                            )
                            //转为刻度
                            temperatureSlider.currentProgress = tempValue - minTemp
                        }
                        "104" -> {
                            //出水量
                            when (val volumeValue = parseObject[it] as String) {
                                "150ml" -> {
                                    volumeSeekBar.currentProgress = 0
                                    currentVolumeView.text = volumeValue
                                }
                                "300ml" -> {
                                    volumeSeekBar.currentProgress = 1
                                    currentVolumeView.text = volumeValue
                                }
                                else -> {
                                    volumeSeekBar.currentProgress = 2
                                    currentVolumeView.text = "无限"
                                }
                            }
                        }
                    }
                }
            }
        })
    }

    /**
     * 设置温度范围
     * */
    private fun setTemperatureScope() {
        temperatureSlider.tickCount = abs(maxTemp - minTemp)
        temperatureSlider.currentProgress = currentProgress
        currentTempView.text = String.format(
            "${minTemp + currentProgress}${resources.getString(R.string.temperature_unit)}"
        )
        minTempView.text = minTemp.toString()
        maxTempView.text = maxTemp.toString()
    }

    /**
     * 设置出水量范围
     * */
    private fun setVolumeScope() {
        volumeSeekBar.tickCount = volumeScope.size - 1
        volumeSeekBar.currentProgress = currentTimeProgress
        currentVolumeView.text = String.format("${volumeScope[currentTimeProgress]}mL")
        minVolumeView.text = "${volumeScope.first()}"
        maxVolumeView.text = "${volumeScope.last()}"
    }

    override fun initEvent() {
        temperatureSlider.setCallback(object : SliderCallback() {
            override fun onProgressChange(
                slider: QMUISlider?, progress: Int, tickCount: Int, fromUser: Boolean
            ) {
                currentProgress = progress
                currentTempView.text = String.format(
                    "${minTemp + progress}${resources.getString(R.string.temperature_unit)}"
                )
            }

            override fun onStopMoving(slider: QMUISlider?, progress: Int, tickCount: Int) {
                CommandManager.sendTuyaDp(
                    deviceInstance, "3".createCommand(minTemp + progress)
                )
            }
        })

        volumeSeekBar.setCallback(object : SliderCallback() {
            override fun onProgressChange(
                slider: QMUISlider?, progress: Int, tickCount: Int, fromUser: Boolean
            ) {
                currentTimeProgress = progress
                currentVolumeView.text = String.format("${volumeScope[currentTimeProgress]}mL")
            }

            override fun onStopMoving(slider: QMUISlider?, progress: Int, tickCount: Int) {
                CommandManager.sendTuyaDp(
                    deviceInstance, "102".createCommand(volumeScope[currentTimeProgress])
                )
            }
        })
    }

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