package com.develop.step.ui.cook_step

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.develop.base.ext.load
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.develop.base.ext.setGone
import com.develop.base.ext.setVisible
import com.develop.base.ext.updateText
import com.develop.base.util.MusicBackPlayerUtil
import com.develop.base.util.ThreadUtils
import com.develop.common.router.Screens
import com.develop.common.widget.TimePickerView
import com.develop.step.CookSettingType
import com.develop.common.R
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.entity.UserFavoriteRecipes
import com.develop.common.data_repo.db.entity.UserHistoryRecipes
import com.develop.common.dialog.CancelConfirmDialog
import com.develop.common.dialog.CookStepCompleteDialog
import com.develop.common.dialog.PotCoverUnlockedDialog
import com.develop.common.event.CookStepEvent
import com.develop.common.food_sdk.FloatWindowManager
import com.develop.common.food_sdk.FoodSdkUtils
import com.develop.common.tag.CURRENT_USER_ID
import com.develop.common.tag.PRESS_DOWN_KEY_CODE
import com.develop.common.tag.TURN_DOWN_KEY_CODE
import com.develop.common.tag.TURN_UP_KEY_CODE
import com.develop.common.utils.CofarUtils
import com.develop.common.utils.TimeUtil
import com.develop.step.ui.cook_step.model.CookStepStatus
import com.develop.step.ui.cook_step.model.CookStepUiData
import com.kuyuntech.cofarcooking.device.sdk.constant.core.*
import com.kuyuntech.cofarcooking.device.sdk.eventbus.core.DevInfo
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.DevCommonEvent
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.greenrobot.eventbus.Subscribe
import java.io.File

@Route(path = Screens.Cook.COOK_STEP2)
class CookStepActivity : CookStepBaseActivity() {
    private var timeArray = IntArray(3)
    private val audioUtil = MusicBackPlayerUtil()
    private var audioMute = false
    private var pendingCookStep = false
    private var isHistory = false
    private var mSettingInstId = ""
    private var mRunningInstId = ""
    private var potCloverStatus = 1 //锅盖是否盖上 0 是 1 否
    private var coverPath: Any? = null
    private var isFromOverWrite = false


