package com.casic.br.view.device.waterheater

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.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.pengxh.kt.lite.widget.dialog.BottomActionSheet
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_once_config.*
import kotlinx.android.synthetic.main.include_base_title.*
import kotlin.math.abs

class OnceConfigActivity : KotlinBaseActivity() {

    private val kTag = "OnceConfigActivity"
    private lateinit var deviceInstance: ITuyaDevice
    private val onceTimeScope = arrayListOf(
        "30s",
        "1min",
        "2min",
        "3min",
        "4min",
        "5min",
        "6min",
        "7min",
        "8min",
        "9min",
        "10min",
        "11min",
        "12min",
        "13min",
        "14min",
        "15min"
    )
    private val minTemp = 3
    private var maxTemp = 15
    private var currentProgress = 0
    private val keepTempTimeScope = arrayListOf(
        "0min",
        "30min",
        "60min",
        "90min",
        "120min",
        "150min",
        "180min",
        "240min",
        "300min",
        "720min"
    )

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

    override fun observeRequestState() {

    }

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

        leftBackView.setOnClickListener { finish() }
        titleView.text = "单次参数设置"
    }

    override fun initData() {
        val deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        //控制设备前必须初始家庭化数据，每次 App 活跃期间，初始化一次即可。
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)

        temperatureSlider.tickCount = abs(maxTemp - minTemp)
        tempDiffView.text =
            String.format("${minTemp + currentProgress}${resources.getString(R.string.temperature_unit)}")
        minTempView.text =
            String.format("$minTemp${resources.getString(R.string.temperature_unit)}")
        maxTempView.text =
            String.format("$maxTemp${resources.getString(R.string.temperature_unit)}")

        CommandManager.getTuyaDp(deviceInstance, "112")
        CommandManager.getTuyaDp(deviceInstance, "113")
        CommandManager.getTuyaDp(deviceInstance, "114")
        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) {
                        "112" -> {
                            onceTimeView.text = parseObject[it] as String
                        }
                        "113" -> {
                            val currentTemp = parseObject[it] as Int
                            temperatureSlider.currentProgress = currentTemp - minTemp
                        }
                        "114" -> {
                            keepTempTimeView.text = parseObject[it] as String
                        }
                    }
                }
            }
        })
    }

    override fun initEvent() {
        onceTimeView.text = onceTimeScope[0]
        onceTimeLayout.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(onceTimeScope)
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        onceTimeView.text = onceTimeScope[position]
                        //单次时长
                        CommandManager.sendTuyaDp(
                            deviceInstance, "112".createCommand(onceTimeScope[position])
                        )
                    }
                })
                .build().show()
        }

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

            override fun onStopMoving(slider: QMUISlider?, progress: Int, tickCount: Int) {
                //温度设置
                CommandManager.sendTuyaDp(
                    deviceInstance, "113".createCommand(minTemp + progress)
                )
            }
        })

        keepTempTimeView.text = keepTempTimeScope[1]
        keepTempTimeLayout.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(keepTempTimeScope)
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        keepTempTimeView.text = keepTempTimeScope[position]
                        //保温时长
                        if (keepTempTimeScope[position] == "0min") {
                            CommandManager.sendTuyaDp(
                                deviceInstance, "114".createCommand("danci")
                            )
                        } else {
                            CommandManager.sendTuyaDp(
                                deviceInstance, "114".createCommand(keepTempTimeScope[position])
                            )
                        }
                    }
                })
                .build().show()
        }
    }

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