package com.develop.step.modes

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.develop.food.base.common.MODE_TYPE
import com.develop.food.base.common.PRESS_DOWN_KEY_CODE
import com.develop.food.base.common.TURN_DOWN_KEY_CODE
import com.develop.food.base.common.TURN_UP_KEY_CODE
import com.develop.food.base.data.ModesType
import com.develop.food.base.data.model.CookSettingType
import com.develop.food.base.event.CookStepEvent
import com.develop.food.base.manager.FloatWindowManager
import com.develop.food.base.router.Screens
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.utils.CofarUtils
import com.develop.food.base.utils.ThreadUtils
import com.develop.food.base.utils.timeStamp2Time
import com.develop.food.base.utils.toJson
import com.develop.food.base.widgets.CancelConfirmDialog
import com.develop.food.base.widgets.DirectionView
import com.develop.food.base.widgets.TimePickerView
import com.develop.step.BuildConfig
import com.develop.step.R
import com.develop.step.databinding.ActivityModeDetailBinding
import com.develop.step.viewmodel.CookModesViewModel
import com.develop.step.widgets.RingControlView
import com.kuyuntech.cofarcooking.device.sdk.constant.core.CommonEventTypes
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.devmode.core.Turbo
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.apache.commons.lang3.StringUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.*

@Route(path = Screens.Cook.COOK_MODES)
class ModesDetailActivity : BaseActivity<ActivityModeDetailBinding>() {
    private var modeType = ModesType.CHOP.name
    override fun createViewBinding(inflater: LayoutInflater): ActivityModeDetailBinding {
        return ActivityModeDetailBinding.inflate(layoutInflater)
    }

    private val viewModel by viewModels<CookModesViewModel>()
    private var userChanging = false //当前是否用户在操作
    private var currDevInfo = DevInfo()
    private var lastModeType = ModesType.CHOP.name
    private var modeChange = false
    private var turboTimer: Timer? = null
    private var mSettingInstId = ""
    private var mRunningInstId = ""
    private var mRunningState = 0
    private var currentTemp = 0
    private var currentMotorGer = 0
    private var maxTemp = 0
    private var minTemp = 0
    private var maxMotorGear = 0
    private var minMotorGear = 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 initModeData = false

    private val backRequestDialog by lazy {
        CancelConfirmDialog()
    }
    private val overrideModeDialog by lazy {
        CancelConfirmDialog()
    }
    private var rotateAnimator: ObjectAnimator? = null
    private var rotateAnimDir = -1

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

    @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.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.tempRingView.onRingViewListener = object : RingControlView.OnRingViewListener {
            override fun onProgressChange(progress: Int) {
                val pg = CofarUtils.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(modeType),
                        isMode = true,
                        modeName = 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(modeType),
                        isMode = true,
                        modeName = modeType
                    )
                    FloatWindowManager.showStepFlowWindow(cookStepEvent)
                    when (modeType) {
                        ModesType.WIGHT.name -> {
                            CofarSDK.stop(false)
                            CofarSDK.startWeight()
                        }
                        ModesType.TURBO.name -> {
                            CofarSDK.stop(false)
                        }
                        else -> {
                            userChanging = false
                            CofarSDK.startRunning(modeType)
                        }
                    }
                }