    private fun turnDevModeUI(){

        if(CofarSDK.devInfo().devMode == DevModes.AIR_FRYER){
            //隐藏点击
            binding.controller.clCookDirection.visibility = View.GONE;
            binding.controller.clCookSpeed.visibility = View.GONE;
            binding.controller.clCookWater.visibility = View.VISIBLE
        }

        if(CofarSDK.devInfo().devMode == DevModes.SOUP){
            //隐藏点击
            binding.controller.clCookDirection.visibility = View.VISIBLE;
            binding.controller.clCookSpeed.visibility = View.VISIBLE;
            binding.controller.clCookWater.visibility = View.GONE

        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //隐藏称重与电动
        binding.viewChangeCrush.setGone()
        binding.viewChangeWeight.setGone()

        binding.controller.clSetTime.onTimePickerCallback =
            object : TimePickerView.OnTimePickerCallback {
                override fun onTimePicker(
                    hours: Int,
                    minute: Int,
                    second: Int,
                    time: String,
                    setByUser: Boolean
                ) {
                    if (setByUser) {
                        viewModel.stepUiData.doingModify = true
                        val totalTime = second + (minute + hours * 60) * 60
                        viewModel.displayStep()?.uiData?.targetTime = totalTime
                        binding.controller.tvCookingTimeTarget.updateText("--${time}--")
                        CofarSDK.cfgTime(totalTime)
                    }
                }

                override fun onTimePickerTouchFirst() {
                    viewModel.stepUiData.doingModify = true
                }
            }
        binding.viewAlarm.setOnClickListener {
            audioMute = !audioMute
            if (audioMute) {
                audioUtil.stopBgSound()
                binding.viewAlarm.setBackgroundResource(R.drawable.ic_audio_mute)
            } else {
                binding.viewAlarm.setBackgroundResource(R.drawable.ic_alarm)
            }
        }


        binding.controller.jiahao.setOnClickListener{
            var event =  KeyEvent(0,0, KeyEvent.ACTION_DOWN,TURN_UP_KEY_CODE,0);
            this.dispatchKeyEvent(event);
        }

        binding.controller.jianhao.setOnClickListener{
            var event =  KeyEvent(0,0, KeyEvent.ACTION_DOWN,TURN_DOWN_KEY_CODE,0);
            this.dispatchKeyEvent(event);
        }

        binding.viewChangeWeight.setOnClickListener {
            if (CofarSDK.devInfo().status == DevStatus.RUNNING.toInt()) {
                Toast.makeText(this, "Step is running!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val weightSelected = binding.viewChangeWeight.isSelected
            if (weightSelected) {
                CofarSDK.stoptWeight()
                viewModel.setDisplayStep(viewModel.stepIndex, force = true)
            } else {
                binding.ivPrevStep.setGone()
                binding.ivNextStep.setGone()
                CofarSDK.changeMode(
                    "$recipeNumber:${viewModel.stepIndex}",
                    CofarSDK.devMode("WEIGHT")
                )
                changeWeightPanel()
                CofarSDK.stoptWeight()
                CofarSDK.startWeight()
            }
        }
        binding.viewChangeCrush.setOnClickListener {
            if (CofarSDK.devInfo().status == DevStatus.RUNNING.toInt()) {
                Toast.makeText(this, "Step is running!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val turboSelected = binding.viewChangeCrush.isSelected
            if (turboSelected) {
                CofarSDK.stoptWeight()
                viewModel.setDisplayStep(viewModel.stepIndex, force = true)
            } else {
                binding.ivPrevStep.setGone()
                binding.ivNextStep.setGone()
                CofarSDK.changeMode(
                    "$recipeNumber:${viewModel.stepIndex}",
                    CofarSDK.devMode("TURBO")
                )
                CofarSDK.stoptWeight()
                changeTurboPanel()
            }
            binding.viewChangeWeight.isSelected = false
            binding.viewChangeCrush.isSelected = !turboSelected
        }
        initData()
        initStepData()
        turnDevModeUI()
    }

    private fun initData() {
        viewModel.queryRecipeCookStep(recipeNumber ?: "", currentStepIndex)
        viewModel.stepDisplay.observe(this) { it ->
            coverPath = FoodDataProvider.getImagePath(it.source.photoVideoFilePath)
            if (it.workMode == "FINISH_DESC") {
                val stepCount = viewModel.getStepCount()
                val stepIndex = viewModel.allSteps.indexOf(it)
                changeDescription()
                cookProgressDrawable.setStepState(stepIndex, stepCount)
                binding.tvStepName.text = getText(R.string.engjoy_your_meal)
                binding.tvTitleStep.text = getText(R.string.recipe_complete)

                if (stepCount == 1) {
                    binding.ivPrevStep.setGone()
                    binding.ivNextStep.setGone()
                } else if (viewModel.isFirstStep(it)) {
                    binding.ivPrevStep.setGone()
                    binding.ivNextStep.setVisible()
                } else if (viewModel.isFinalStep(it)) {
                    binding.ivPrevStep.setVisible()
                    binding.ivNextStep.setGone()
                } else {
                    binding.ivPrevStep.setVisible()
                    binding.ivNextStep.setVisible()
                }

                var photoPath = it.source.photoVideoFilePath;
                if (photoPath == null || photoPath == "") {
                    photoPath = viewModel.recipe?.photoPath;
                }
                binding.ivCookBg.load(
                    FoodDataProvider.getResourcePath(photoPath),
                    R.drawable.bg_cook_session
                )
            } else {
                if (CofarSDK.devInfo().status == DevStatus.STOP.toInt()) {
                    CofarSDK.changeModeWithoutCfg(
                        "$recipeNumber:${viewModel.stepIndex}",
                        CofarSDK.devMode(it.workMode)
                    )
                }
                if (it.isWeightMode()) {
                    changeWeightPanel()
                    CofarSDK.stoptWeight()
                    CofarSDK.startWeight()
                } else if (it.isTurboMode()) {
                    CofarSDK.stoptWeight()
                    changeTurboPanel()
                } else if (it.isDescription()) {
                    CofarSDK.stoptWeight()
                    changeDescription()
                } else {
                    CofarSDK.stoptWeight()
                    changeTempSettingPanel()
                }
                val stepCount = viewModel.getStepCount()
                val stepIndex = viewModel.allSteps.indexOf(it)
//            //通知当前步骤信息给浮窗
//            EventBus.getDefault()
//                .post(
//                    CookStepEvent(
//                        recipeNumber ?: "",
//                        coverPath as String,
//                        stepIndex
//                    )
//                )
                cookProgressDrawable.setStepState(stepIndex, stepCount)
                if (it.source.description == null || it.source.description == "") {
                    var minute = "0"
                    var second = "0"
                    var temperature = "0"
                    var rotateSpeed = "0"
                    var rotateDirection = MotorDirections.FORWARD.toString()
                    if (it.source.minute != null) {
                        minute = it.source.minute.toString();
                    }
                    if (it.source.second != null) {
                        second = it.source.second.toString();
                    }
                    if (it.source.temperature != null) {
                        temperature =
                            CofarUtils.parseTemp(it.source.temperature!!.toShort()).toString();
                    }
                    if (it.source.rotateSpeed != null) {
                        rotateSpeed = it.source.rotateSpeed.toString();
                    }
                    if (it.source.rotateDirection != null && it.source.rotateDirection != "") {
                        rotateDirection = it.source.rotateDirection.toString();
                    }
                    val description =
                        "${temperature}°C/${minute}m${second}s/V${rotateSpeed}/${if (rotateDirection == MotorDirections.FORWARD.toString()) "R" else "L"}";
                    binding.tvStepName.text = description
                    binding.tvTitleStep.text = description
                } else {
                    binding.tvStepName.text = it.source.description
                    binding.tvTitleStep.text = it.source.description
                }
                if (stepCount == 1) {
                    binding.ivPrevStep.setGone()
                    binding.ivNextStep.setGone()
                } else if (viewModel.isFirstStep(it)) {
                    binding.ivPrevStep.setGone()
                    binding.ivNextStep.setVisible()
                } else if (viewModel.isFinalStep(it)) {
                    binding.ivPrevStep.setVisible()
                    binding.ivNextStep.setGone()
                } else {
                    binding.ivPrevStep.setVisible()
                    binding.ivNextStep.setVisible()
                }
                var photoPath = it.source.photoVideoFilePath;
                if (photoPath == null || photoPath == "") {
                    photoPath = viewModel.recipe?.photoPath;
                }
                binding.ivCookBg.load(
                    FoodDataProvider.getResourcePath(photoPath),
                    R.drawable.bg_cook_session
                )
                updateUiSetting(it)
                playStepAudio(it.source.audioFilePath)
                tryConsumePendingCookStep(it)
            }

            // initStepData()

        }

        backRequestDialog.apply {
            title = "Keep cooking in the background?"
            onDialogClickListener = object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    val info = CofarSDK.devInfo().runningInstId.split(":");

                    val cookStepEvent = CookStepEvent(
                        info[0],
                        coverPath as String,
                        info[1].toInt(),
                        isMode = false
                    )
                    FloatWindowManager.showStepFlowWindow(cookStepEvent)
                    finish()
                }

                override fun onCancel() {
                    FloatWindowManager.hideStepFlowWindow()
                    CofarSDK.stop(false)
                    finish()
                }
            }
        }

        overrideModeDialog.apply {
            title =
                "Overwrite current cooking process?\n By overwriting,your current progress will got lost."
            onDialogClickListener = object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    isFromOverWrite = true
                    viewModel.displayStep()?.let {
                        viewModel.setTargetCookingStep(it)
                        configDataAndStart(it.uiData)
                    }
                    val cookStepEvent = CookStepEvent(
                        recipeNumber ?: "",
                        coverPath as String,
                        viewModel.stepIndex,
                        isMode = false
                    )
                    FloatWindowManager.showStepFlowWindow(cookStepEvent)
                    recordRecipes()
                }

                override fun onCancel() {

                }
            }
        }

    }

    private fun playStepAudio(audioPath: String?) {
        audioUtil.stopBgSound()
        if (audioMute) {
            return
        }
        if (!audioPath.isNullOrEmpty()) {
            val filePath = FoodDataProvider.getResourcePath(audioPath)
            if (File(filePath).exists()) {
                audioUtil.playBgSound(filePath)
            }
        }
    }


    var configing: Boolean = false

    private fun initStepData() {
        if (CofarSDK.devInfo().status == DevStatus.STOP.toInt()) {
            configing = true;
            viewModel.allSteps.get(viewModel.stepIndex)?.let {

                it.uiData.applyRecipeSetting(it.source)

                if (!it.isWeightMode() && !it.isDescription()) {
                    //设置初始参数
                    CofarSDK.cfgMotorGear(0)
                    CofarSDK.cfgTime(0)
                    ThreadUtils.runOnMainThread({
                        CofarSDK.cfgMotor(it.uiData.currentSpeed.toByte(),it.uiData.direction.toByte(),1);
                        CofarSDK.cfgTime(it.uiData.targetTime)
                        CofarSDK.cfgHeat(it.uiData.targetTemp.toShort(), 0)
                    },200)


                }
                ThreadUtils.runOnMainThread({
                    configing = false
                }, 500)

            }

        }

    }

    override fun clickNextStep() {
        if (viewModel.isCurrentOnCookingStep()
            && viewModel.cookingStep?.isManualStep() == true || runningState == DevStatus.STOP.toInt()
        ) {
            // 当前为手动步骤, 下一个步骤切换会设置为当前烹饪步骤
            pendingCookStep = true
        }
        viewModel.nextStep()

        initStepData() //初始化步骤参数


    }

    override fun clickPrevStep() {
        if (viewModel.isCurrentOnCookingStep() && viewModel.cookingStep?.isManualStep() == true
            || runningState == DevStatus.STOP.toInt()
        ) {
            // 当前为手动步骤, 上一个步骤切换会设置为当前烹饪步骤
            pendingCookStep = true
        }
        viewModel.prevStep()
        initStepData()
    }

    /**
     * 前一个步骤为称重步骤, 切换到左/右步骤后自动设定为当前步骤, 有自动开始字段则自动开始烹饪
     */
    private fun tryConsumePendingCookStep(status: CookStepStatus) {
        if (!pendingCookStep) {
            return
        }
        pendingCookStep = false
        viewModel.setTargetCookingStep(status)
//        if (status.source.autoStart == "1") {
//            configDataAndStart(status.uiData)
//        }
    }

    /**
     * BUTTON_TAG_START
     * BUTTON_TAG_PAUSE
     * BUTTON_TAG_RESUME
     * BUTTON_TAG_CONFIRM
     */
    override fun clickFirstButton(tag: String) {
        handleButtonState(tag)
    }

    /**
     * BUTTON_TAG_CANCEL
     * BUTTON_TAG_STOP
     * BUTTON_TAG_RESET
     */
    override fun clickSecondButton(tag: String) {
        handleButtonState(tag)
    }

    private fun handleButtonState(tag: String) {
        if (tag == BUTTON_TAG_START) {
            if (CofarSDK.devInfo().potCloverStatus.toInt() == 1) {
                showPotCloverDialog()
            } else if (CofarSDK.devInfo().runningInstId != "${recipeNumber}:${viewModel.stepIndex}") {
                overrideModeDialog.showDialog(supportFragmentManager, "overrideModeDialog")
            } else {
                viewModel.displayStep()?.let {
                    viewModel.setTargetCookingStep(it)
                    configDataAndStart(it.uiData)
                }
                recordRecipes()
            }
        } else if (tag == BUTTON_TAG_PAUSE) {
            CofarSDK.pause()
        } else if (tag == BUTTON_TAG_RESUME) {
            CofarSDK.resume()
        } else if (tag == BUTTON_TAG_CONFIRM) {
            CofarSDK.confirm()
            binding.controller.btnStart.setGone()
            binding.controller.btnReset.setGone()
        } else if (tag == BUTTON_TAG_STOP) {
            CofarSDK.stop(true)
        } else if (tag == BUTTON_TAG_RESET) {
            val current = viewModel.displayStep() ?: return
            val stepIndex = viewModel.allSteps.indexOf(current)
            val uiCopy = viewModel.dataCopy.getOrNull(stepIndex)
            uiCopy?.let {
                current.uiData.copyFrom(it)
                updateUiSetting(current)
            }
        } else if (tag == BUTTON_TAG_CANCEL) {
            CofarSDK.cancel()
            binding.controller.btnStart.setGone()
            binding.controller.btnReset.setGone()
        } else if (tag == BUTTON_TAG_NEXT_STEP) {
            viewModel.cookingStep?.let {
                binding.controller.llStepComplete.setGone()
                val nextStep = viewModel.getNextStep(it) ?: return@let
                viewModel.setTargetCookingStep(nextStep)
            }
        }
    }

    override fun clickWeightTare() {
        CofarSDK.clearWeight()
    }

    fun checkShowConfirm() {
//        if(runningState.toByte() != DevStatus.STOP){
//             viewModel.stepUiData.doingModify=true
//        }
    }

    override fun onUserChangeTemp(value: Int) {
        val v = FoodSdkUtils.parseTemp(value.toShort())
        viewModel.displayStep()?.uiData?.targetTemp = v.toInt()
        binding.controller.tvCookingTempTarget.updateText("--${v}°C--")
        binding.controller.tvRingTempText.updateText("${v}°C")
        CofarSDK.cfgHeat(value.toShort(), HeatModes.PU_TONG)
        checkShowConfirm()
    }

    override fun onUserChangeSpeed(value: Int) {
        viewModel.displayStep()?.uiData?.currentSpeed = value
        binding.controller.tvSetSpeed.updateText(value.toString())
        binding.controller.tvSpeedText.updateText(value.toString())
        CofarSDK.cfgMotorGear(value.toByte())
        checkShowConfirm()
    }

    override fun onUserWaterGear(value: Int) {
        CofarSDK.cfgWaterBear(value);
        binding.controller.waterSprayShow.updateGear(value)                               // 圆环设置-当前运行速度
        binding.controller.clCookWater.binding.waterSprayShow.updateGear(value)
        checkShowConfirm()
    }

    override fun onSettingDirection(value: Int) {
        viewModel.displayStep()?.uiData?.direction = value
        if (value == 0) {
            CofarSDK.cfgMotorDirection(MotorDirections.FORWARD)
            updateDirection(MotorDirections.FORWARD.toInt())
        } else {
            CofarSDK.cfgMotorDirection(MotorDirections.REVERSE)
            updateDirection(MotorDirections.REVERSE.toInt())
        }

        checkShowConfirm()
    }

    override fun onDevStateChange(devInfo: DevInfo) {
        if (configing) {
            return
        }
        viewModel.cookingStep?.let {
            potCloverStatus = devInfo.potCloverStatus.toInt()

            if (recipeNumber?.let { it1 -> CofarSDK.devInfo().runningInstId.equals("$it1:${viewModel.stepIndex}") } == true) {
                mRunningInstId = devInfo.runningInstId
                mSettingInstId = devInfo.settingInstId
                it.uiData.runningStatus = devInfo.status
                it.uiData.targetTemp = FoodSdkUtils.parseTemp(devInfo.targetTemp).toInt()
                it.uiData.targetTime = devInfo.targetTime
                it.uiData.currentSpeed = devInfo.motorGear.toInt()
                it.uiData.weightNum = devInfo.weight.toInt()
                it.uiData.direction = devInfo.motorDirection.toInt()
                it.uiData.currentTemp = FoodSdkUtils.parseTemp(devInfo.temp).toInt()
                it.uiData.remainTime = devInfo.remainTime
                it.uiData.targetTimeBuffer = devInfo.targetTimeBuffer
                it.uiData.isTimeChange = devInfo.mode.isTimeChange
                it.uiData.isTempChange = devInfo.mode.isTempChange
                it.uiData.isMotorDirectionChange = devInfo.mode.isMotorDirectionChange
                it.uiData.isMotorGearChange = devInfo.mode.isMotorGearChange
                it.uiData.limitMaxSpeed = devInfo.mode.maxMotorGear
                it.uiData.limitMinSpeed = devInfo.mode.minMotorGear
                it.uiData.limitMaxTemp = devInfo.mode.maxTemp
                it.uiData.limitMinTemp = devInfo.mode.minTemp
                it.uiData.limitMaxTime = devInfo.mode.maxTime
                it.uiData.limitMinTime = devInfo.mode.minTime

            }

            if (!it.hasStarted && devInfo.status == DevStatus.RUNNING.toInt()) {
                // 标记这个步骤曾经开始过了
                it.hasStarted = true
            }
            if (it.hasStarted && !it.hasComplete && devInfo.status == DevStatus.STOP.toInt()) {
                // 这个步骤目前已经结束了
                it.hasComplete = true
//                notifyStepComplete(it)
            }
        }
        if (viewModel.isCurrentOnCookingStep()) {
            viewModel.cookingStep?.let {
                updateUiSetting(it)
            }
        }
        // 重量设置
        viewModel.cookingStep?.apply {
            binding.tvWeightNum.updateText("${uiData.weightNum}g")
            binding.weightView.setWeightNumber(uiData.weightNum.toFloat())
        }
    }


    private fun showPotCloverDialog() {
        val warnDialog = supportFragmentManager.findFragmentByTag("WarningDialog")
        if (warnDialog == null) {
            supportFragmentManager
                .beginTransaction()
                .add(PotCoverUnlockedDialog(), "WarningDialog")
                .commitNowAllowingStateLoss()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun notifyStepComplete(cookStep: CookStepStatus) {
        if (viewModel.isFinalStep(cookStep)) {
            notifyAllCookStepComplete()
            return
        }
        setStepTextIconEnable(false)
        binding.controller.btnStart.text = "START NEXT STEP"
        binding.controller.llStepComplete.setVisible()
        binding.controller.tempRingView.visibility = View.INVISIBLE
        binding.controller.speedRingView.visibility = View.INVISIBLE
        binding.controller.tvSpeedText.visibility = View.INVISIBLE
        binding.controller.tvRingTempText.visibility = View.INVISIBLE
        binding.controller.clSetTime.visibility = View.INVISIBLE
        binding.controller.flDirection.visibility = View.INVISIBLE
    }

    private fun configDataAndStart(uiData: CookStepUiData) {
        CofarSDK.changeModeWithoutCfg(
            "$recipeNumber:${viewModel.stepIndex}",
            CofarSDK.devMode(viewModel.cookingStep?.workMode)
        )
        CofarSDK.cfgTime(uiData.targetTime.toInt())
        CofarSDK.cfgMotorDirection(
            if (uiData.direction == 0) {
                MotorDirections.FORWARD
            } else {
                MotorDirections.FORWARD
            }
        )
        CofarSDK.cfgMotorGear(uiData.currentSpeed.toByte())
        CofarSDK.cfgHeat(uiData.targetTemp.toShort(), HeatModes.PU_TONG)
        CofarSDK.cancel()
        if (isFromOverWrite) {
            //覆盖调用
            CofarSDK.startRunning("${recipeNumber}:${viewModel.stepIndex}")
            isFromOverWrite = false
        } else {
            CofarSDK.start("${recipeNumber}:${viewModel.stepIndex}")
        }
        //通知当前运行的菜谱的ID和当前步骤索引
        CofarSDK.startRecipe(recipeNumber, viewModel.stepIndex.toString())
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.action != KeyEvent.ACTION_UP) {
            when (event.keyCode) {
                TURN_UP_KEY_CODE -> {
                    operateByPhysical(true)
                }
                TURN_DOWN_KEY_CODE -> {
                    operateByPhysical(false)
                }
            }
        }
        return super.dispatchKeyEvent(event)
    }


    private fun rotateStep(): Int {

        viewModel.cookingStep?.let {
            if (it.uiData.targetTime >= 60) {
                return 10;
            }

            if (it.uiData.targetTime >= 10 * 60) {
                return 30;
            }
        }



        return 1
    }

    private fun operateByPhysical(increase: Boolean) {
        val cookStep = viewModel.displayStep()
        val tabType = getSelectedTabType()
        if (tabType == CookSettingType.TEMP_SETTING) {
            cookStep?.uiData?.let {
                if (!it.isTempChange) {
                    return
                }
                if (increase) {
                    it.targetTemp += CofarSDK.getTempInterval()
                    if (it.targetTemp > it.limitMaxTemp) {
                        it.targetTemp = it.limitMaxTemp
                    }
                } else {
                    it.targetTemp -= CofarSDK.getTempInterval()
                    if (it.targetTemp < it.limitMinTemp) {
                        it.targetTemp = it.limitMinTemp
                    }

                    if (it.targetTemp < 37) {
                        it.targetTemp = 0
                    }

                }
                viewModel.stepUiData.doingModify = true
                binding.controller.tempRingView.updateProgress(it.targetTemp)
                onUserChangeTemp(it.targetTemp)
            }
        } else if (tabType == CookSettingType.SPEED_SETTING) {
            cookStep?.uiData?.let {
                if (!it.isMotorGearChange) {
                    return
                }
                if (increase) {
                    it.currentSpeed++
                    if (it.currentSpeed > it.limitMaxSpeed) {
                        it.currentSpeed = it.limitMaxSpeed
                    }
                } else {
                    it.currentSpeed--
                    if (it.currentSpeed < it.limitMinSpeed) {
                        it.currentSpeed = it.limitMinSpeed
                    }
                }
                viewModel.stepUiData.doingModify = true
                binding.controller.speedRingView.updateProgress(it.currentSpeed)
                onUserChangeSpeed(it.currentSpeed)
            }
        } else if(tabType == CookSettingType.WATER_SPRY){
            cookStep?.uiData?.let {
                if (!it.isWaterGearChange) {
                    return
                }
                if (increase) {
                    it.currentWaterGear++
                    if (it.currentWaterGear > it.limitMaxWaterGear) {
                        it.currentWaterGear = it.limitMaxWaterGear
                    }
                } else {
                    it.currentWaterGear--
                    if (it.currentWaterGear < it.limitMinWaterGear) {
                        it.currentWaterGear = it.limitMinWaterGear
                    }
                }
                viewModel.stepUiData.doingModify = true
                binding.controller.waterRingView.updateProgress(it.currentWaterGear)
                onUserWaterGear(it.currentWaterGear)
            }
        }else if (tabType == CookSettingType.TIME_SETTING) {
            cookStep?.uiData?.let {
                if (!it.isTimeChange) {
                    return
                }
                dealWithTimeByOperation(it, increase)
            }
        }else if (tabType == CookSettingType.DIRECTION_SETTING) {
            cookStep?.uiData?.let {
                 if(increase){
                     onSettingDirection(MotorDirections.FORWARD.toInt())
                 }else{
                     onSettingDirection(MotorDirections.REVERSE.toInt())
                 }
            }
        }
    }

    private fun dealWithTimeByOperation(uiData: CookStepUiData, increase: Boolean) {
        //当前调节时间
        var targetTime = uiData.targetTime
        if (increase) {
            targetTime += rotateStep()
        } else {
            targetTime -= rotateStep()
        }
        if (targetTime > uiData.limitMaxTime) {
            targetTime = uiData.limitMaxTime
        }
        if (targetTime < uiData.limitMinTime) {
            targetTime = uiData.limitMinTime
        }
        val sec = targetTime % 60
        val min = ((targetTime / 60) % 60)
        val hour = (targetTime / 3600)
        var time = ""
        if (hour > 0) {
            time += if (hour < 10) {
                "0${hour}"
            } else {
                "${hour}"
            }

            time += if (min < 10) {
                ":0${min}"
            } else {
                ":${min}"
            }
        } else {
            time += if (min < 10) {
                "0${min}"
            } else {
                "${min}"
            }

            time += if (sec < 10) {
                ":0${sec}"
            } else {
                ":${sec}"
            }
        }
        uiData.isTimeChange = true
        uiData.targetTime = targetTime
        binding.controller.clSetTime.isTimeCanChange(true)
        // 回调到上面那个地方来设置时间
        TimeUtil.getTimes(targetTime, timeArray)
        binding.controller.clSetTime.setTimeInternal(
            timeArray[0],
            timeArray[1],
            timeArray[2],
            changeSetting = true,
            setByUser = true
        )
    }

    override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {

        if (CofarSDK.devInfo().status == DevStatus.RUNNING.toInt() || CofarSDK.devInfo().status == DevStatus.PAUSE.toInt()) {
            viewModel.stepUiData.doingModify = false
            clickFirstButton(BUTTON_TAG_STOP)
            Log.d("QQQQ", "click stop")
        }
        pressStartTime = -1L

        return super.onKeyLongPress(keyCode, event)
    }

    private var canStart = true

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        pressStartTime = -1L
        if (keyCode == PRESS_DOWN_KEY_CODE) {
            Log.d("QQQQ", "catch key down")
            //当前是turbo模式下
            if (viewModel.cookingStep?.isTurboMode() != true) {

                if (canStart) {
                    //非turbo模式
                    if (viewModel.stepUiData.doingModify && CofarSDK.devInfo().status.toByte() != DevStatus.STOP) {
                        //用户调节中
                        viewModel.stepUiData.doingModify = false
                        clickFirstButton(BUTTON_TAG_CONFIRM)
                        Log.d("QQQQ", "click confirm")
                    } else {
                        when (CofarSDK.devInfo().status) {
                            DevStatus.RUNNING.toInt() -> {
                                viewModel.stepUiData.doingModify = false
                                clickFirstButton(BUTTON_TAG_PAUSE)
                                Log.d("QQQQ", "click stop")
                            }
                            DevStatus.PAUSE.toInt() -> {
                                viewModel.stepUiData.doingModify = false
                                clickFirstButton(BUTTON_TAG_RESUME)
                                Log.d("QQQQ", "click stop")
                            }
                            DevStatus.STOP.toInt() -> {
                                viewModel.stepUiData.doingModify = false
                                clickFirstButton(BUTTON_TAG_START)
                                Log.d("QQQQ", "click start")
                            }
                            else -> {
                                Log.d("QQQQ", "nothing to do")
                            }
                        }
                    }
                }


            } else {
                turboUpEvent();
            }
        }
        canStart = true
        return super.onKeyUp(keyCode, event)
    }

    private var pressStartTime = -1L;


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == PRESS_DOWN_KEY_CODE) {
            Log.d("QQQQ", "catch key down")
            //当前是turbo模式下
            if (viewModel.cookingStep?.isTurboMode() == true) {
                turboDownEvent()
            } else {
                if (pressStartTime == -1L) {
                    pressStartTime = System.currentTimeMillis()
                }


                if (pressStartTime != -1L && (System.currentTimeMillis() - pressStartTime) > 1000 && event?.keyCode == PRESS_DOWN_KEY_CODE) {
                    this.onKeyLongPress(keyCode, event);
                    event.startTracking()
                    pressStartTime = -1L
                    canStart = false
                    return false
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 所有步骤已经结束，展示结束页面
     */
    private fun notifyAllCookStepComplete() {
        binding.controller.root.setGone()
        binding.tvStepName.setGone()
        binding.viewChangeCrush.setGone()
        binding.viewChangeWeight.setGone()
        binding.viewRemark.setGone()
        binding.ivTurboView.setGone()
        binding.llWeightView.setGone()
        binding.llStepFinish.setVisible()
        binding.ivAddToFav.setOnClickListener {
            if (isLike) {
                isLike = false
                FoodDataProvider.getUserDatabase().runInTransaction {
                    FoodDataProvider.getUserDatabase().userInfoDao().removeFavoriteRecipe(
                        CURRENT_USER_ID, recipeNumber ?: ""
                    )
                }
                binding.ivAddToFav.setBackgroundResource(R.drawable.ic_cook_fav)
            } else {
                isLike = true
                binding.ivAddToFav.setBackgroundResource(R.drawable.ic_like)
                FoodDataProvider.getUserDatabase().runInTransaction {
                    FoodDataProvider.getUserDatabase().userInfoDao().insertFavoriteRecipe(
                        UserFavoriteRecipes(CURRENT_USER_ID, recipeNumber ?: "")
                    )
                }
            }
        }
    }

    /**
     * 根据UI状态刷新View
     */
    @SuppressLint("SetTextI18n")
    private fun updateUiSetting(status: CookStepStatus, focusUpdate: Boolean = false) {
        val uiData = status.uiData

        if (viewModel.stepUiData.doingModify && (uiData.runningStatus == DevStatus.RUNNING.toInt() || uiData.runningStatus == DevStatus.PAUSE.toInt())) {
            binding.controller.btnStart.setVisible()
            binding.controller.btnReset.setVisible()
            binding.controller.btnStart.updateText(getString(R.string.confirm))
            binding.controller.btnReset.updateText(getString(R.string.cancel))
            binding.controller.btnStart.tag = BUTTON_TAG_CONFIRM
            binding.controller.btnReset.tag = BUTTON_TAG_CANCEL
        } else {
            if (uiData.runningStatus == DevStatus.STOP.toInt()) {
                binding.controller.btnStart.setVisible()
                binding.controller.btnReset.setVisible()
                binding.controller.btnStart.updateText(getString(R.string.start))
                binding.controller.btnReset.updateText(getString(R.string.reset_button))
                binding.controller.btnStart.tag = BUTTON_TAG_START
                binding.controller.btnReset.tag = BUTTON_TAG_RESET
            } else if (uiData.runningStatus == DevStatus.RUNNING.toInt()) {
                binding.controller.btnStart.setVisible()
                binding.controller.btnReset.setGone()
                binding.controller.btnStart.updateText(getString(R.string.pause))
                binding.controller.btnStart.tag = BUTTON_TAG_PAUSE
            } else {
                binding.controller.btnStart.setVisible()
                binding.controller.btnReset.setVisible()
                binding.controller.btnStart.updateText(getString(R.string.resume))
                binding.controller.btnReset.updateText(getString(R.string.stop))
                binding.controller.btnStart.tag = BUTTON_TAG_RESUME
                binding.controller.btnReset.tag = BUTTON_TAG_STOP
            }
        }
        // 已经开始运行, 并且不是当前步骤, 隐藏操作按钮, 禁止操作
        val modifyDisable = viewModel.isCookingStepStarted() && !viewModel.isCurrentOnCookingStep()
        binding.controller.speedRingView.setCanTouch(!modifyDisable && uiData.isMotorGearChange)
        binding.controller.tempRingView.setCanTouch(!modifyDisable && uiData.isTempChange)
        binding.controller.tvTurnLeft.isEnabled = !modifyDisable && uiData.isMotorDirectionChange
        binding.controller.tvTurnRight.isEnabled = !modifyDisable && uiData.isMotorDirectionChange
        binding.controller.clSetTime.isTimeCanChange(!modifyDisable && uiData.isTimeChange)
        if (modifyDisable || status.isManualStep()) {
            binding.controller.btnStart.setGone()
            binding.controller.btnReset.setGone()
        }

        binding.controller.speedRingView.setRange(
            uiData.limitMinSpeed.toFloat(), uiData.limitMaxSpeed.toFloat()
        )
        binding.controller.tempRingView.setRange(
            uiData.limitMinTemp.toFloat(), uiData.limitMaxTemp.toFloat()
        )
        binding.controller.clSetTime.setTimeRange(
            uiData.limitMinTime, uiData.limitMaxTime
        )

        // 播放电机转动动画
        if (viewModel.isCurrentOnCookingStep()
            && uiData.runningStatus == DevStatus.RUNNING.toInt()
            && uiData.currentSpeed > 0
        ) {
            playRotateAnimator(uiData.direction)
        } else {
            pauseRotateAnimator()
        }

        // 时间设置
        if (runningState == DevStatus.STOP.toInt()) {
            TimeUtil.getTimes(uiData.targetTime, timeArray)
        } else {
            TimeUtil.getTimes(uiData.remainTime, timeArray)
        }
        if (!viewModel.stepUiData.doingModify || focusUpdate) {
            binding.controller.clSetTime.setTimeInternal(
                timeArray[0],
                timeArray[1],
                timeArray[2],
                true
            ) // 表盘时间设置-当前剩余时间
            TimeUtil.getTimes(uiData.targetTime, timeArray)
            binding.controller.tvCookingTimeTarget.updateText("--${TimeUtil.formatTime(timeArray)}--") // 下面的TAB-目标运行时间
        }
        TimeUtil.getTimes(uiData.remainTime, timeArray)
        binding.controller.tvSetTime.updateText(TimeUtil.formatTime(timeArray))                            // 下面的TAB-当前剩余时间

        // 温度
        val showTemp =
            if (runningState == DevStatus.STOP.toInt()) uiData.targetTemp else uiData.currentTemp;
        if (!viewModel.stepUiData.doingModify || focusUpdate) {
            binding.controller.tvCookingTempTarget.updateText("--${uiData.targetTemp}°C--")            // 下面的TAB-目标运行温度
            binding.controller.tempRingView.updateProgress(showTemp)                                 // 圆环设置-当前运行温度
            binding.controller.tvRingTempText.updateText("${showTemp}°C")                     // 圆环内的数字-当前运行温度
        }
        binding.controller.tvTempValue.updateText("${uiData.currentTemp}°C")                       // 下面的TAB-当前运行温度

        // 速度设置
        if (!viewModel.stepUiData.doingModify || focusUpdate) {

            binding.controller.speedRingView.updateProgress(uiData.currentSpeed)                               // 圆环设置-当前运行速度
            binding.controller.tvSpeedText.updateText(uiData.currentSpeed.toString())                          // 圆环内的数字-当前运行速度
            binding.controller.tvSetSpeed.updateText(uiData.currentSpeed.toString())                           // 下面的TAB-当前运行速度
        }

        // 喷水设置
        if (!viewModel.stepUiData.doingModify || focusUpdate) {
            binding.controller.waterRingView.updateProgress(CofarSDK.devInfo().waterGear?:0)                               // 圆环设置-当前运行速度
            binding.controller.waterSprayShow.updateGear(CofarSDK.devInfo().waterGear?:0)                               // 圆环设置-当前运行速度
            binding.controller.clCookWater.binding.waterSprayShow.updateGear(CofarSDK.devInfo().waterGear?:0)                               // 圆环设置-当前运行速度
        }

        // 方向设置
        if (!viewModel.stepUiData.doingModify || focusUpdate) {
            updateDirection(uiData.direction)
        }
    }


    @Subscribe
    fun onDevCommonEvent(event: DevCommonEvent) {



        ThreadUtils.runOnMainThread({

            val mode = CofarSDK.devMode(viewModel.cookingStep?.workMode)

            if (CommonEventTypes.MOTOR_GEAR_RATHER_THEN_7 == event.type) {
                CofarSDK.cfgTime((10 * 60))

                viewModel.cookingStep?.let { updateUiSetting(it, true) }
            }


            if(CommonEventTypes.CONFIRM_STOP == event.type){
                clickNextStep();
            }

            if (CommonEventTypes.MOTOR_GEAR_RATHER_THEN_4_WITH_TEMP == event.type) {
                CofarSDK.cfgMotorGear(4)
                viewModel.cookingStep?.let { updateUiSetting(it, true) }
            }
        }, 500)


    }

    override fun onDestroy() {
        super.onDestroy()
        audioUtil.releaseMedia()
    }

    private fun recordRecipes() {
        if (!isHistory) {
            isHistory = true
            FoodDataProvider.getUserDatabase().runInTransaction {
                recipeNumber?.let {
                    FoodDataProvider.getUserDatabase().userInfoDao().removeHistoryRecipe(
                        CURRENT_USER_ID, it
                    )
                }
                FoodDataProvider.getUserDatabase().userInfoDao().insertHistoryRecipe(
                    UserHistoryRecipes(CURRENT_USER_ID, recipeNumber ?: "")
                )
            }
        }
    }
}