package com.casic.br.fragment.waterheater

import android.os.Handler
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.createCommand
import com.casic.br.extensions.disableLayout
import com.casic.br.extensions.enableLayout
import com.casic.br.utils.CommandManager
import com.casic.br.utils.SliderCallback
import com.casic.br.view.device.waterheater.GasConsumeActivity
import com.casic.br.view.device.waterheater.OnceConfigActivity
import com.casic.br.view.device.waterheater.TimeConfigActivity
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.qmuiteam.qmui.widget.QMUISlider
import com.tuya.smart.sdk.api.ITuyaDevice
import kotlinx.android.synthetic.main.fragment_device_waterheater_control.*
import kotlin.math.abs

class ControlPageFragment(private val deviceInstance: ITuyaDevice, private val deviceId: String) :
    KotlinBaseFragment() {

    companion object {
        lateinit var weakReference: WeakReferenceHandler
    }

    private val kTag = "ControlPageFragment"
    private val minTemp = 36
    private var maxTemp = 60
    private var currentProgress = 0
    private val timeScope = intArrayOf(30, 60, 120, 180)
    private var currentTimeProgress = 0

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

    override fun setupTopBarLayout() {

    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)
        //默认选中
        modeRadioGroup.check(R.id.kitchenRadioButton)
        setTemperatureScope()
        setTimeScope()
        modeRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.kitchenRadioButton -> {
                    maxTemp = 60
                    kitchenTimeLayout.enableLayout(timeSeekBar)
                }
                R.id.showerRadioButton -> {
                    maxTemp = 60
                    kitchenTimeLayout.disableLayout(timeSeekBar)
                }
                R.id.tempRadioButton -> {
                    maxTemp = 48
                    kitchenTimeLayout.disableLayout(timeSeekBar)
                }
            }
            setTemperatureScope()
        }
    }

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

    /**
     * 设置定时范围
     * */
    private fun setTimeScope() {
        timeSeekBar.tickCount = timeScope.size - 1
        timeSeekBar.currentProgress = currentTimeProgress
        currentTimeView.text = timeScope[currentTimeProgress].toString()
        minTimeView.text = "${timeScope.first()}"
        maxTimeView.text = "${timeScope.last()}"
    }

    override fun observeRequestState() {

    }

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

        kitchenRadioButton.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "2".createCommand("chufang"))
        }

        showerRadioButton.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "2".createCommand("shushiyu"))
        }

        tempRadioButton.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "2".createCommand("suiwengan"))
        }

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

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

        timeSeekBar.setCallback(object : SliderCallback() {
            override fun onProgressChange(
                slider: QMUISlider?, progress: Int, tickCount: Int, fromUser: Boolean
            ) {
                currentTimeProgress = progress
                currentTimeView.text = timeScope[currentTimeProgress].toString()
            }

            override fun onStopMoving(slider: QMUISlider?, progress: Int, tickCount: Int) {
                //厨房定时
                CommandManager.sendTuyaDp(
                    deviceInstance, "111".createCommand(timeScope[currentTimeProgress])
                )
            }
        })

        functionRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.onceRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "101".createCommand(true))
                }
                R.id.initiateRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "102".createCommand(true))
                }
                R.id.reservationRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "109".createCommand(true))
                }
                R.id.pressureRadioButton -> {
                    CommandManager.sendTuyaDp(deviceInstance, "110".createCommand(true))
                }
            }
        }

        //单次参数设定
        onceConfigLayout.setOnClickListener {
            requireContext().navigatePageTo<OnceConfigActivity>(deviceId)
        }

        //预约时间设定
        timeConfigLayout.setOnClickListener {
            requireContext().navigatePageTo<TimeConfigActivity>(deviceId)
        }

        //水气量消耗
        gasConsumeLayout.setOnClickListener {
            requireContext().navigatePageTo<GasConsumeActivity>(deviceId)
        }
    }

    private val callback = Handler.Callback { message ->
        if (message.what == 2022092601) {
            val parseObject = JSONObject.parseObject(message.obj as String)
            parseObject.keys.forEach {
                when (it) {
                    "1" -> {//开关机
                        turnOffRadioButton.isChecked = parseObject[it] as Boolean
                    }
                    "2" -> {

                    }
                    "9" -> {//温度设置
                        val tempValue = parseObject[it] as Int
                        //转为刻度
                        temperatureSlider.currentProgress = tempValue - minTemp
                    }
                    "111" -> {//厨房定时
                        val timeValue = parseObject[it]
                        timeScope.forEachIndexed { index, i ->
                            if (i == timeValue) {
                                timeSeekBar.currentProgress = index
                                return@forEach
                            }
                        }
                    }
                }
            }
        }
        true
    }

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