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

import android.net.TrafficStats
import android.text.format.DateFormat
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
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.hboxs.serialport.plc.util.HexadecimalUtil
import com.hboxs.serialport.sbc.SBCHeartbeat
import com.module.database.room.SZDatabase
import com.module.database.room.entity.LocalOrderBean
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PlcHomeAddressEnum
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.ProductDataBean
import com.quyunshuo.androidbaseframemvvm.common.bean.ShoppingCartBean
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
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.fragment.repo.HomeFragmentRepo
import com.quyunshuo.module.home.interfaces.IShoppingTrolley
import com.quyunshuo.module.home.utils.DeviceOperateManager
import com.quyunshuo.module.home.utils.UploadWorker
import dagger.hilt.android.lifecycle.HiltViewModel
import java.math.BigDecimal
import javax.inject.Inject

/**
 * HomeFragment 的 VM 层
 *
 * @author Qu Yunshuo
 * @since 2021/8/5 11:11 下午
 */
@HiltViewModel
class HomeFragmentVM @Inject constructor(private val mRepo: HomeFragmentRepo) : BaseViewModel(),
    IShoppingTrolley {

    private val TAG = "HomeFragmentVM"
    private val _D170Value = MutableLiveData<String>()
    val D170Value: LiveData<String> get() = _D170Value
    private val _D2Value = MutableLiveData<String>()
    val D2Value: LiveData<String> get() = _D2Value
    private var shoppingCartList = ArrayList<ShoppingCartBean>()//购物车 商品list

    private val _shoppingCarSize = MutableLiveData<Int>()
    val shoppingCarSize: LiveData<Int> get() = _shoppingCarSize
    private val _shoppingCarSumPrice = MutableLiveData<Double>()
    val shoppingCarSumPrice: LiveData<Double> get() = _shoppingCarSumPrice
    private val localOrderDao = SZDatabase.getDatabase(BaseApplication.context).getLocalOrderDao()

    fun getPriceData(): ArrayList<ProductDataBean> {
        val arrayList = ArrayList<ProductDataBean>()

        val priceData = mRepo.getPriceData()
        priceData.forEach {
            if (it.isSelected) {
                arrayList.add(it)
            }
        }

        return arrayList
    }

    private var rxtxTotal: Long = 0
    fun getSpeed(): Double {
        val tempSum = (TrafficStats.getTotalRxBytes()

                + TrafficStats.getTotalTxBytes())

        val rxtxLast: Long = tempSum - rxtxTotal

        val totalSpeed = rxtxLast * 1000 / 2000.0

        rxtxTotal = tempSum

        return totalSpeed
    }


    suspend fun addLocalOrder(sn: String, price: Double, payType: String, name: String) {
        val sysTime = System.currentTimeMillis() //获取系统时间
        val sysTimeStr = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime) //时间显示格式
        UploadWorker.getInstance().addNewOrder(
            LocalOrderBean(
                price = price,
                payType = payType,
                sn = sn,
                time = sysTimeStr.toString(),
                name = name
            )
        )

    }

    /**
     * 获取 banner 数据
     */
    suspend fun getBanners() {
        mRepo.saveBill()
    }

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

    }

    fun ack(messageEvent: Message) {

    }

    fun response(messageEvent: Message) {

        val name = messageEvent.name
        val responseFrame = messageEvent.content as ResponseFrame
        val result = AsciiUtils.asciiByteArray2HexStr(responseFrame.data)
        val results = HexadecimalUtil.flipString(result)
        when (name) {
            PlcHomeAddressEnum.D170.address -> {
                //通知数据更新
                D170(results)
            }

            PlcHomeAddressEnum.D2.address -> {
                val data = HexadecimalUtil.hex2dec(
                    HexadecimalUtil.flipString(
                        AsciiUtils.asciiByteArray2HexStr(responseFrame.data)
                    )[0]
                ).toString()
                Log.d(TAG, "response: " + data)
                _D2Value.value = data

            }

            else -> {}
        }
    }

    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()
        var integer = s.toInt()
        Log.d(TAG, "getRealData: " + integer)
        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 deviceStatusCheck(): String? {
        return DeviceOperateManager.instance?.CanOperateMake()
    }

    override fun shoppingTrolleyAdd(productDataBean: ProductDataBean): Boolean {
        //添加之前，先确认发是否超过的指定的数据。
        val shoppingCartsize = SpUtils.getString(MMKVName.SHOPPING_CART_SIZE, "5")?.toInt()
        if (shoppingTrolleySumCount() > shoppingCartsize!! - 1) {
            ToastUtil.switchToastStyleToWarn("购物车数量已满")
            return false
        }
        //添加到购物车的时候，先看看以前有没有。如果有，是数量+1
        var existingItem: ShoppingCartBean? =
            shoppingCartList.find { it.productNo == productDataBean.productNo }
        if (existingItem != null) {
            // 如果已存在，更新数量
            existingItem.count += 1
        } else {
            // 如果不存在，添加新项
            val newItem = ShoppingCartBean(
                productDataBean.productId,
                productDataBean.productNo,
                productDataBean.price,
                productDataBean.nameId,
                productDataBean.imgID,
                productDataBean.nameChinese,
                productDataBean.index,
                1
            )
            shoppingCartList.add(newItem)
        }
        shoppingTrolleySumCount()
        shoppingTrolleySumPrice()
        return true
    }

    override fun shoppingTrolleyRemove(position: Int) {
        if (position == -1 || position > shoppingCartList.size) {
            return
        }
        shoppingCartList.removeAt(position)
        shoppingTrolleySumCount()
        shoppingTrolleySumPrice()
    }

    override fun shoppingTrolleyRemoveAll() {
        shoppingCartList.clear()
        shoppingTrolleySumCount()
        shoppingTrolleySumPrice()
    }

    override fun shoppingTrolleySumPrice(): Double {
        //是否为有开启折扣
        if (SpUtils.getBoolean(MMKVName.DISCOUNT_FUNCTION, false) == true) {
            return shoppingTrolleyDiscountSumPrice();
        }

        var sumPrice = 0.0
        shoppingCartList.forEach {
            sumPrice += it.price * it.count
        }
        _shoppingCarSumPrice.value = sumPrice
        return sumPrice
    }

    override fun shoppingTrolleySumCount(): Int {
        var count = 0
        shoppingCartList.forEach {
            count += it.count
        }
        _shoppingCarSize.value = count
        return count
    }

    override fun shoppingTrolleyDiscountSumPrice(): Double {
        val twoPieceDiscount = SpUtils.getString(MMKVName.TWO_PRICE_DISCOUNT, "10")
        val threePieceDiscount = SpUtils.getString(MMKVName.THREE_PRICE_DISCOUNT, "10")
        val fivePieceDiscount = SpUtils.getString(MMKVName.FIVE_PRICE_DISCOUNT, "10")

        var sumPrice = BigDecimal("0")
        var shoppingCarNumber = 0
        shoppingCartList.forEach {
            for (i in 0 until it.count) {
                shoppingCarNumber++
                if (shoppingCarNumber == 2) {
                    sumPrice = sumPrice.add(
                        BigDecimal(it.price.toString()).multiply(
                            BigDecimal(twoPieceDiscount).divide(BigDecimal("10"))
                        )
                    )
                } else if (shoppingCarNumber == 3) {
                    sumPrice = sumPrice.add(
                        BigDecimal(it.price.toString()).multiply(
                            BigDecimal(threePieceDiscount).divide(BigDecimal("10"))
                        )
                    )
                } else if (shoppingCarNumber == 5) {
                    sumPrice = sumPrice.add(
                        BigDecimal(it.price.toString()).multiply(
                            BigDecimal(fivePieceDiscount).divide(BigDecimal("10"))
                        )
                    )
                } else {
                    sumPrice = sumPrice.add(BigDecimal(it.price.toString()))
                }
                XLogUtil.d("sumPrice1:$sumPrice:$shoppingCarNumber:$twoPieceDiscount")
            }
        }
        _shoppingCarSumPrice.value = sumPrice.toDouble()
        return sumPrice.toDouble()

    }

    override fun getShoppingTrolleyList(): List<ShoppingCartBean> {
        return shoppingCartList
    }

    override fun shoppingTrolleyUpdateCount(count: Int, position: Int): Boolean {
//        //添加之前，先确认发是否超过的指定的数据。
//        val shoppingCartsize = SpUtils.getString(MMKVName.SHOPPING_CART_SIZE, "5")?.toInt()
//        if (shoppingTrolleySumCount() > shoppingCartsize!! - 1) {
//            ToastUtil.switchToastStyleToWarn("购物车数量已满")
//            return false
//        }
        shoppingCartList[position].count = count
        shoppingTrolleySumCount()
        shoppingTrolleySumPrice()
        return true
    }

}