package com.casic.br.fragment.cooker

import android.os.Handler
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.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.show
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_cooker_control.*
import kotlin.math.abs


class ControlPageFragment(private val deviceInstance: ITuyaDevice) : KotlinBaseFragment() {

    companion object {
        lateinit var weakReference: WeakReferenceHandler
    }

    private val kTag = "ControlPageFragment"
    private var isDeviceWorking = false
    private val minTime = 0
    private var maxTime = 180
    private var leftCookerCurrentProgress = 0
    private var rightCookerCurrentProgress = 0

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

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {

    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)

        //左
        leftCookerTimeSlider.tickCount = abs(maxTime - minTime)
        leftCookerTimeSlider.currentProgress = leftCookerCurrentProgress
        leftCookerTimeView.text = String.format("${minTime + leftCookerCurrentProgress}")
        leftCookerMinTimeView.text = minTime.toString()
        leftCookerMaxTimeView.text = maxTime.toString()

        //右
        rightCookerTimeSlider.tickCount = abs(maxTime - minTime)
        rightCookerTimeSlider.currentProgress = rightCookerCurrentProgress
        rightCookerTimeView.text = String.format("${minTime + rightCookerCurrentProgress}")
        rightCookerMinTimeView.text = minTime.toString()
        rightCookerMaxTimeView.text = maxTime.toString()
    }

    private val callback = Handler.Callback { message ->
        when (message.what) {
            2022092901 -> {
                val parseObject = JSONObject.parseObject(message.obj as String)
                parseObject.keys.forEach {
                    var leftWork = false
                    var rightWork = false
                    when (it) {
                        "1" -> {
                            //soft, low, medium, high, close
                            leftWork = (parseObject[it] as String) != "close"
                            setTurnOffRadioButton(leftWork, rightWork)
                        }
                        "2" -> {
                            rightWork = (parseObject[it] as String) != "close"
                            setTurnOffRadioButton(leftWork, rightWork)
                        }
                        "3" -> {//定时
                            leftCookerCurrentProgress = parseObject[it] as Int
                            leftCookerTimeSlider.currentProgress = leftCookerCurrentProgress
                            leftCookerTimeView.text =
                                String.format("${minTime + leftCookerCurrentProgress}")
                        }
                        "5" -> {//倒计时
                            leftDelayTimeView.text = String.format("${parseObject[it]}min")
                        }
                        "4" -> {
                            rightCookerCurrentProgress = parseObject[it] as Int
                            rightCookerTimeSlider.currentProgress = rightCookerCurrentProgress
                            rightCookerTimeView.text =
                                String.format("${minTime + rightCookerCurrentProgress}")
                        }
                        "6" -> {
                            rightDelayTimeView.text = String.format("${parseObject[it]}min")
                        }
                        "102" -> {
                            leftSwitch.isChecked = parseObject[it] as Boolean
                            if (!leftSwitch.isChecked) {
                                leftCookerCurrentProgress = 0
                                leftCookerTimeSlider.currentProgress = leftCookerCurrentProgress
                                leftCookerTimeView.text =
                                    String.format("${minTime + leftCookerCurrentProgress}")
                                leftDelayTimeView.text = "--"
                            }
                        }
                        "103" -> {
                            rightSwitch.isChecked = parseObject[it] as Boolean
                            if (!rightSwitch.isChecked) {
                                rightCookerCurrentProgress = 0
                                rightCookerTimeSlider.currentProgress = rightCookerCurrentProgress
                                rightCookerTimeView.text =
                                    String.format("${minTime + rightCookerCurrentProgress}")
                                rightDelayTimeView.text = "--"
                            }
                        }
                    }
                }
            }
        }
        true
    }

    private fun setTurnOffRadioButton(left: Boolean, right: Boolean) {
        turnOffRadioButton.isChecked = !(!left && !right)
        isDeviceWorking = turnOffRadioButton.isChecked
    }

    override fun initEvent() {
        turnOffRadioButton.setOnClickListener {
            if (isDeviceWorking) {
                CommandManager.sendTuyaDp(deviceInstance, "104".createCommand(true))
            } else {
                turnOffRadioButton.isChecked = false
                "燃气灶无法自动点火，请手动点火".show(requireContext())
            }
        }

        leftCookerTimeSlider.setCallback(object : SliderCallback() {
            override fun onProgressChange(
                slider: QMUISlider?, progress: Int, tickCount: Int, fromUser: Boolean
            ) {
                leftCookerCurrentProgress = progress
                leftCookerTimeView.text = String.format("${minTime + progress}")
            }

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

        rightCookerTimeSlider.setCallback(object : SliderCallback() {
            override fun onProgressChange(
                slider: QMUISlider?, progress: Int, tickCount: Int, fromUser: Boolean
            ) {
                rightCookerCurrentProgress = progress
                rightCookerTimeView.text = String.format("${minTime + progress}")
            }

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

        leftSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "102".createCommand(isChecked))
        }

        rightSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "103".createCommand(isChecked))
        }
    }
}