package com.quyunshuo.module.home.fragment.makefragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import coil.request.ImageRequest
import com.hboxs.serialport.sbc.VBoxMessage
import com.hboxs.serialport.sbc.frame.VboxCommand
import com.quyunshuo.androidbaseframemvvm.base.utils.CoilGIFImageLoader
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.common.bean.ShoppingCartBean
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.LogUtil
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.databinding.FragmentProdutionProcessBinding
import com.quyunshuo.module.home.fragment.makefragment.utlis.OrderManagement
import com.quyunshuo.module.home.fragment.vm.ProdutionProcessFragmentVM
import com.quyunshuo.module.home.utils.SingleShotLock
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 首页Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@RegisterEventBus
@AndroidEntryPoint
class RetrieveStatusFragment :
    BaseFragment<FragmentProdutionProcessBinding, ProdutionProcessFragmentVM>() {

    var makeList: MutableList<ShoppingCartBean>? = null
    override val mViewModel: ProdutionProcessFragmentVM by viewModels()
    override fun createVB() = FragmentProdutionProcessBinding.inflate(layoutInflater)
    var singleShotLock = SingleShotLock()
    var payType = ""

    override fun FragmentProdutionProcessBinding.initView() {
        //处理传递过来的商品数据，进行制作、数据保存
                val request = context?.let {
                    ImageRequest.Builder(it)
                        .data(R.drawable.qutang) // 替换为你的G图像路径
                        .target(mBinding.processgif)
                        .build()
                }

                request?.let { CoilGIFImageLoader.imageLoader.enqueue(it) }
        // val selectPro = arguments?.getString("SELECT_PRO")
        payType = arguments?.getString("payType", "")!!;
        /*     val arrayList: ArrayList<ShoppingCartBean> = Gson().fromJson(
                 selectPro,
                 object : TypeToken<ArrayList<ShoppingCartBean?>?>() {}.type
             )*/
        makeList = splitProductsByCount(OrderManagement.getInstance().remainingOrders)
        //  nextProduct()
    }

    fun splitProductsByCount(originalList: List<ShoppingCartBean>): MutableList<ShoppingCartBean> {
        val resultList: MutableList<ShoppingCartBean> = ArrayList<ShoppingCartBean>()
        for (product in originalList) {
            val count: Int = product.count
            if (count <= 0) continue  // 跳过无效count
            // 根据count生成新对象
            for (i in 0 until count) {
                val newItem: ShoppingCartBean = ShoppingCartBean(
                    product.productId,
                    product.productNo,
                    product.price,
                    product.nameId,
                    product.imgID,
                    product.nameChinese,
                    product.index,
                    1
                )
                resultList.add(newItem)
            }
        }

        return resultList
    }

    fun nextProduct() {
        singleShotLock.tryExecute {
            makeList?.let {
                if (it.size > 0) {
                    mViewModel.startSendm231(it.get(0).productId, it.size)
                }
            }
        }

    }

    override fun initObserve() {

        // lifecycle.addObserver(myHandler)

    }


    override fun initRequestData() {


    }

    override fun onDestroy() {
        super.onDestroy()

    }

    override fun onDestroyView() {

        super.onDestroyView()

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(messageEvent: VBoxMessage) {
        when (messageEvent.cmd) {
            VboxCommand.CMD_HEARTBEAT -> {
                Log.e("backinfo", "心跳包数据：" + messageEvent.data)
                var state = messageEvent.data.substring(0, 2)
                var loading = messageEvent.data.substring(2, 4)
                var operate =
                    com.quyunshuo.androidbaseframemvvm.base.utils.commons.StringUtils.parseInt(state)
                var progress =
                    com.quyunshuo.androidbaseframemvvm.base.utils.commons.StringUtils.parseInt(
                        loading
                    )
                LogUtil.d("backinfo", "operate:" + operate)
                when (operate) {
                    24 -> {
                        val findNavController = findNavController()
                        var bundle = Bundle()
                        bundle.putString("payType", payType)
                        findNavController.navigate(
                            R.id.home_action_home_makefragment_to_produtionprocess,
                            bundle
                        )
                        XLogUtil.d("开始制作下一个商品：")
                    }

                    23 -> {
                        XLogUtil.d("用户操作进度：" + progress)
                        setTipText(progress)
                    }

                    11 -> {
                        XLogUtil.d("制作完成所有：")
                        val findNavController = findNavController()
                        findNavController.navigate(
                            R.id.home_action_home_makefragment_to_home_homefragment,
                        )
                    }

                }
            }

            VboxCommand.CMD_MAKE -> {
                Log.d("backinfo", "关闭发送制作")
                mViewModel.stopM231()

            }
        }
        // globalServiceViewModel.disposeData(messageEvent)
    }

    fun setTipText(progress: Int) {
        lifecycleScope.launch(Dispatchers.Main) {
            if (progress == 1) {
                mBinding.tipInfo.setText(UiUtil.getStringRes(R.string.base_make_complete_1))
            } else if (progress == 2) {
                mBinding.tipInfo.setText(UiUtil.getStringRes(R.string.base_make_complete_2))

            } else if (progress == 3) {
                mBinding.tipInfo.setText(UiUtil.getStringRes(R.string.base_make_complete_3))

            }
        }


    }

}