package com.develop.step.ui

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.KeyEvent.ACTION_DOWN
import android.view.KeyEvent.ACTION_UP
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.develop.base.util.ThreadUtils
import com.develop.common.data_repo.db.ModesType
import com.develop.common.dialog.CancelConfirmDialog
import com.develop.common.event.CookStepEvent
import com.develop.common.food_sdk.FloatWindowManager
import com.develop.common.food_sdk.FoodSdkUtils
import com.develop.common.router.Screens
import com.develop.common.tag.MODE_TYPE
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.ui.CommonBVMActivity
import com.develop.common.utils.ConfigUtils
import com.develop.common.utils.getTimeStr
import com.develop.common.widget.DirectionView
import com.develop.common.widget.RingControlView
import com.develop.common.widget.TimePickerView
import com.develop.step.BuildConfig
import com.develop.step.CookSettingType
import com.develop.step.R
import com.develop.step.databinding.ActivityModeDetailBinding
import com.develop.step.viewmodel.ModesViewMode
import com.kuyuntech.cofarcooking.device.sdk.constant.core.CommonEventTypes
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevModes
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import com.kuyuntech.cofarcooking.device.sdk.constant.core.HeatModes
import com.kuyuntech.cofarcooking.device.sdk.constant.core.MotorDirections
import com.kuyuntech.cofarcooking.device.sdk.eventbus.core.DevInfo
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.DevCommonEvent
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.DevStatusEvent
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * 模式详情页
 */
@Route(path = Screens.Cook.COOK_MODES)
class ModesDetailActivity : CommonBVMActivity<ActivityModeDetailBinding, ModesViewMode>() {

    private var modeType = ModesType.CHOP.name
    private var lastModeType = ModesType.CHOP.name


    private var userChanging = false //当前是否用户在操作
    private var currDevInfo = DevInfo()
    private var modeChange = false
    private var mSettingInstId = ""
    private var mRunningInstId = ""
    private var mRunningState = 0
    private var currentTemp = 0
    private var currentMotorGer = 0
    private var currentWaterGear = 0;
    private var maxTemp = 0
    private var minTemp = 0
    private var maxMotorGear = 0
    private var minMotorGear = 0
    private var maxWaterGear = 0
    private var minWaterGear = 0

    private var currTime = 0L
    private var maxTime = 0L
    private var minTime = 0L
    private var isTempChange = false
    private var isTimeChange = false
    private var isMotorGearChange = false
    private var isWaterGearChange = false
    private var initModeData = false
    private var pressStartTime = -1L
    private var canStart = true

    private val backRequestDialog by lazy {
        CancelConfirmDialog()
    }
    private val overrideModeDialog by lazy {
        CancelConfirmDialog()
    }

    override fun createViewModel(): ModesViewMode {
        return getViewModel(ModesViewMode::class.java)
    }

    override fun createViewBinding(inflater: LayoutInflater): ActivityModeDetailBinding {
        return ActivityModeDetailBinding.inflate(inflater)
    }

