package com.quyunshuo.module.home.fragment.vm

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hboxs.serialport.plc.frame.ResponseFrame
import com.hboxs.serialport.plc.message.Message
import com.hboxs.serialport.plc.util.AdvacedUtil
import com.hboxs.serialport.plc.util.AsciiUtils
import com.quyunshuo.androidbaseframemvvm.common.util.ByteUtils
import com.hboxs.serialport.plc.util.HexUtils
import com.hboxs.serialport.plc.util.HexadecimalUtil
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PlcHomeAddressEnum
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.fragment.repo.MakeFragmentRepo
import com.hboxs.serialport.plc.thread.ThreadHomeParam
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * HomeFragment 的 VM 层
 *
 * @author Qu Yunshuo
 * @since 2021/8/5 11:11 下午
 */
@HiltViewModel
class MakeFragmentVM @Inject constructor(private val mRepo: MakeFragmentRepo) : BaseViewModel() {
    val threadHomeParam: ThreadHomeParam = ThreadHomeParam()
    private val _D2Value = MutableLiveData<String>()
    val D2Value: LiveData<String> get() = _D2Value
    private val TAG = "MakeFragmentVM"
    private val _D170Value = MutableLiveData<String>()
    val D170Value: LiveData<String> get() = _D170Value

    /**
     * 当前已获取的文章页码
     */
    private var mCurrArticlePage = 0


    /**
     * 文章列表数据加载 first:是否是加载更多、second:加载更多是否成功
     */
    val articleLoadLD = MutableLiveData<Pair<Boolean, Boolean>>()

    /**
     * 是否已经加载了全部
     */
    val isLoadAllLD = MutableLiveData<Boolean>()

    /**
     * 获取 banner 数据
     */
    fun getBanners() {

    }

    /**
     * 获取文章数据
     */
    fun getArticleData() {

    }


    fun startSendm231(selectPro: Int,number:Int) {
        threadHomeParam.startSetM231(selectPro,number)
    }
    fun stopM231() {
        threadHomeParam.stopSetM231()
    }
    fun test(p:String){
        threadHomeParam.testP(p)
    }

    fun response(messageEvent: Message) {
        val responseFrame = messageEvent.content as ResponseFrame
        val result = AsciiUtils.asciiByteArray2HexStr(responseFrame.data)
        val results = HexadecimalUtil.flipString(result)
        when (messageEvent.name) {
            PlcHomeAddressEnum.D2.address -> {
                val data = HexadecimalUtil.hex2dec(
                    HexadecimalUtil.flipString(
                        AsciiUtils.asciiByteArray2HexStr(responseFrame.data)
                    )[0]
                ).toString()
                _D2Value.value = data
            }

            PlcHomeAddressEnum.D170.address -> {
                //通知数据更新
                D170(results)
            }

            else -> {}
        }

    }


    /*  fun ack(messageEvent: Message) {
          when (messageEvent.name) {

              PlcHomeAddressEnum.D91.address -> {
                  Log.d(TAG, "stopSetD91 ack: ")
                  threadHomeParam.stopSetD91()
                  //开始置位M1
                  threadHomeParam.stopSetM1()
                  threadHomeParam.startSetM1()
                  viewModelScope.launch {
                      delay(1000)
                      threadHomeParam.stopRstM1()
                      threadHomeParam.startRstM1()
                  }
              }

              PlcHomeAddressEnum.M1.address -> {
                  threadHomeParam.stopSetM1()
                  Log.d(TAG, "结束 set M1")
              }

              PlcHomeAddressEnum.RM1.address -> {
                  threadHomeParam.stopRstM1()
                  Log.d(TAG, "结束 set rstM1")
              }
          }
      }*/

    private fun D170(results: ArrayList<String>) {

        _D170Value.value = getRealData(results, 0)

    }


    private fun getRealData(results: java.util.ArrayList<String>, index: Int): String {
        var realData = ""
        val s = HexadecimalUtil.hex2dec(results[index]).toString()
        val integer = s.toInt()
        val l = HexadecimalUtil.hex2dec(results[index])
        //2进制
        val s1 = Integer.toBinaryString(integer)
        if (s1.length < 16) {
            //正数
            realData = (HexadecimalUtil.hex2dec(results.get(0)) / 10.0).toString()
        } else {
            //负数
            realData = AdvacedUtil.getRealData(s1)
        }
        return realData
    }

    fun usePromotionCode(promotionCodes: String?) {
        if ("" == promotionCodes) {
            return
        }
        val promotionCodeArray = promotionCodes?.split(".")
        if (promotionCodeArray!!.isEmpty()) {
            return
        }
        viewModelScope.launch(Dispatchers.IO) {
            promotionCodeArray.forEach {
                if ("" != it) {
                    mRepo.updateProCodeState(it).catch { ij ->
                        Log.d(TAG, "usePromotionCode catch: " + ij.message)
                    }.collect { ia ->
                        Log.d(TAG, "usePromotionCode collect: $ia")

                    }
                }
            }
        }

    }
}