package com.quyunshuo.module.home.service

import android.os.Message
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.google.gson.Gson
import com.hboxs.serialport.sbc.SBCHeartbeat
import com.quyunshuo.androidbaseframemvvm.base.utils.commons.StringUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.bean.Dosugar
import com.quyunshuo.module.home.utils.OrderManage
import com.quyunshuo.module.home.utils.RemotePushUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject


class MqServiceViewModel @Inject constructor(
    private val mRepo: MqServiceRepository,
) : LifecycleOwner {

    @Inject
    lateinit var remotePushUtil: RemotePushUtil

    private val TAG = "MqServiceViewModel"

    private val mLifecycleRegistry = LifecycleRegistry(this)
    override val lifecycle: Lifecycle
        get() = mLifecycleRegistry

    /**
     * 创建队列
     */
    fun getAddQueue() {
        CoroutineScope(Dispatchers.IO).launch {
            mRepo.getAddQueue().catch {
                Log.d(TAG, "getAddQueue catch: ${it.message}")
            }.collect {
                Log.d(TAG, "getAddQueue collect: $it")
            }

        }

    }

    /**
     * 远程制作棉花糖
     * */
    fun makingmarshmallows(kindData: String) {
        val gson = Gson()
        XLogUtil.d("kindData1:$kindData")
        var dosugar = Gson().fromJson(kindData, Dosugar::class.java)
        if (dosugar == null) {
            return
        }
        XLogUtil.d("kindData2:$kindData")

        //上传状态
        val params = HashMap<String, Any>()

        Heartbeat.deviceId?.let {
            params["clientId"] = Heartbeat.deviceId!!
        }
        params["no"] = dosugar.no
        if (StringUtils.isNullOrEmpty(canMaking())) {
            params.put("status", "1")
            updateSugarDoStatus(params, dosugar.productName)
        } else {
            params.put("status", "2")
            params.put("note", canMaking())
            updateSugarDoStatus(params, "")
        }

    }

    fun updateSugarDoStatus(params: HashMap<String, Any>, productNo: String) {
        val status: String = params.get("status").toString()
        val isStatus = "1" == status //如果等于1，说明是可以做棉花糖
        CoroutineScope(Dispatchers.IO).launch {
            mRepo.updateSugarDoStatus(params).catch {

            }.collect {
                if (isStatus && StringUtils.isNotNullOrEmpty(productNo)) {
                    if ("success" == it) {
                        writeFlowerType(productNo)
                    } else {
                        ToastUtil.showToast(UiUtil.getStringRes(R.string.base_red_sugar))
                    }
                }
            }
        }

    }

    fun writeFlowerType(productNo: String) {
        OrderManage.getInstance().getProductsByNo(productNo)
    }

    fun canMaking(): String {
        if (SBCHeartbeat.devCode.equals("OB01")) {
            return "";
        } else {
            var openState = SBCHeartbeat.isPowerOn
            if (!openState) {
                return "设备关机"
            } else if (!SBCHeartbeat.fatalError.equals("0000") || !SBCHeartbeat.nonFatalError.equals(
                    "0000"
                )
            ) {
                return "设备异常报警"
            } else if (SBCHeartbeat.devCode.startsWith("21") || SBCHeartbeat.devCode.startsWith(
                    "22"
                ) || SBCHeartbeat.devCode.startsWith(
                    "23"
                )
            ) {
                return "设备正在准备中，请稍后再远程操作"
            } else {
                return "未定义状态，请联系技术人员"
            }
        }
    }

    /**
     * 切换通道
     */
    fun getChannel() {
        CoroutineScope(Dispatchers.IO).launch {
            mRepo.getChannel().catch {
                Log.d(TAG, "getChannel catch: ${it.message}")
            }.collect {
                Log.d(TAG, "getChannel collect: $it")
            }

        }
    }


    fun updateEqeStatus() {
        var status = 0
        if (SBCHeartbeat.isPowerOn) {
            status = 1
        }

        CoroutineScope(Dispatchers.IO).launch {
            mRepo.updateEqeStatus(status).catch {

            }.collect {

            }

        }
    }

    fun getMQTTMessage(msg: String) {
        Log.d("backinfo","getMQTTMessage:"+msg)
        remotePushUtil.getMqttMessage(msg)
    }

    fun getMtMessage(msg: Message) {
        remotePushUtil.getMessage(msg)

    }
}