    private fun turnDevModeUI(){

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


        }

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

        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        hasShowScreenSaver = true
        configLock = true
        turnDevModeUI();
        viewModel.modeType = intent.extras?.getString(MODE_TYPE, ModesType.CHOP.name) ?: ""
        viewModel.lastModeType = viewModel.modeType
        lastModeType = viewModel.modeType
        modeType = lastModeType
        //初始化模式数据
        initModeData(lastModeType)
        initData()
        initListener()
        ThreadUtils.runOnMainThread({configLock = false},500)
    }

    override fun onDestroy() {
        super.onDestroy()
        CofarSDK.stoptWeight()

        viewModel.stopTurbo()
        viewModel.cancelAnimator()
        hasShowScreenSaver = false
    }

    /**
     * 旋转物理键
     */
    var lastKeyTime = 0L
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        val spend = (System.currentTimeMillis() - lastKeyTime);
        if( spend < 10){
            return super.dispatchKeyEvent(event);
        }
        lastKeyTime = System.currentTimeMillis();
        val currentStep = viewModel.currentStep.value
        Log.d("aaaaaa", "${event.keyCode}")
        if (event.action != KeyEvent.ACTION_UP) {
            when (event.keyCode) {
                //旋转+
                TURN_UP_KEY_CODE -> {
                    when (currentStep) {
                        CookSettingType.TEMP_SETTING -> {
                            if (isTempChange) {
                                //当前调节温度
                                currentTemp += CofarSDK.getTempInterval()
                                if (currentTemp > maxTemp) {
                                    currentTemp = maxTemp
                                }
                                currentTemp = FoodSdkUtils.parseTemp(currentTemp.toShort()).toInt();
                                Log.d("aaaaaa++++", "curr=${currentTemp}  max=${maxTemp}")
                                binding.tempRingView.updateProgress(currentTemp)
                                tempRingEvent(currentTemp)
                            }
                        }
                        CookSettingType.SPEED_SETTING -> {
                            if (isMotorGearChange) {
                                //当前调节转速
                                currentMotorGer += 1
                                if (currentMotorGer > maxMotorGear) {
                                    currentMotorGer = maxMotorGear
                                }
                                binding.speedRingView.updateProgress(currentMotorGer)
                                motorGearSpeedEvent(currentMotorGer)
                            }
                        }
                    CookSettingType.WATER_SPRY -> {
                        if (isWaterGearChange) {
                            //当前调节转速
                            currentWaterGear += 1
                            if (currentWaterGear > maxWaterGear) {
                                currentWaterGear = maxWaterGear
                            }
                            binding.waterRingView.updateProgress(currentWaterGear)
                            waterGearSpeedEvent(currentWaterGear)
                        }
                    }
                        CookSettingType.TIME_SETTING -> {
                            if (isTimeChange) {
                                //当前调节时间
                                //dealWithTimeByOperation(true)
                                handleRotateTimeChange(rotateStep())
                            }
                        }
                        CookSettingType.DIRECTION_SETTING -> {
                            motorGearDirectionClick(DirectionView.Direction.RIGHT)

                        }
                        else -> {

                        }
                    }
                }
                //旋转-
                TURN_DOWN_KEY_CODE -> {
                    when (currentStep) {
                        CookSettingType.TEMP_SETTING -> {
                            if (isTempChange) {
                                //当前调节温度
                                currentTemp -= CofarSDK.getTempInterval()
                                if (currentTemp < minTemp) {
                                    currentTemp = minTemp
                                }

                                if (currentTemp < 37) { //小于37度置0
                                    currentTemp = 0
                                }

                                currentTemp = FoodSdkUtils.parseTemp(currentTemp.toShort()).toInt();

                                Log.d("aaaaaa------", "curr=${currentTemp}  min=${minTemp}")
                                binding.tempRingView.updateProgress(currentTemp)
                                tempRingEvent(currentTemp)
                            }
                        }
                        CookSettingType.SPEED_SETTING -> {
                            if (isMotorGearChange) {
                                //当前调节转速
                                currentMotorGer -= 1
                                if (currentMotorGer < minMotorGear) {
                                    currentMotorGer = minMotorGear
                                }
                                binding.speedRingView.updateProgress(currentMotorGer)
                                motorGearSpeedEvent(currentMotorGer)
                            }
                        }
                        CookSettingType.WATER_SPRY -> {
                            if (isWaterGearChange) {
                                //当前调节转速
                                currentWaterGear -= 1
                                if (currentWaterGear > maxWaterGear) {
                                    currentWaterGear = maxWaterGear
                                }
                                binding.waterRingView.updateProgress(currentWaterGear)
                                waterGearSpeedEvent(currentWaterGear)
                            }
                        }
                        CookSettingType.TIME_SETTING -> {
                            if (isTimeChange) {
                                //当前调节时间
                                //dealWithTimeByOperation(false)
                                handleRotateTimeChange(-rotateStep())
                            }
                        }
                        CookSettingType.DIRECTION_SETTING -> {
                            motorGearDirectionClick(DirectionView.Direction.LEFT)

                        }
                        else -> {

                        }
                    }
                }
            }
        }
        return super.dispatchKeyEvent(event)
    }

    /**
     * 物理键按下事件
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == PRESS_DOWN_KEY_CODE) {
            //当前是turbo模式下
            if (viewModel.modeType == ModesType.TURBO.name) {
                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)
    }

    /**
     * 物理键长按事件
     */
    override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {
        if (mRunningState == DevStatus.RUNNING.toInt() || currDevInfo.status == DevStatus.PAUSE.toInt()) {
            stopClick()
        } else if (mRunningState == DevStatus.STOP.toInt()) {
            startClick()
        }

        return super.onKeyLongPress(keyCode, event)
    }

    /**
     * 物理键离开事件
     */
    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        if (viewModel.modeType == ModesType.TURBO.name && event.keyCode == PRESS_DOWN_KEY_CODE) {
            //当前是turbo模式下,并且是物理键按下
            turboUpEvent()
            return false
        }
        pressStartTime = -1L

        if (viewModel.modeType != ModesType.TURBO.name && event.keyCode == PRESS_DOWN_KEY_CODE && canStart) {
            //非turbo模式
            if (userChanging && currDevInfo.status.toByte() != DevStatus.STOP) {
                //用户调节中
                confirmClick()
            } else {
                if (mRunningState == DevStatus.RUNNING.toInt()) {
                    pauseClick()
                } else if (currDevInfo.status == DevStatus.PAUSE.toInt()) {
                    resumeClick();
                } else if (mRunningState == DevStatus.STOP.toInt()) {
                    startClick()
                }
            }
        }
        canStart = true
        return super.onKeyUp(keyCode, event)
    }

    //======================================烹饪设备回调监听==================================\\

    @Subscribe
    fun onDevCommonEvent(event: DevCommonEvent) {

        if(configLock){
            return;
        }

        ThreadUtils.runOnMainThread({
            if (CommonEventTypes.MOTOR_GEAR_RATHER_THEN_7 == event.type) {
                CofarSDK.cfgTime((10 * 60))
                currDevInfo.mode.apply {
                    updateTimeUI(
                        minTime,
                        maxTime,
                        currDevInfo.targetTime,
                        currDevInfo.targetTime.toLong(),
                        isTimeChange = true,
                        focusUpdate = true
                    )
                }
            }

            if (CommonEventTypes.MAX_MOTOR_GEAR_RATHER_THEN_WITH_TEMP == event.type ) {
                CofarSDK.cfgMotorGear(CofarSDK.devInfo().mode.maxMotorWithTemp.toByte())
                currDevInfo.mode.apply {
                    updateMotorGearUI(
                        minMotorGear.toFloat(),
                        maxMotorGear.toFloat(),
                        CofarSDK.devInfo().mode.maxMotorWithTemp,
                        isMotorGearChange
                    )
                }
            }



            if ( CommonEventTypes.MOTOR_REVERSE_CAN_NOT_RATHER_THEN_3 == event.type) {
                CofarSDK.cfgMotorGear(3)
                currDevInfo.mode.apply {
                    updateMotorGearUI(
                        minMotorGear.toFloat(),
                        maxMotorGear.toFloat(),
                        3,
                        isMotorGearChange
                    )
                }
            }
        }, 500)
    }

    @Subscribe
    fun onDevStateEvent(event: DevStatusEvent) {
        if (!initModeData) {
            return
        }
        ThreadUtils.runOnMainThread {
            currDevInfo = event.devInfo
            mRunningState = currDevInfo.runningStatus.toInt()
            mRunningInstId = currDevInfo.runningInstId
            mSettingInstId = currDevInfo.settingInstId
            updateStatusBtn(currDevInfo.status.toByte())
            currDevInfo.mode.apply {
                updateTempUI(
                    minTemp.toFloat(),
                    maxTemp.toFloat(),
                    if (currDevInfo.status == DevStatus.STOP.toInt()) currDevInfo.targetTemp.toInt()
                    else currDevInfo.temp.toInt(),
                    currDevInfo.targetTemp.toString(),
                    isTempChange
                )
                updateTimeUI(
                    if(currDevInfo.status == DevStatus.STOP.toInt() || userChanging) minTime else 0,
                    maxTime,
                    if (currDevInfo.status == DevStatus.STOP.toInt()) currDevInfo.targetTime
                    else currDevInfo.remainTime,
                    currDevInfo.targetTime.toLong(),
                    isTimeChange
                )
                var motorGear = currDevInfo.motorGear.toInt()
                if (currDevInfo.motorGearBuffer.toInt() != -1) {
                    motorGear = currDevInfo.motorGearBuffer.toInt()
                }
                updateMotorGearUI(
                    minMotorGear.toFloat(),
                    maxMotorGear.toFloat(),
                    motorGear,
                    isMotorGearChange
                )


                var waterGear = if(currDevInfo.waterGear != null) currDevInfo.waterGear.toInt() else defaultMotorGear;
                if (currDevInfo.waterGearBuffer != null && currDevInfo.waterGearBuffer.toInt() != -1) {
                    waterGear = currDevInfo.waterGearBuffer.toInt()
                }
                updateWaterGearUI(
                    minWaterGear.toFloat(),
                    maxWaterGear.toFloat(),
                    waterGear,
                    isWaterGearChange
                )

                updateMotorDirectionUI(if(currDevInfo.motorDirectionBuffer.toInt() == -1) currDevInfo.motorDirection.toInt() else currDevInfo.motorDirectionBuffer.toInt(), isMotorDirectionChange)

                updateWeightUI(currDevInfo.weight.toFloat())
            }
        }
    }


    //======================================初始化数据和监听去==================================\\

    private fun initData() {
        var workMode = ConfigUtils.getMode(modeType)
        binding.tvModeName.text = getString(resources.getIdentifier(workMode?.name,"string",this.packageName))
        binding.ivBanner.setImageResource(resources.getIdentifier(workMode?.bg,"drawable",this.packageName))
//        // 获取ImageView的宽度和高度
//        val imageViewWidth = binding.ivBanner.width
//        val imageViewHeight = binding.ivBanner.height
//
//        // 设置ImageView的尺寸和scaleType属性
//        binding.ivBanner.layoutParams.width = imageViewWidth
//        binding.ivBanner.layoutParams.height = imageViewHeight
//        binding.ivBanner.scaleType = ImageView.ScaleType.FIT_CENTER
//
//        // 设置ImageView的图片
//        val bitmap = BitmapFactory.decodeResource(resources, resources.getIdentifier(workMode?.bg,"drawable",this.packageName))
//        binding.ivBanner.setImageBitmap(bitmap)
        //点击切换的模式来显示对应的UI
        viewModel.currentStep.observe(this) {
            if (it == null) {
                return@observe
            }
            if (it != CookSettingType.WEIGHT) {
                CofarSDK.stoptWeight()
            }
            when (it) {
                CookSettingType.WEIGHT -> {
                    changeWeightStep()
                }
                CookSettingType.TEMP_SETTING -> {
                    changeTempSettingStep()
                }
                CookSettingType.TIME_SETTING -> {
                    changeTimeSettingStep()
                }
                CookSettingType.SPEED_SETTING -> {
                    changeSpeedSettingStep()
                }
                CookSettingType.WATER_SPRY -> {
                   // changeSpeedSettingStep()
                    changeWaterSprySettingStep()
                }
                CookSettingType.DIRECTION_SETTING -> {
                    changeDirectionSettingStep()
                }
                CookSettingType.TURBO -> {
                    changeTurboStep()
                }
            }
        }
    }

    var configLock = false;


    private fun initModeData(type: String,keep:Boolean=false) {

        viewModel.modeType.apply {
            val baseMode = CofarSDK.devMode(this)
            //显示对应模式UI
            if (this == ModesType.WIGHT.name) {
                CofarSDK.recordConfig()

                //称重模式
                viewModel.changeStep(CookSettingType.WEIGHT)
                CofarSDK.changeMode(baseMode)
            } else if (this == ModesType.TURBO.name) {
                CofarSDK.recordConfig()

                viewModel.changeStep(CookSettingType.TURBO)
                CofarSDK.changeMode(baseMode)
            } else {
                //其他模式
                changeCommonStep()



                viewModel.changeStep(CookSettingType.TEMP_SETTING)

                if(CofarSDK.devInfo().status != DevStatus.PAUSE.toInt() && CofarSDK.devInfo().status != DevStatus.RUNNING.toInt()){

                    var targetTemp = baseMode.defaultTemp.toShort()
                    var motorDirection = baseMode.motorDirection.toByte()
                    var motorGear = baseMode.defaultMotorGear.toByte()
                    var targetTime = baseMode.defaultTime.toInt()

                    if(keep){
                        var restoreConfig:DevInfo ?= null
                        configLock = true;
                        restoreConfig = CofarSDK.changeMode(type, baseMode,true)
                        ThreadUtils.runOnMainThread({
                            configLock = false;
                        },500);
                        if(restoreConfig != null){
                            targetTemp = restoreConfig.targetTemp;
                            motorDirection = restoreConfig.motorDirection;
                            motorGear = restoreConfig.motorGear;
                            targetTime = restoreConfig.targetTime;
                        }
                    }else{
                        CofarSDK.changeMode(type, baseMode)
                    }

//                    currDevInfo.apply {
//                        targetTemp = baseMode.defaultTemp.toShort()
//                        motorDirection = baseMode.motorDirection.toByte()
//                        motorGear = baseMode.defaultMotorGear.toByte()
//                        targetTime = baseMode.defaultTime.toInt()
//                    }




                    baseMode.apply {
                        currentTemp = targetTemp.toInt()
                        updateTempUI(
                            minTemp.toFloat(),
                            maxTemp.toFloat(),
                            currentTemp,
                            targetTemp.toString(),
                            isTempChange,
                            true
                        )

                        currTime = targetTime.toLong()
                        updateTimeUI(
                            minTime,
                            maxTime,
                            currTime.toInt(),
                            targetTime.toLong(),
                            isTimeChange,
                            true
                        )

                        currentMotorGer = defaultMotorGear
                        updateMotorGearUI(
                            minMotorGear.toFloat(),
                            maxMotorGear.toFloat(),
                            motorGear.toInt(),
                            isMotorGearChange,
                            focusUpdate = true
                        )

                        updateMotorDirectionUI(motorDirection.toInt(), isMotorDirectionChange)

                        updateWeightUI(currDevInfo.weight.toFloat())
                    }
                }



            }
            initModeData = true
        }

    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initListener() {
        binding.ivBack.setOnClickListener {
            backClick()
        }
        binding.clCookTemp.setOnClickListener {
            viewModel.changeStep(CookSettingType.TEMP_SETTING)
        }
        binding.clCookTime.setOnClickListener {
            viewModel.changeStep(CookSettingType.TIME_SETTING)
        }
        binding.clCookSpeed.setOnClickListener {
            viewModel.changeStep(CookSettingType.SPEED_SETTING)
        }
        binding.clCookDirection.setOnClickListener {
            viewModel.changeStep(CookSettingType.DIRECTION_SETTING)
        }

        binding.clCookWater.setOnClickListener {
            viewModel.changeStep(CookSettingType.WATER_SPRY)
        }

        binding.ivTurbo.setOnClickListener {
            turboClick()
        }

        binding.ivWeight.setOnClickListener {
            weightClick()
        }

        binding.btnStart.setOnClickListener {
            startClick()
        }

        binding.btnResume.setOnClickListener {
            resumeClick()
        }

        binding.btnPause.setOnClickListener {
            pauseClick()
        }

        binding.btnStop.setOnClickListener {
            stopClick()
        }

        binding.btnCancel.setOnClickListener {
            cancelClick()
        }

        binding.btnConfirm.setOnClickListener {
            confirmClick()
        }

        binding.tvWeightTare.setOnClickListener {
            weightClearClick()
        }

        binding.btnReset.setOnClickListener {
            resetConfigClick()
        }


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


        binding.tempRingView.onRingViewListener = object : RingControlView.OnRingViewListener {
            override fun onProgressChange(progress: Int) {
                val pg = FoodSdkUtils.parseTemp(progress.toShort()).toInt()
                currentTemp = pg
                tempRingEvent(pg)
            }
        }

        backRequestDialog.apply {
            title = "Keep cooking in the background?"
            onDialogClickListener = object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    val cookStepEvent = CookStepEvent(
                        coverPath = viewModel.getBanner(),
                        isMode = true,
                        modeName = viewModel.modeType
                    )
                    FloatWindowManager.showStepFlowWindow(cookStepEvent)
                    finish()
                }

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

        overrideModeDialog.apply {
            title =
                "Overwrite current cooking process?\n By overwriting,your current progress will got lost."
            onDialogClickListener = object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    val cookStepEvent = CookStepEvent(
                        coverPath = viewModel.getBanner(),
                        isMode = true,
                        modeName = viewModel.modeType
                    )
                    FloatWindowManager.showStepFlowWindow(cookStepEvent)
                    when (viewModel.modeType) {
                        ModesType.WIGHT.name -> {
                            CofarSDK.stop(false)
                            CofarSDK.startWeight()
                        }
                        ModesType.TURBO.name -> {
                            CofarSDK.stop(false)
                        }
                        else -> {
                            userChanging = false
                            CofarSDK.startRunning(viewModel.modeType)
                        }
                    }
                }

                override fun onCancel() {

                }
            }
        }

        binding.speedRingView.onRingViewListener = object : RingControlView.OnRingViewListener {
            override fun onProgressChange(progress: Int) {
                currentMotorGer = progress
                motorGearSpeedEvent(progress)
            }
        }

        binding.waterRingView.onRingViewListener = object : RingControlView.OnRingViewListener {
            override fun onProgressChange(progress: Int) {
                currentWaterGear = progress
                waterGearSpeedEvent(progress)
            }
        }

        binding.clSetTime.onTimePickerCallback = object : TimePickerView.OnTimePickerCallback {
            override fun onTimePicker(
                hours: Int, minute: Int, second: Int, time: String, setByUser: Boolean
            ) {
                if (setByUser) {
                    //  currTime = time.toLong()
                }
                rollTimeEvent(hours, minute, second, time, setByUser)
            }

            override fun onTimePickerTouchFirst() {
                userChanging = true
            }
        }

        binding.flDirection.onDirectionClickListener =
            object : DirectionView.OnDirectionClickListener {
                override fun onDirectionClick(direction: DirectionView.Direction) {
                    motorGearDirectionClick(direction)
                }
            }

        /**
         * turbo触摸事件
         */
        binding.llTurboView.setOnTouchListener { view, motionEvent ->
            when (motionEvent.action) {
                MotionEvent.ACTION_DOWN -> {
                    turboDownEvent()
                }
                MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    turboUpEvent()
                }
            }
            true
        }
    }

    //======================================UI更新的方法==================================\\

    /**默认显示的UI，切换到温度*/
    private fun changeCommonStep() {
        binding.functionLayout.visibility = View.VISIBLE
        binding.llWeightView.visibility = View.GONE
        if (viewModel.modeType == ModesType.WIGHT.name || viewModel.modeType == ModesType.TURBO.name) {
            binding.ivWeight.visibility = View.GONE
            binding.ivTurbo.visibility = View.GONE
            if (viewModel.modeType == ModesType.TURBO.name) {
                binding.llTurboView.visibility = View.VISIBLE
            }
        } else {
            binding.ivWeight.visibility = View.VISIBLE
            binding.ivTurbo.visibility = View.VISIBLE
        }
        turnDevModeUI()
        changeTempSettingStep()
    }

    /**切换到称重*/
    private fun changeWeightStep() {
        binding.ivWeight.visibility = View.GONE
        binding.ivTurbo.visibility = View.GONE
        binding.functionLayout.visibility = View.GONE
        binding.llWeightView.visibility = View.VISIBLE
        binding.llTurboView.visibility = View.GONE
        //开始称重
        CofarSDK.startWeight()
    }

    /**切换到切碎*/
    private fun changeTurboStep() {
        binding.ivWeight.visibility = View.GONE
        binding.ivTurbo.visibility = View.GONE
        binding.functionLayout.visibility = View.GONE
        binding.llTurboView.visibility = View.VISIBLE
        binding.llWeightView.visibility = View.GONE
    }

    /**切换到温度*/
    private fun changeTempSettingStep() {
        binding.llWeightView.visibility = View.GONE
        binding.functionLayout.visibility = View.VISIBLE
        binding.tempRingView.visibility = View.VISIBLE
        binding.tempRingText.visibility = View.VISIBLE
        binding.speedRingView.visibility = View.GONE
        binding.speedRingText.visibility = View.GONE
        binding.tempRingTextCooking.visibility = View.GONE
        binding.clSetTime.visibility = View.GONE
        binding.flDirection.visibility = View.GONE
        binding.waterRingView.visibility = View.GONE
        binding.waterSprayShow.visibility = View.GONE

        setPanelViewProperty(CookSettingType.TEMP_SETTING)
    }

    /**切换到时间*/
    private fun changeTimeSettingStep() {
        binding.llWeightView.visibility = View.GONE
        binding.functionLayout.visibility = View.VISIBLE
        binding.tempRingView.visibility = View.INVISIBLE
        binding.speedRingView.visibility = View.GONE
        binding.speedRingText.visibility = View.GONE
        binding.tempRingText.visibility = View.GONE
        binding.tempRingTextCooking.visibility = View.GONE
        binding.clSetTime.visibility = View.VISIBLE
        binding.flDirection.visibility = View.GONE
        binding.waterRingView.visibility = View.GONE
        binding.waterSprayShow.visibility = View.GONE

        setPanelViewProperty(CookSettingType.TIME_SETTING)
    }

    /**切换到转速*/
    private fun changeSpeedSettingStep() {
        binding.llWeightView.visibility = View.GONE
        binding.functionLayout.visibility = View.VISIBLE
        binding.tempRingView.visibility = View.INVISIBLE
        binding.tempRingText.visibility = View.INVISIBLE
        binding.speedRingView.visibility = View.VISIBLE
        binding.speedRingText.visibility = View.VISIBLE
        binding.tempRingTextCooking.visibility = View.GONE
        binding.clSetTime.visibility = View.GONE
        binding.flDirection.visibility = View.GONE
        binding.waterRingView.visibility = View.GONE
        binding.waterSprayShow.visibility = View.GONE

        setPanelViewProperty(CookSettingType.SPEED_SETTING)
    }

    /**切换到方向*/
    private fun changeDirectionSettingStep() {
        binding.llWeightView.visibility = View.GONE
        binding.functionLayout.visibility = View.VISIBLE
        binding.tempRingView.visibility = View.INVISIBLE
        binding.tempRingText.visibility = View.GONE
        binding.speedRingView.visibility = View.GONE
        binding.speedRingText.visibility = View.GONE
        binding.tempRingTextCooking.visibility = View.GONE
        binding.clSetTime.visibility = View.GONE
        binding.flDirection.visibility = View.VISIBLE
        binding.waterRingView.visibility = View.GONE
        binding.waterSprayShow.visibility = View.GONE

        setPanelViewProperty(CookSettingType.DIRECTION_SETTING)
    }

    /**切换到*/
    private fun changeWaterSprySettingStep() {
        binding.llWeightView.visibility = View.GONE
        binding.functionLayout.visibility = View.VISIBLE
        binding.tempRingView.visibility = View.INVISIBLE
        binding.tempRingText.visibility = View.GONE
        binding.speedRingView.visibility = View.GONE
        binding.speedRingText.visibility = View.GONE
        binding.tempRingTextCooking.visibility = View.GONE
        binding.clSetTime.visibility = View.GONE
        binding.flDirection.visibility = View.GONE
        binding.clCookWater.visibility = View.VISIBLE
        binding.waterRingView.visibility = View.VISIBLE
        binding.waterSprayShow.visibility = View.VISIBLE

        setPanelViewProperty(CookSettingType.WATER_SPRY)
    }

    private fun setPanelViewProperty(selectStep: CookSettingType) {
        binding.apply {
            clCookTemp.upSelectedView(false)
            clCookTime.upSelectedView(false)
            clCookSpeed.upSelectedView(false)
            clCookDirection.upSelectedView(false)
            clCookWater.upSelectedView(false)
            when (selectStep) {
                CookSettingType.TEMP_SETTING -> {
                    clCookTemp.upSelectedView(true)
                }
                CookSettingType.TIME_SETTING -> {
                    clCookTime.upSelectedView(true)
                }
                CookSettingType.SPEED_SETTING -> {
                    clCookSpeed.upSelectedView(true)
                }
                CookSettingType.DIRECTION_SETTING -> {
                    clCookDirection.upSelectedView(true)
                }
                CookSettingType.WATER_SPRY -> {
                    clCookWater.upSelectedView(true)
                }
                CookSettingType.WEIGHT -> {
                    // do nothing
                }
                CookSettingType.TURBO -> {

                }
            }
        }
    }

    /**旋转按钮切换时间*/
    private fun handleRotateTimeChange(c: Int) {
        ThreadUtils.runOnMainThread {
            //当前调节时间
            var targetTime = currDevInfo.targetTime
            if (currDevInfo.remainTime != 0) {
                targetTime = currDevInfo.remainTime
            }
            if (currDevInfo.targetTimeBuffer != -1) {
                targetTime = currDevInfo.targetTimeBuffer
            }
            targetTime += c
            if (targetTime < 0) {
                targetTime = 0;
            }
            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}"
                }
            }
            rollTimeEvent(hour, min, sec, time, setByUser = true)
            currDevInfo.apply {
                updateTimeUI(
                    mode.minTime,
                    mode.maxTime,
                    remainTime,
                    targetTime.toLong(),
                    true
                )
            }
            binding.clSetTime.setTimeInternal(
                hour,
                min,
                sec,
                changeSetting = true,
                setByUser = true
            )
        }
    }

    /**旋转按钮步进*/
    private fun rotateStep(): Int {
        if (currDevInfo.targetTime >= 60) {
            return 10;
        }
        if (currDevInfo.targetTime >= 10 * 60) {
            return 30;
        }
        return 1
    }

    /**
     * 更新温度相关的UI
     * @param minTemp 最小温度
     * @param maxTemp 最大温度
     * @param currentTemp 当前温度（或默认温度）
     * @param targetTemp 设置的目标温度
     * @param isTempChange 温度是否可以改变
     */
    @SuppressLint("SetTextI18n")
    private fun updateTempUI(
        minTemp: Float,
        maxTemp: Float,
        currentTemp: Int,
        targetTemp: String,
        isTempChange: Boolean,
        focusUpdate: Boolean = false
    ) {
        this.maxTemp = maxTemp.toInt()
        this.minTemp = minTemp.toInt()
        this.isTempChange = isTempChange
        binding.apply {
            clCookTemp.updateChangeValue("${FoodSdkUtils.parseTemp(currDevInfo.temp)}°C")
            tempRingView.setRange(minTemp, maxTemp)
            tempRingView.setCanTouch(isTempChange)
            if (!userChanging || focusUpdate) {
                clCookTemp.setConfigValue("--${FoodSdkUtils.parseTemp(targetTemp.toShort())}°C--")
                tempRingView.updateProgress(FoodSdkUtils.parseTemp(currentTemp.toShort()).toInt())
                tempRingText.text = ("${FoodSdkUtils.parseTemp(currentTemp.toShort()).toInt()}°C")
            }

        }
    }

    /**
     * 更新时间相关的UI
     * @param minTime 最小时间
     * @param maxTime 最大时间
     * @param remainTime 剩余时间（或默认时间）
     * @param targetTime 设置的目标时间
     * @param isTimeChange 时间是否可以修复
     */
    private fun updateTimeUI(
        minTime: Int,
        maxTime: Int,
        remainTime: Int,
        targetTime: Long,
        isTimeChange: Boolean,
        focusUpdate: Boolean = false,
    ) {
        this.isTimeChange = isTimeChange
        this.maxTime = maxTime.toLong()
        this.minTime = minTime.toLong()
        binding.apply {
            clCookTime.updateChangeValue(getTimeStr(currDevInfo.remainTime.toLong()))
            var hours = 0
            var minute = 0
            var sec = 0
            if (remainTime > 3600) {
                hours = remainTime / 3600
                minute = remainTime % 3600 / 60
            } else {
                minute = remainTime / 60
                sec = remainTime % 60
            }
            clSetTime.isTimeCanChange(isTimeChange)
            clSetTime.setTimeRange(minTime, maxTime)
            if (!userChanging || focusUpdate) {
                clCookTime.setConfigValue("--${getTimeStr(targetTime)}--")
                clSetTime.setTimeInternal(hours, minute, sec, true)
                clSetTime.setTargetTime("--${getTimeStr(targetTime)}--")
            }
        }
    }

    /**
     * 更新电机方向的UI
     * @param motorDirection 电机方向
     * @param isMotorDirectionChange 方向是否可以修改
     */
    private fun updateMotorDirectionUI(motorDirection: Int, isMotorDirectionChange: Boolean) {
        binding.apply {
            flDirection.isCanChangeDirection(isMotorDirectionChange)
            if (!userChanging) {
                clCookDirection.updateChangeValue(
                    viewModel.getDirectionStr(
                        motorDirection == MotorDirections.REVERSE.toInt(), resources
                    )
                )
                flDirection.updateDirectionView(
                    if (motorDirection == MotorDirections.FORWARD.toInt()) DirectionView.Direction.RIGHT
                    else DirectionView.Direction.LEFT
                )
            }
            if (mRunningState == DevStatus.RUNNING.toInt() && currDevInfo.motorGear > 0) {
                viewModel.playRotateAnimator(
                    motorDirection, binding.clCookDirection.binding.viewIcon
                )
            } else {
                viewModel.pauseRotateAnimator(binding.clCookDirection.binding.viewIcon)
            }
        }
    }

    /**
     * 更新电机转速的UI
     * @param minMotorGear 电机最小转速
     * @param maxMotorGear 电机最大转速
     * @param currentMotorGer 电机当前转速
     * @param isMotorGearChange 转速是否可以修改
     */
    private fun updateMotorGearUI(
        minMotorGear: Float, maxMotorGear: Float, currentMotorGer: Int, isMotorGearChange: Boolean,focusUpdate: Boolean = false
    ) {

        if(CofarSDK.devInfo().devMode != DevModes.SOUP){
            return
        }

        this.minMotorGear = minMotorGear.toInt()
        this.maxMotorGear = maxMotorGear.toInt()
        this.isMotorGearChange = isMotorGearChange
        binding.apply {
            clCookSpeed.updateChangeValue(currentMotorGer.toString())
            speedRingView.setRange(minMotorGear, maxMotorGear)
            speedRingView.setCanTouch(isMotorGearChange)
            if (!userChanging || focusUpdate) {
                speedRingView.updateProgress(currentMotorGer)
                speedRingText.text = currentMotorGer.toString()
            }
        }
    }


    /**
     * 更新喷水档位的UI
     * @param minWaterGear 最小转速
     * @param maxWaterGear 电机最大转速
     * @param currentMotorGer 电机当前转速
     * @param isWaterGearChange 转速是否可以修改
     */
    private fun updateWaterGearUI(
        minWaterGear: Float, maxWaterGear: Float, currentMotorGer: Int, isWaterGearChange: Boolean,focusUpdate: Boolean = false
    ) {

        if(CofarSDK.devInfo().devMode != DevModes.AIR_FRYER){
             return
        }

        this.minWaterGear = minWaterGear.toInt()
        this.maxWaterGear = maxWaterGear.toInt()
        this.isWaterGearChange = isWaterGearChange

        binding.apply {
            clCookSpeed.updateChangeValue(currentMotorGer.toString())
            waterRingView.setRange(minWaterGear, maxWaterGear)
            waterRingView.setCanTouch(isWaterGearChange)
            waterSprayShow.updateGear(currentMotorGer)
            binding.clCookWater.binding.waterSprayShow.updateGear(currentWaterGear)
            if (!userChanging) {
                waterRingView.updateProgress(currentMotorGer)
            }
        }
    }


    /**
     * 更新电机转速的UI
     * @param weight 当前的重量
     */
    @SuppressLint("SetTextI18n")
    private fun updateWeightUI(weight: Float) {
        binding.tvWeightNum.text = "${weight}g"
        binding.weightView.setWeightNumber(weight)
    }

    /**
     * 更新各种状态的按钮
     * @param status 设备运行状态
     */
    private fun updateStatusBtn(status: Byte) {
        //当前用户正在修改不更新按钮状态
        if (userChanging) return
        //切碎功能隐藏按钮
        if (viewModel.modeType == ModesType.TURBO.name) {
            binding.apply {
                btnStart.visibility = View.GONE
                btnResume.visibility = View.GONE
                btnPause.visibility = View.GONE
                btnStop.visibility = View.GONE
                btnCancel.visibility = View.GONE
                btnConfirm.visibility = View.GONE
            }
            return
        }

        if (viewModel.modeType == ModesType.WIGHT.name) {
            binding.apply {
                btnStart.visibility = View.GONE
                btnResume.visibility = View.GONE
                btnPause.visibility = View.GONE
                btnStop.visibility = View.GONE
                btnCancel.visibility = View.GONE
                btnConfirm.visibility = View.GONE
            }
            return
        }

        when (status) {
            DevStatus.RUNNING -> {
                binding.apply {
                    ivWeight.visibility = View.GONE
                    ivTurbo.visibility = View.GONE
                    btnStart.visibility = View.INVISIBLE
                    btnStop.visibility = View.VISIBLE
                    btnResume.visibility = View.INVISIBLE
                    btnPause.visibility = View.VISIBLE
                    btnReset.visibility = View.INVISIBLE
                }
            }

            DevStatus.PAUSE -> {
                binding.apply {
                    ivWeight.visibility = View.VISIBLE
                    ivTurbo.visibility = View.GONE
                    btnStart.visibility = View.INVISIBLE
                    btnResume.visibility = View.VISIBLE
                    btnPause.visibility = View.INVISIBLE
                    btnStop.visibility = View.VISIBLE
                    btnCancel.visibility = View.INVISIBLE
                    btnConfirm.visibility = View.INVISIBLE
                    btnReset.visibility = View.INVISIBLE
                }
            }

            DevStatus.STOP -> {
                binding.apply {
                    ivWeight.visibility = View.VISIBLE
                    ivTurbo.visibility = View.VISIBLE
                    btnStop.visibility = View.INVISIBLE
                    btnStart.visibility = View.VISIBLE
                    btnPause.visibility = View.INVISIBLE
                    btnResume.visibility = View.INVISIBLE
                    btnCancel.visibility = View.INVISIBLE
                    btnConfirm.visibility = View.INVISIBLE
                    btnReset.visibility = View.VISIBLE
                }

            }
        }

        turnDevModeUI()
    }

    /**
     * 显示/隐藏 确认取消按钮
     */
    private fun showConfirmAndCancelBtn() {
        if (currDevInfo.status.toByte() != DevStatus.STOP) {
            binding.btnCancel.visibility = View.VISIBLE
            binding.btnConfirm.visibility = View.VISIBLE
            binding.btnStop.visibility = View.GONE
            binding.btnPause.visibility = View.GONE
            binding.btnResume.visibility = View.GONE
        }
    }


    //============================================================操作事件的响应方法=================================================\\

    /**
     * 点击开始操作
     */
    private fun startClick() {
        if (mRunningInstId != mSettingInstId) {
            overrideModeDialog.showDialog(supportFragmentManager, "overrideModeDialog")
        } else {
            userChanging = false
            CofarSDK.cancel()
            CofarSDK.devInfo().runningRecipeId = null
            CofarSDK.start(viewModel.modeType)
        }
    }

    /**
     * 点击恢复操作
     */
    private fun resumeClick() {
        userChanging = false
        CofarSDK.resume()
    }

    /**
     * 点击取消操作
     */
    private fun cancelClick() {
        //取消
        userChanging = false
        CofarSDK.cancel()
        binding.btnCancel.visibility = View.GONE
        binding.btnConfirm.visibility = View.GONE
    }

    /**
     * 点击确认操作
     */
    private fun confirmClick() {
        //确认
        userChanging = false
        //配置
        CofarSDK.confirm()
        binding.btnCancel.visibility = View.GONE
        binding.btnConfirm.visibility = View.GONE
    }

    private fun resetConfigClick() {
        //确认
        userChanging = false
        initModeData(modeType)
    }

    /**
     * 点击停止操作
     */
    private fun stopClick() {
        userChanging = false
        //结束
        CofarSDK.stop()
        try {
            FloatWindowManager.hideStepFlowWindow()
        } catch (e: Exception) {
            print(e)
        }
    }

    /**
     * 点击暂停操作
     */
    private fun pauseClick() {
        userChanging = false
        CofarSDK.pause()
    }

    /**
     * 点击称重操作
     */
    private fun weightClick() {
//        CofarSDK.stop(false)
        modeChange = true
        viewModel.modeType = ModesType.WIGHT.name
        initModeData(viewModel.modeType)
        viewModel.changeStep(CookSettingType.WEIGHT)
        binding.ivTurbo.visibility = View.GONE
        binding.ivWeight.visibility = View.GONE
        binding.tvModeName.text = viewModel.getModeTitle(resources)
        binding.ivBanner.setBackgroundResource(viewModel.getBanner())
    }

    /**
     * 点击turbo操作
     */
    private fun turboClick() {
        CofarSDK.stop(false)
        modeChange = true
        viewModel.modeType = ModesType.TURBO.name
        initModeData(viewModel.modeType)
        viewModel.changeStep(CookSettingType.TURBO)
        binding.tvModeName.text = viewModel.getModeTitle(resources)
        binding.ivTurbo.visibility = View.GONE
        binding.ivWeight.visibility = View.GONE
        binding.llTurboView.visibility = View.VISIBLE
        binding.ivBanner.setBackgroundResource(viewModel.getBanner())
    }

    /**
     * 点击称重清0操作
     */
    private fun weightClearClick() {
        //称重清0
        userChanging = false
        CofarSDK.clearWeight()
    }


    /**
     * 点击返回按钮操作
     */
    private fun backClick() {
        if (modeChange) {

            if(modeType == ModesType.TURBO.name){ //TURBO未停止之前不能退出
                CofarSDK.stop(false)
                if(DevStatus.STOP != CofarSDK.devInfo().status.toByte()){
                    return
                }

                //先注释掉，忘记有什么用了
//                turboLock = true
//                ThreadUtils.runOnMainThread({turboLock = false},2000);
            }
            var cm = viewModel.modeType;
            modeType = viewModel.lastModeType
            viewModel.modeType = viewModel.lastModeType
            binding.tvModeName.text = viewModel.getModeTitle(resources)
            binding.ivBanner.setBackgroundResource(viewModel.getBanner())
            modeChange = false
            binding.llTurboView.visibility = View.GONE
            initModeData(modeType,cm == ModesType.WIGHT.name || cm == ModesType.TURBO.name)
            changeCommonStep()
        } else if (mRunningState != 0 && viewModel.modeType != ModesType.WIGHT.name && viewModel.modeType != ModesType.TURBO.name) {
            if (CofarSDK.devInfo().runningInstId == viewModel.modeType) backRequestDialog.show(
                supportFragmentManager, "backRequestDialog"
            )
            else finish()
        } else {
            finish()
        }
    }


    /**
     * 旋转温度事件
     */
    private fun tempRingEvent(progress: Int) {
        userChanging = true
        binding.tempRingText.text = "${progress}°C"
        binding.clCookTemp.setConfigValue("--${progress}°C--")
        CofarSDK.cfgHeat(progress.toShort(), HeatModes.PU_TONG);
        showConfirmAndCancelBtn()
    }


    private fun waterGearSpeedEvent(progress: Int){
        userChanging = true
        CofarSDK.cfgWaterBear(progress);
        showConfirmAndCancelBtn()
    }

    /**
     * 旋转电机转速事件
     */
    private fun motorGearSpeedEvent(progress: Int) {
        userChanging = true
        binding.speedRingText.text = "$progress"
        CofarSDK.cfgMotorGear(progress.toByte());
        showConfirmAndCancelBtn()
    }

    /**
     * 点击电机方向事件
     */
    private fun motorGearDirectionClick(direction: DirectionView.Direction) {
        userChanging = true
        binding.clCookDirection.updateChangeValue(
            viewModel.getDirectionStr(
                direction == DirectionView.Direction.LEFT, resources
            )
        )
        if (direction != DirectionView.Direction.RIGHT) {
            CofarSDK.cfgMotorDirection(MotorDirections.REVERSE);
            updateMotorDirectionUI(MotorDirections.REVERSE.toInt(), true);


        } else {
            CofarSDK.cfgMotorDirection(MotorDirections.FORWARD);
            updateMotorDirectionUI(MotorDirections.FORWARD.toInt(), true);

        }

        showConfirmAndCancelBtn()
    }

    /**
     * 滑动时间事件
     */
    private fun rollTimeEvent(
        hours: Int, minute: Int, second: Int, time: String, setByUser: Boolean
    ) {
        if (setByUser) {
            userChanging = true
            binding.clCookTime.setConfigValue("--${time}--")
            CofarSDK.cfgTime((second + (minute + hours * 60) * 60))
            showConfirmAndCancelBtn()
        }
    }


    /**
     * turbo按下事件
     */
    private fun turboDownEvent() {
        binding.ivTurboView.setBackgroundResource(com.develop.common.R.drawable.ic_turbo)
        viewModel.startTurbo()
    }

    /**
     * turbo离开事件
     */
    private fun turboUpEvent() {
        binding.ivTurboView.setBackgroundResource(com.develop.common.R.drawable.ic_turbo_unselected)
        viewModel.stopTurbo()
    }
}