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

import android.os.Bundle
import android.os.Handler
import android.text.format.DateFormat
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.navigation.fragment.findNavController
import com.google.gson.Gson
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.plc.message.MakeMessage
import com.hboxs.serialport.sbc.VBoxMessage
import com.hboxs.serialport.sbc.frame.VboxCommand
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PlcD2StatusEnum
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.ShoppingCartBean
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MakeName
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.LogUtil
import com.quyunshuo.androidbaseframemvvm.common.util.LongClickUtils
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.databinding.HomeFragmentMakeBinding
import com.quyunshuo.module.home.dialog.AgainBuyDialog
import com.quyunshuo.module.home.enums.LogoEnum
import com.quyunshuo.module.home.fragment.makefragment.utlis.OrderManagement
import com.quyunshuo.module.home.fragment.vm.MakeFragmentVM
import com.quyunshuo.module.home.utils.SimplePlayerUtil
import com.quyunshuo.module.home.utils.SingleShotLock
import com.quyunshuo.module.home.weight.ProgressView
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.ref.WeakReference

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

    private val TAG = "MakeFragment"
    private var simplePlayerUtil: SimplePlayerUtil? = null

    private val myHandler: MyHandler = MyHandler(this@MakeFragment)
    var againBuyDialog: AgainBuyDialog? = null
    var isShowAgainBuyDialog = true//是否已经显示，如果已经显示，就不要弹出。
    override val mViewModel: MakeFragmentVM by viewModels()
    override fun createVB() = HomeFragmentMakeBinding.inflate(layoutInflater)
    var jobHandler: Job? = null
    var makeList: MutableList<ShoppingCartBean>? = null
    var index = 0
    var allowedMake = true
    var singleShotLock = SingleShotLock()
    var payType = ""
    private val lock = Any()
    override fun HomeFragmentMakeBinding.initView() {
        //处理传递过来的商品数据，进行制作、数据保存
        //   val selectPro = arguments?.getString("SELECT_PRO", "")
        payType = arguments?.getString("payType", "").toString()
        /* if (StringUtils.isNotNullOrEmpty(selectPro)) {
             val arrayList: ArrayList<ShoppingCartBean> = Gson().fromJson(
                 selectPro,
                 object : TypeToken<ArrayList<ShoppingCartBean?>?>() {}.type
             )
             makeList = splitProductsByCount(arrayList)
         }*/
        makeList = splitProductsByCount(OrderManagement.getInstance().remainingOrders)

        simplePlayerUtil = SimplePlayerUtil(svVideo)
        simplePlayerUtil!!.setUrl("/storage/emulated/0/adB/1440.mp4")



        Log.e("backinfo", "商品数据：" + Gson().toJson(makeList))
        initProgress()

        //首先判断是否有做糖数据，如果有则发送指令，如果没有就结束。
        LongClickUtils.setLongClick(Handler(), ivLogo, 5000, object : View.OnLongClickListener {
            override fun onLongClick(p0: View?): Boolean {
                val findNavController = findNavController()
                findNavController.navigate(R.id.home_action_home_makefragment_to_home_homefragment)

                return true
            }

        })
        //联系人
        ilContact.tvContact.text = SpUtils.getString(MMKVName.CONTACT, "name")
        ilContact.tvContactWay.text = SpUtils.getString(MMKVName.CONTACT_WAY, "123456")

        val logoIcon = SpUtils.getString(MMKVName.LOGO_TEXT, "1")
        val enumByValue = LogoEnum.getEnumByValue(logoIcon!!)
        val layoutParams = ivLogo.layoutParams
        enumByValue?.navId?.let { ivLogo.setImageResource(it) }
        enumByValue?.width?.let { layoutParams.width = it }
        enumByValue?.height?.let { layoutParams.height = it }
        mBinding.testsend.setOnClickListener {
            mViewModel.test(mBinding.testp.text.toString())
        }
    }


    override fun initObserve() {
        observeLiveData(mViewModel.D2Value, ::getD2Value)
        observeLiveData(mViewModel.D170Value, ::dataChange)
        lifecycle.addObserver(mViewModel.threadHomeParam)
        // lifecycle.addObserver(myHandler)

    }

    fun nextProduct() {
        singleShotLock.tryExecute {
            makeList?.let {
                if (it.size > 0) {
                    allowedMake = false
                    ToastUtil.switchToastStyleToWarn("制作$index")
                    mViewModel.startSendm231(it.get(0).productId, it.size)


                } else {
                    val findNavController = findNavController()
                    findNavController.navigate(R.id.home_action_home_makefragment_to_home_homefragment)
                }
            }
        }

    }

    private fun dataChange(value: String) {
        mBinding.tvFashengqi.text = "$value°C"
    }

    fun getD2Value(s: String) {
        when (s) {
            PlcD2StatusEnum.D2_2.address -> {
                if (isShowAgainBuyDialog) {
                    isShowAgainBuyDialog = false
                    showAgainBuyDialog()
                }
            }

            else -> {}
        }
    }

    override fun initRequestData() {
        /*       val promotionCodes = arguments?.getString("PROMOTION_CODE")
               mViewModel.getArticleData()
               //todo 优惠码处理
               mViewModel.usePromotionCode(promotionCodes)*/
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: ")
    }

    override fun onDestroyView() {
        simplePlayerUtil?.onDestroy()
        jobHandler?.cancel()
        Log.d(TAG, "onDestroyView: ")
        super.onDestroyView()

    }

    private var plannedSpeed: Float = 10f //进度
    private fun initProgress() {
//        ivCdrX = ivCdr.getTranslationX()
        // 添加叶子对象到控件
        val leaf1: ProgressView.Leaf = ProgressView.Leaf()
        // 设置叶子对象的属性，例如坐标等
        mBinding.progressView.addLeaf(leaf1)
        mBinding.progressView.maxProgress = 10f
        mBinding.progressView.setCurrentProgress(1f)
        jobHandler = CoroutineScope(Dispatchers.IO).launch {
            while (true) {
                myHandler.sendEmptyMessage(1)
                delay(1000)
            }
        }
    }

    internal class MyHandler(fragment: Fragment) : Handler(), LifecycleObserver {
        var mWeakReference: WeakReference<Fragment> = WeakReference(fragment)

        override fun handleMessage(msg: android.os.Message) {
            //as用来强转
            var fragment: MakeFragment = mWeakReference.get() as MakeFragment
            when (msg.what) {
                1 -> {
                    val sysTime = System.currentTimeMillis() //获取系统时间
                    val sysTimeStr = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime) //时间显示格式

                    //  fragment.plannedSpeed = 1f
                    // fragment.mBinding.progressView.setCurrentProgress(fragment.plannedSpeed)
                    fragment.mBinding.tvProgressDescribe.text =UiUtil.getStringRes(R.string.base_makeing)
                    fragment.mBinding.tvTime.text = sysTimeStr //更新时间


                }

                else -> {

                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun disconnectListener() {
            removeCallbacksAndMessages(null)
        }
    }

    @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) {
                    22 -> {//制作中
                        if (progress != 255) {
                            XLogUtil.d("制作进度：" + progress)
                            mBinding.progressView.setCurrentProgress(progress.toFloat())
                        }
                    }
                    23 -> {
                        XLogUtil.d("制作完成：" + progress)
                        val findNavController = findNavController()
                        var bundle = Bundle()
                        bundle.putString("payType", payType)
                        findNavController.navigate(
                            R.id.home_action_home_makefragment_to_retrieve_status_fragment,
                            bundle
                        )
                    }

                    /* 11 -> {
                         val findNavController = findNavController()
                         findNavController.navigate(
                             R.id.home_action_home_makefragment_to_home_homefragment,
                         )
                     }*/

                    /* 23 -> {
                         if (progress == 255) {//制作完成
                             allowedMake = true
                             if (makeList != null && makeList?.size!! >= 1) {
                                 makeList?.removeAt(0) //
                             }
                             singleShotLock.unlock()
                             if (makeList==null|| makeList?.size!! <=0){
                                 val findNavController = findNavController()
                                 findNavController.navigate(
                                     R.id.home_homefragment,
                                 )
                             }

                         }
                     }*/
                    /*11 -> {
                        if (progress == 1) {
                            nextProduct()
                        }
                    }*/
                }


            }

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

            }
        }
        // globalServiceViewModel.disposeData(messageEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(messageEvent: MakeMessage) {
        when (messageEvent.type) {
            MakeName.complete -> {

            }


        }
    }

    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
    }

    private fun showAgainBuyDialog() {
        if (againBuyDialog == null) {
            againBuyDialog = this@MakeFragment.context?.let { AgainBuyDialog(it) }
            againBuyDialog?.setListener(object : DialogClickListener {
                override fun onClickListener(type: Int, text: String?) {
                    when (type) {
                        againBuyDialog?.type1 -> {
                            againBuyDialog?.dismiss()
                            val findNavController = findNavController()
                            findNavController.navigate(R.id.home_action_home_makefragment_to_home_homefragment)
                        }

                        else -> {}
                    }
                }

            })
        }
        againBuyDialog?.show()

    }


}