                override fun onCancel() {

                }
            }
        }

        binding.speedRingView.onRingViewListener = object : RingControlView.OnRingViewListener {
            override fun onProgressChange(progress: Int) {
                currentMotorGer = progress
                motorGearSpeedEvent(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.ivTurboView.setOnTouchListener { view, motionEvent ->
            when (motionEvent.action) {
                MotionEvent.ACTION_DOWN -> {
                    turboDownEvent()
                }
                MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    turboUpEvent()
                }
            }
            true
        }

    }

    private fun startTurbo() {
        turboTimer?.cancel()
        turboTimer = null
        turboTimer = Timer()
        turboTimer?.schedule(object : TimerTask() {
            override fun run() {
                CofarSDK.start(modeType)
                Log.d("ddddddd", "-----")
            }

        }, 0, 300)
    }

    private fun initData() {
        binding.tvModeName.text = viewModel.getModeTitle(resources, modeType)
        binding.ivBanner.setBackgroundResource(viewModel.getBanner(modeType))
        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.DIRECTION_SETTING -> {
                    changeDirectionSettingStep()
                }
            }
        }
    }

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

    private fun changeCommonStep() {
        binding.functionLayout.visibility = View.VISIBLE
        binding.llWeightView.visibility = View.GONE
        if (modeType == ModesType.WIGHT.name || modeType == ModesType.TURBO.name) {
            binding.ivWeight.visibility = View.GONE
            binding.ivTurbo.visibility = View.GONE
            if (modeType == ModesType.TURBO.name) {
                binding.ivTurboView.visibility = View.VISIBLE
            }
        } else {
            binding.ivWeight.visibility = View.VISIBLE
            binding.ivTurbo.visibility = View.VISIBLE
        }
        changeTempSettingStep()
    }

    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
        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
        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
        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
        setPanelViewProperty(CookSettingType.DIRECTION_SETTING)
    }

    private fun setPanelViewProperty(selectStep: CookSettingType) {
        binding.apply {
            clCookTemp.upSelectedView(false)
            clCookTime.upSelectedView(false)
            clCookSpeed.upSelectedView(false)
            clCookDirection.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.WEIGHT -> {
                    // do nothing
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        CofarSDK.stoptWeight()
//        EventBus.getDefault().unregister(this)
        turboTimer?.cancel()
        rotateAnimator?.cancel()
        hasShowScreenSaver = false
    }


    @Subscribe
    fun onDevCommonEvent(event:DevCommonEvent){


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

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



    }

    @Subscribe
    fun onDevStateEvent(event: DevStatusEvent) {
        if(!initModeData || turboLock){
            return
        }
        ThreadUtils.runOnMainThread {
            if (BuildConfig.DEBUG) {
                //Log.d("ddddddddd", event.devInfo.toJson())
            }
            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(
                    minTime,
                    maxTime,
                    if(currDevInfo.status == DevStatus.STOP.toInt()) currDevInfo.targetTime.toInt() else currDevInfo.remainTime.toInt(),
                    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
                )

                updateMotorDirectionUI(currDevInfo.motorDirection.toInt(), isMotorDirectionChange)

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




    //初始化模式数据
    @SuppressLint("SetTextI18n")
    private fun initModeData(type: String,keep:Boolean = false) {

        userChanging = false
        val baseMode = CofarSDK.devMode(type)
        //显示对应模式UI
        if (modeType == ModesType.WIGHT.name) {
            CofarSDK.recordConfig()
            //称重模式
            viewModel.changeStep(CookSettingType.WEIGHT)
//            CofarSDK.changeMode(baseMode)
        } else {
            //其他模式
           changeCommonStep()

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

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

                var restoreConfig:DevInfo ?= null

                if (modeType == ModesType.TURBO.name) {
                    CofarSDK.recordConfig()
                    CofarSDK.changeMode(baseMode)
                    changeSpeedSettingStep()
                } else {
                    turboLock=false;
                    viewModel.changeStep(CookSettingType.TEMP_SETTING)
                    if(keep){
                        restoreConfig = CofarSDK.changeMode(type, baseMode,true)

                        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 = CofarSDK.devInfo().temp.toInt()
                    updateTempUI(
                        minTemp.toFloat(),
                        maxTemp.toFloat(),
                        currentTemp,
                        targetTemp.toString(),
                        isTempChange,
                        true
                    )

                    currTime = defaultTime.toLong()
                    updateTimeUI(
                        minTime,
                        maxTime,
                        defaultTime,
                        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
    }


    private fun getDirectionStr(isLeft: Boolean): String {
        return if (isLeft) getString(
            R.string.turn_left
        ) else getString(R.string.turn_right)
    }

    private fun getTimeStr(time: Long): String {

        if(time >= 91*60){
            var h = time / 3600;
            var m = time % 3600 / 60;
            return "${if(h < 10) "0${h}" else h}:${if(m < 10) "0${m}" else m}";
        }else{

            var m = time / 60;
            var s = time % 60;

            return "${if(m < 10) "0${m}" else m}:${if(s < 10) "0${s}" else s}";

        }


//        val format = if (time >= 90 * 60) {
//            "HH:mm"
//        } else {
//            "mm:ss"
//        }
//        return timeStamp2Time(
//            time,
//            format
//        ) ?: ""
    }

    private fun playRotateAnimator(direction: Int) {
        if (rotateAnimator == null) {
            rotateAnimator = ObjectAnimator.ofFloat(
                binding.clCookDirection.binding.viewIcon, View.ROTATION, 0f, 360f
            ).apply {
                duration = 2000
                repeatCount = ObjectAnimator.INFINITE
                interpolator = LinearInterpolator()
            }
        }
        if (rotateAnimator!!.isRunning) {
            if (direction == rotateAnimDir) {
                return
            } else {
                rotateAnimator?.cancel()
            }
        }
        if (direction == MotorDirections.REVERSE.toInt()) {
            rotateAnimator?.reverse()
        } else {
            rotateAnimator?.start()
        }
        rotateAnimDir = direction
    }

    private fun pauseRotateAnimator() {
        rotateAnimator?.cancel()
        binding.clCookDirection.binding.viewIcon.rotation = 0f
    }

    private fun isHour(remainTime: Long): Boolean {
        return remainTime > 3600
    }


    private fun rotateStep(): Int {
        if(currDevInfo.targetTime >= 60){
            return  10;
        }

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

        return 1
    }




    /**
     * 旋转物理键
     */
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        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 = CofarUtils.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.TIME_SETTING -> {
                            if (isTimeChange){
                                //当前调节时间
                                //dealWithTimeByOperation(true)
                                handleRotateTimeChange(rotateStep())
                            }
                        }
                    }
                }
                //旋转-
                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 = CofarUtils.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.TIME_SETTING -> {
                            if (isTimeChange) {
                                //当前调节时间
                                //dealWithTimeByOperation(false)
                                handleRotateTimeChange(-rotateStep())
                            }
                        }
                    }
                }
            }
        }
        return super.dispatchKeyEvent(event)
    }

    private var timeBuffer = 0;



    /**
     * 旋转按钮切换时间
     */
    private fun handleRotateTimeChange(c:Int){

        ThreadUtils.runOnMainThread({
            //当前调节时间
            var targetTime = currDevInfo.targetTime.toInt()
            if(currDevInfo.remainTime.toInt() != 0){
                targetTime = currDevInfo.remainTime.toInt()
            }
            if(currDevInfo.targetTimeBuffer.toInt() != -1){
                targetTime = currDevInfo.targetTimeBuffer.toInt()
            }
            targetTime+=c


            if(targetTime < currDevInfo.mode.minTime){ //处理边界
                targetTime = currDevInfo.mode.minTime
            }

            if( targetTime > currDevInfo.mode.maxTime){ //处理边界
                targetTime = currDevInfo.mode.maxTime
            }

            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.toInt(),targetTime.toLong(),true)
                binding.apply {
                    clSetTime.setTimeInternal(hour,min,sec,true,true)
                }

            }
        })


    }



    private var pressStartTime = -1L;


    private var canStart = true;

    /**
     * 物理键按下事件
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == PRESS_DOWN_KEY_CODE) {


            //当前是turbo模式下
            if (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( modeType == ModesType.WIGHT.name){
            backClick()
        }else{
            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 (modeType == ModesType.TURBO.name && event.keyCode == PRESS_DOWN_KEY_CODE) {
            //当前是turbo模式下,并且是物理键按下
            turboUpEvent()
            return false
        }

        pressStartTime = -1L



        if (modeType != ModesType.WIGHT.name && 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()
                }
            }
        }


        if(modeType == ModesType.WIGHT.name){
            weightClearClick();
        }

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

    //============================================================UI更新的方法=================================================\\
    /**
     * 更新温度相关的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("${CofarUtils.parseTemp(currDevInfo.temp)}°C")
            tempRingView.setRange(minTemp, maxTemp)
            tempRingView.setCanTouch(isTempChange)
            if (!userChanging || focusUpdate) {
                clCookTemp.setConfigValue("--${CofarUtils.parseTemp(targetTemp.toShort())}°C--")
                tempRingView.updateProgress(CofarUtils.parseTemp(currentTemp.toShort()).toInt())
                tempRingText.text = ("${CofarUtils.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 > ( 91 * 60)) {
                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(getDirectionStr(motorDirection == MotorDirections.REVERSE.toInt()))
                flDirection.updateDirectionView(
                    if (motorDirection == MotorDirections.FORWARD.toInt()) DirectionView.Direction.RIGHT
                    else DirectionView.Direction.LEFT
                )
            }
            if (mRunningState == DevStatus.RUNNING.toInt() && currDevInfo.motorGear > 0) {
                playRotateAnimator(motorDirection)
            } else {
                pauseRotateAnimator()
            }
        }
    }

    /**
     * 更新电机转速的UI
     * @param minMotorGear 电机最小转速
     * @param maxMotorGear 电机最大转速
     * @param currentMotorGer 电机当前转速
     * @param isMotorGearChange 转速是否可以修改
     */
    private fun updateMotorGearUI(
        minMotorGear: Float,
        maxMotorGear: Float,
        currentMotorGer: Int,
        isMotorGearChange: Boolean,
        focusUpdate: Boolean = false
    ) {
        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) {
                speedRingView.updateProgress(currentMotorGer)
                speedRingText.text = currentMotorGer.toString()
            }
        }
    }

    /**
     * 更新电机转速的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 (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 (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
                }
            }

            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.GONE
                    btnConfirm.visibility = View.GONE
                }
            }

            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.GONE
                    btnConfirm.visibility = View.GONE
                }

            }
        }
    }

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

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

    /**
     * 点击开始操作
     */
    private fun startClick() {
        if (mRunningInstId != mSettingInstId) {
            overrideModeDialog.showDialog(supportFragmentManager, "overrideModeDialog")
        } else {
            userChanging = false
            CofarSDK.cancel()
            CofarSDK.devInfo().runningRecipeId = null
            CofarSDK.start(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 stopClick() {
        userChanging = false
        //结束
        CofarSDK.stop()
        //TODO 崩溃？
        try {
            FloatWindowManager.hideStepFlowWindow()
        }catch (e:Exception) {
            print(e)
        }
    }

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

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

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

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


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

        val devInfo = CofarSDK.devInfo();



        if (modeChange) {

            if(modeType == ModesType.TURBO.name){
                CofarSDK.stop(false)
                //先注释掉，忘记有什么用了
//                turboLock = true
//                ThreadUtils.runOnMainThread({turboLock = false},2000);
            }
            var cm = modeType;
            modeType = lastModeType
            binding.tvModeName.text = viewModel.getModeTitle(resources, modeType)
            binding.ivBanner.setBackgroundResource(viewModel.getBanner(modeType))
            modeChange = false
            binding.ivTurboView.visibility = View.GONE
            initModeData(modeType,cm == ModesType.WIGHT.name || cm == ModesType.TURBO.name)
            changeCommonStep()
        } else if (devInfo.status != DevStatus.STOP.toInt() && modeType != ModesType.WIGHT.name
            && modeType != ModesType.TURBO.name
        ) {
           if(CofarSDK.devInfo().runningInstId == modeType) backRequestDialog.showDialog(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 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(
            getDirectionStr(direction == DirectionView.Direction.LEFT)
        )
        if (direction != DirectionView.Direction.RIGHT) {
            CofarSDK.cfgMotorDirection(MotorDirections.REVERSE);

        } else {
            CofarSDK.cfgMotorDirection(MotorDirections.FORWARD);
        }
        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).toInt())
            showConfirmAndCancelBtn()
        }
    }

    var turboLock = false;

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

    /**
     * turbo离开事件
     */
    private fun turboUpEvent() {
        binding.ivTurboView.setBackgroundResource(R.drawable.ic_turbo_unselected)
        turboTimer?.cancel()
        turboTimer = null


    }
}