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

import android.annotation.SuppressLint
import android.graphics.Point
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.telephony.SignalStrength
import android.text.TextUtils
import android.text.format.DateFormat
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.elvishew.xlog.XLog
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.sbc.SBCHeartbeat
import com.module.pay.nayax.CreditCardPresenter
import com.quyunshuo.androidbaseframemvvm.base.bean.Global
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.ktx.setVisible
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.base.utils.commons.StringUtils
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.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.constant.PayName
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.enums.ConnectStateEnum
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.adapter.HomeProductAdapter
import com.quyunshuo.module.home.databinding.HomeFragmentHomeBinding
import com.quyunshuo.module.home.dialog.PayChooseDialogFragment
import com.quyunshuo.module.home.dialog.PaySuccessDialog
import com.quyunshuo.module.home.dialog.ShoppingCartDialogFragment
import com.quyunshuo.module.home.dialog.TipsDialog
import com.quyunshuo.module.home.enums.LogoEnum
import com.quyunshuo.module.home.fragment.fragment.pay.PaySuccessBean
import com.quyunshuo.module.home.fragment.makefragment.utlis.OrderManagement
import com.quyunshuo.module.home.fragment.vm.HomeFragmentVM
import com.quyunshuo.module.home.utils.NetWorkUtils
import com.quyunshuo.module.home.utils.PhoneStateUtils
import com.quyunshuo.module.home.weight.NXHooldeIMGView
import com.zhanshow.mylibrary.network.NetworkStateReceiver.NetworkStateReceiverListener
import com.zhanshow.mylibrary.phonestate.MyPhoneStateListener.MyPhoneStateListenerListener
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.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.ref.WeakReference
import java.text.DecimalFormat


/**
 * 首页Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@RegisterEventBus
@AndroidEntryPoint
class HomeFragment : BaseFragment<HomeFragmentHomeBinding, HomeFragmentVM>(), View.OnTouchListener,
    View.OnClickListener, LifecycleObserver {


    private val myHandler: MyHandler = MyHandler(this@HomeFragment)
    private var productList = ArrayList<ProductDataBean>()//传递给make的制作商品list
    private var homeProductAdapter: HomeProductAdapter? = null
    override val mViewModel: HomeFragmentVM by viewModels()
    private var CLOSE_TIME = 60
    private var backTime: Int = CLOSE_TIME //倒计时时间
    private var pauseTime: Boolean = true //用于对话框出现的时候，那么就要修改为false，如果关掉，则修改为true，继续倒计时
    private val TAG = "HomeFragment"
    private var payChooseDialogFragment: PayChooseDialogFragment? = null//支付方式选择对户口
    private var HANDLE_TIME = 1//设置时间
    private var NETWORK_STATE = 2//网络状态
    private var NETWORK_LEVEL = 3//网络等级

    private var product: ProductDataBean? = null//产品
    override fun createVB() = HomeFragmentHomeBinding.inflate(layoutInflater)
    private var tipsDialog: TipsDialog? = null//条件不足提示对话框
    private var paySuccessDialog: PaySuccessDialog? = null//支付成功对话框
    private var shoppingCartDialog: ShoppingCartDialogFragment? = null//购物车列表对话框
    private var promotionCode: String? = "" //用户输入的优惠码
    private var networkName = "";//当前的网络状态
    private var networkLevel = 4;//当前的网络等级
    var shopping: WeakReference<ShoppingCartDialogFragment>? = null
    var payChoose: WeakReference<PayChooseDialogFragment>? = null//支付方式选择对户口

    @RequiresApi(Build.VERSION_CODES.P)
    override fun HomeFragmentHomeBinding.initView() {

        // ToastUtil.switchToastStyleToWarn("app版本："+AppTypeManger.getInstance().appChina)
        startRefreshime()

        with(homeRvProduct) {
            productList = mViewModel.getPriceData()
            //设置布局排列方式，默认垂直排列
            val gridLayoutManager =
                GridLayoutManager(
                    this@HomeFragment.context,
                    productList.size,
                    GridLayoutManager.VERTICAL,
                    false
                )
            layoutManager = gridLayoutManager
            //设置adapter

            homeProductAdapter = HomeProductAdapter(productList)
            homeProductAdapter?.setOnclickListener { view, position, data ->
                clickProduct(
                    position,
                    view
                )
            }

            adapter = homeProductAdapter
        }

        LongClickUtils.setLongClick(Handler(), clHomeTime, 3000, object : View.OnLongClickListener {
            override fun onLongClick(p0: View?): Boolean {
                try {
                    val findNavController = findNavController()
                    findNavController.navigate(R.id.home_action_home_homefragment_to_home_userloginfragment)
                } catch (E: Exception) {

                }


                return true
            }

        })
        clHomeBg.setOnTouchListener(this@HomeFragment)
        val deviceId = XLogUtil.getDeviceId()
        if (deviceId.isNotEmpty()) {
            tvClientId.text =
                UiUtil.getStringRes(R.string.base_home_dev_id) + deviceId.substring(deviceId.length - 6)
        }
        clShoppingCart.setOnClickListener(this@HomeFragment)
        tvTotal.setOnClickListener(this@HomeFragment)
        ivShoppingTrolley.setOnClickListener(this@HomeFragment)
        tvPay.setOnClickListener(this@HomeFragment)
        tvAacpeBill.text = UiUtil.getStringRes(R.string.base_insert_banknotes) + "：${Heartbeat.acceptBill}"
        initUi()
        //刷卡器初始化 在内部要做好判断？在外部吧  支付方式是否保护Nyax来决定。
        CreditCardPresenter.getCreditCardContract()
        //联系人
        ilContact.tvContact.text = SpUtils.getString(MMKVName.CONTACT, "name")
        ilContact.tvContactWay.text = SpUtils.getString(MMKVName.CONTACT_WAY, "123456")


        if (SpUtils.getBoolean(MMKVName.DISCOUNT_FUNCTION, false) == true) {
            val discountFunctionTitle: String = SpUtils.getString(MMKVName.TIPS_DISCOUNT_TEXT, "")!!
            if ("" != discountFunctionTitle) {
                tvDiscountFunctionTitle.visibility = View.VISIBLE
                tvDiscountFunctionTitle.text =
                    "大家家底阿斯蒂芬士大夫啊手动阀手动阀阿斯蒂芬啊手动阀手动阀手动阀"
                tvDiscountFunctionTitle.setSelected(true);
                tvDiscountFunctionTitle.setSingleLine(true);
                tvDiscountFunctionTitle.setEllipsize(TextUtils.TruncateAt.MARQUEE);
                tvDiscountFunctionTitle.setMarqueeRepeatLimit(-1);
                tvDiscountFunctionTitle.setFocusable(true);
                tvDiscountFunctionTitle.setFocusableInTouchMode(true);
                tvDiscountFunctionTitle.requestFocus();
                tvDiscountFunctionTitle.requestFocusFromTouch();
            }
        }
        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 }


        //监听当前使用的是什么网络:wifi，3g,4g,2g,wap,unknown,disconnect;
        NetWorkUtils.registerLister(
            this@HomeFragment.activity,
            object : NetworkStateReceiverListener {
                override fun networkAvailable(networkName: String) {
                    Log.e(TAG, "网络 networkAvailable: $networkName")
                    Global.isNetWork = true
                    this@HomeFragment.networkName = networkName
                    myHandler.sendEmptyMessage(NETWORK_STATE)

                }

                override fun networkUnavailable() {
                    Log.e(TAG, "网络 networkUnavailable: ")
                    Global.isNetWork = false
                    networkName = "disconnect"
                    myHandler.sendEmptyMessage(NETWORK_STATE)
                }
            })


        // position:0～5数值 0:无手机卡或者无信号强度 1～5 手机信号轻度，依次增大
        PhoneStateUtils.registerPhoneStateListener(
            this@HomeFragment.activity,
            object : MyPhoneStateListenerListener {

                override fun onSignalStrengthsChanged(p0: SignalStrength?) {
                    Log.e(TAG, "网络  currentSignalStrength: " + p0?.level)
                    this@HomeFragment.networkLevel = p0?.level!!
                    myHandler.sendEmptyMessage(NETWORK_LEVEL)
                }
            })
    }


    /**
     * 定制化、UI显隐等
     */
    private fun initUi() {
        if (!SpUtils.getBoolean(MMKVName.SHOPPING_TROLLEY, true)!!) {
            mBinding.clShoppingCart.setVisible(false)
        }

    }

    override fun initObserve() {
        observeLiveData(mViewModel.D170Value, ::dataChange)
        observeLiveData(mViewModel.shoppingCarSize, ::shoppingCarSize)
        observeLiveData(mViewModel.shoppingCarSumPrice, ::shoppingCarSumPrice)

        lifecycle.addObserver(myHandler)
        lifecycle.addObserver(this)
    }

    private fun shoppingCarSumPrice(price: Double) {
        mBinding.tvTotal.text = price.toString()
    }

    private fun shoppingCarSize(i: Int) {
        mBinding.tvUpdateHint.text = i.toString()
    }


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

    //选择产品:单选或多选。
    private fun clickProduct(position: Int, view: View?) {
        product = productList[position]
        //点击前校验 有没有开机、有没有选择支付方式等。
        if (!VerifyCanJoin()) {
            return
        }
        if (SpUtils.getBoolean(MMKVName.SHOPPING_TROLLEY, true)!!) {
            //添加进购物车
            val isAddSuccess = mViewModel.shoppingTrolleyAdd(product!!)
            if (isAddSuccess) {
                addAction(view)
            }
        } else {
            //单选 直接打开支付对话框  使用和购物车类似的方式，只不过呢，购物车只能加入一个而已。
            mViewModel.shoppingTrolleyRemoveAll()
            val isAddSuccess = mViewModel.shoppingTrolleyAdd(product!!)
            if (isAddSuccess) {
                addAction(view)
            }
            openPayDialog()
        }
    }

    /**
     * 校验是否可以加入购物车
     * */
    fun VerifyCanJoin(): Boolean {
        val deviceStatusCheck = mViewModel.deviceStatusCheck()
        Log.d(TAG, "deviceStatusCheck:" + deviceStatusCheck)
        if (StringUtils.isNotNullOrEmpty(deviceStatusCheck)) {
            deviceStatusCheck?.let {
                showTipsDialog(it)
            }
            return false
        }
        if (product?.price!! <= 0 && !Heartbeat.isForeign) {
            showTipsDialog("价格低于0元,不能购买")
            return false
        }
        return true
    }

    /**
     * 去付款
     * 选择支付方式对话框
     */
    private fun openPayDialog() {
        /*if (payChooseDialogFragment == null) {
            payChooseDialogFragment = PayChooseDialogFragment()
            lifecycle.addObserver(payChooseDialogFragment!!)
            payChooseDialogFragment?.setListener(object : DialogClickListener {
                override fun onClickListener(type: Int, text: String?) {
                    when (type) {
                        payChooseDialogFragment?.typeBack -> {
                            pauseTime = true
                            //点击取消的时候发送一个event，这样统一一点，因为mdb刷卡器也可以取消，nayax也可以取消。。
                            EventBus.getDefault().post(ApiMessageEvent(PayName.CANCEL_PAY, ""))
                        }

                        else -> {}
                    }
                }
            })
            lifecycle.addObserver(payChooseDialogFragment!!)
        }
        //携带购物车内容、优惠码过去。
        payChooseDialogFragment?.setData(
            mViewModel.getShoppingTrolleyList(),
            promotionCode,
            mViewModel.shoppingTrolleySumPrice()
        )
        payChooseDialogFragment?.show(parentFragmentManager, payChooseDialogFragment?.tag)*/
        if (payChoose?.get()?.let { isShow(it) } == true) {
            return
        }
        payChoose = WeakReference(PayChooseDialogFragment())
        payChoose?.get()?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    payChoose?.get()?.typeBack -> {
                        pauseTime = true
                        startRefreshime()
                        //点击取消的时候发送一个event，这样统一一点，因为mdb刷卡器也可以取消，nayax也可以取消。。
                        EventBus.getDefault().post(ApiMessageEvent(PayName.CANCEL_PAY, ""))
                    }

                    else -> {}
                }
            }
        })


        payChoose?.get()?.setData(
            mViewModel.getShoppingTrolleyList(),
            promotionCode,
            mViewModel.shoppingTrolleySumPrice()
        )
        payChoose?.get()?.show(parentFragmentManager, payChooseDialogFragment?.tag)
    }

    override fun initRequestData() {
        lifecycleScope.launch {
            mViewModel.getBanners()

        }
        mViewModel.getArticleData()
    }

    fun isShow(dialogFragment: PayChooseDialogFragment): Boolean {
        if (dialogFragment != null && dialogFragment.getDialog() != null && dialogFragment.getDialog()!!
                .isShowing()
        ) {
            return true
        } else {
            return false
        }
    }

    fun isShowShop(dialogFragment: ShoppingCartDialogFragment): Boolean {
        if (dialogFragment != null && dialogFragment.getDialog() != null && dialogFragment.getDialog()!!
                .isShowing()
        ) {
            return true
        } else {
            return false
        }
    }


    override fun onDestroyView() {
        Log.d(TAG, "onDestroyView: activity")
        mBinding.homeRvProduct.adapter = null //为什么要手动呢？。。。。。

        NetWorkUtils.unRegisterNetWork(activity)
        PhoneStateUtils.unRegisterPhoneStateListener(activity)
        super.onDestroyView()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(message: ApiMessageEvent) {
        when (message.name) {
            MqName.PAY_SUCCESS -> {
                Log.d(TAG, "event: 收到了支付成功")
                payChoose?.get()?.dismiss()
                showPaySuccessDialog()
                lifecycleScope.launch {
                    delay(2000)
                    gotoMake(message.name, message.data as PaySuccessBean)
                }
            }


            PayName.ACCEPT_BILL -> {
                mBinding.tvAacpeBill.setText(UiUtil.getStringRes(R.string.base_insert_banknotes)+"：" + Heartbeat.acceptBill)
            }

            else -> {}
        }
    }


    var makeList: List<ShoppingCartBean>? = null

    private fun gotoMake(name: String, payInfo: PaySuccessBean) {

//        selectProductDataBean = ProTypeEnum.getEnumByValue(name) 上线需要使用这个。
        if (product != null) {
            val findNavController = findNavController()
            var bundle = Bundle()
            makeList = null
//            selectProductDataBean = ProTypeEnum.getEnumByValue(product!!.nameChinese)
//            bundle.putInt("SELECT_PRO", selectProductDataBean.proValue)
            // bundle.putString("SELECT_PRO", Gson().toJson(mViewModel.getShoppingTrolleyList()))
            OrderManagement.getInstance().setOrderList(mViewModel.getShoppingTrolleyList())
            bundle.putDouble("PRICE", mViewModel.shoppingTrolleySumPrice())
            bundle.putString("payType", payInfo.payType)
            bundle.putString("PROMOTION_CODE", promotionCode)
            makeList = splitProductsByCount(mViewModel.getShoppingTrolleyList())
            makeList?.let {
                var allPrice = calculateTotal(it)
                var name = buildNameString(it)
                var sn = payInfo.payNamber
                var payType = payInfo.payType
                CoroutineScope(Dispatchers.Main).launch {
                    Log.d(TAG, "insert: sn:${sn}allPrice:${allPrice}payType:${payType}name:${name}")
                    mViewModel.addLocalOrder(sn, allPrice, payType, name)
                }


            }
            findNavController.navigate(
                R.id.prodution_process,
                bundle
            )
            /* if (SBCHeartbeat.devOType.equals("00")) {//全自动设备
                 findNavController.navigate(
                     R.id.home_action_home_homefragment_to_home_makefragment,
                     bundle
                 )
             } else if (SBCHeartbeat.devOType.equals("01")) {//半自动设备
                 findNavController.navigate(
                     R.id.prodution_process,
                     bundle
                 )
             }*/
            /*  findNavController.navigate(
                  R.id.home_action_home_homefragment_to_home_makefragment,
                  bundle
              )*/
            /*  findNavController.navigate(
                  R.id.home_action_home_homefragment_to_home_makefragment,
                  bundle
              )*/
        }
        XLog.d("payType:$payInfo")
    }

    fun calculateTotal(cartItems: List<ShoppingCartBean>): Double {
        return cartItems.sumOf { it.price }
    }

    // 生成名称拼接字符串
    fun buildNameString(items: List<ShoppingCartBean>): String {
        return items
            .map { bean ->
                // 优先取非空中文名，否则用ID
                bean.nameChinese.takeIf { !it.isNullOrBlank() } ?: bean.nameId
            }
            .joinToString(separator = ", ") // 添加逗号和空格
    }


    fun splitProductsByCount(originalList: List<ShoppingCartBean>): List<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
    }

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

        override fun handleMessage(msg: android.os.Message) {
            //as用来强转
            var fragment: HomeFragment? = mWeakReference.get() as HomeFragment
            LogUtil.d("backinfo", "HomeFragmenthandleMessage")
            when (msg.what) {
                fragment?.HANDLE_TIME -> {
                    setTimeDate(fragment)
                }

                fragment?.NETWORK_STATE -> {
                    setNetwork(fragment)
                }

                fragment?.NETWORK_LEVEL -> {
                    setNetworkLevel(fragment)

                }

                else -> {

                }
            }
        }

        private fun setNetworkLevel(fragment: HomeFragment) {
            XLogUtil.d("fragment.networkLevel:" + fragment.networkLevel)
            when (fragment.networkLevel) {
                1 -> {
                    fragment.mBinding.iv4g.setImageResource(R.drawable.leven1)
                }

                2 -> {
                    fragment.mBinding.iv4g.setImageResource(R.drawable.leven2)
                }

                3 -> {
                    fragment.mBinding.iv4g.setImageResource(R.drawable.leven3)
                }

                4 -> {
                    fragment.mBinding.iv4g.setImageResource(R.drawable.leven4)
                }

                5 -> {
                    fragment.mBinding.iv4g.setImageResource(R.drawable.leven4)
                }

                else -> {
                    fragment.mBinding.iv4g.setImageResource(R.drawable.leven0)

                }
            }
        }

        private fun setNetwork(fragment: HomeFragment) {
            XLogUtil.d("fragment.networkName:" + fragment.networkName)
            when (fragment.networkName) {
                "4g" -> {
                    fragment.mBinding.iv4g.setVisible(true)
                    fragment.mBinding.ivWifi.setVisible(false)

                }

                "wifi" -> {
                    fragment.mBinding.ivWifi.setImageResource(R.drawable.wifi)
                    fragment.mBinding.ivWifi.setVisible(true)
                    fragment.mBinding.iv4g.setVisible(false)
                }

                "disconnect" -> {
                    fragment.mBinding.ivWifi.setImageResource(R.drawable.leven0)
                    fragment.mBinding.ivWifi.setVisible(true)
                    fragment.mBinding.iv4g.setVisible(false)
                }

                else -> {}
            }
        }

        /**
         * 设置时间
         */
        @SuppressLint("SetTextI18n")
        private fun setTimeDate(fragment: HomeFragment) {
            val sysTime = System.currentTimeMillis() //获取系统时间
            val sysTimeStr = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime) //时间显示格式
            fragment.mBinding.tvTime.text = sysTimeStr //更新时间
            fragment.mBinding.tvWendu.text = SBCHeartbeat.outsideTemp + "°C"
            fragment.mBinding.tvShidu.text = SBCHeartbeat.outsideHumidity + "%"
            fragment.mBinding.tvLutou.text = SBCHeartbeat.headTemp + "°C"
            fragment.mBinding.tvFashengqi.text = SBCHeartbeat.steamTemp + "°C"
            fragment.mBinding.totalSpeedTv.text = showSpeed(fragment.mViewModel.getSpeed())
            if (fragment.pauseTime) {
                fragment.backTime--
                if (fragment.backTime == 0) {
                    val findNavController = fragment.findNavController()
                    findNavController.navigate(R.id.home_action_home_homefragment_to_home_buyfragment)
                }
            }
        }

        private val showFloatFormat = DecimalFormat("0.00")
        fun showSpeed(speed: Double): String {
            val speedString: String = if (speed >= 1048576.0) {
                showFloatFormat.format(speed / 1048576.0) + "MB/s"
            } else {
                showFloatFormat.format(speed / 1024.0) + "KB/s"
            }

            return speedString
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun disconnectListener() {

            removeCallbacksAndMessages(null)
        }
    }


    private var jobTimer: Job? = null

    /**
     * 时间日期 隔个一秒执行一次
     */
    private fun startRefreshime() {
        stopRefreshTime()
        // 启动协程
        jobTimer = CoroutineScope(Dispatchers.IO).launch {
            while (true) {
                myHandler.sendEmptyMessage(HANDLE_TIME)
                delay(1000) // 每隔1秒重复执行
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopRefreshTime() {
        jobTimer?.cancel()
    }

    override fun onTouch(p0: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                backTime = CLOSE_TIME
            }

            else -> {}
        }
        return true
    }

    /**
     * 弹窗提醒
     */
    private fun showTipsDialog(content: String) {
        if (tipsDialog == null) {
            tipsDialog = this@HomeFragment.context?.let { TipsDialog(it) }
            lifecycle.addObserver(tipsDialog!!)
        }
        tipsDialog?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    tipsDialog?.type1 -> {
                        tipsDialog?.dismiss()
                    }

                    else -> {}
                }
            }

        })
        tipsDialog?.setContent(content)
        tipsDialog?.show()

        //使用这个的好处，就是界面结束，他里面的内容也不会执行。
        lifecycleScope.launch {
            delay(2000)
            tipsDialog?.dismiss()
            Log.d(TAG, "showTipsDialog: tipsDialog")
        }

    }

    /**
     * 付款成功提醒
     */
    private fun showPaySuccessDialog() {
        if (paySuccessDialog == null) {
            paySuccessDialog = this@HomeFragment.context?.let { PaySuccessDialog(it) }
            lifecycle.addObserver(paySuccessDialog!!)

        }
        paySuccessDialog?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    paySuccessDialog?.type1 -> {
                        paySuccessDialog?.dismiss()
                    }

                    else -> {}
                }
            }

        })
        paySuccessDialog?.show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.cl_shoppingCart,
            R.id.tv_total,
            R.id.iv_shopping_trolley,
            -> {
                //打开购物车对话框
                openShoppingCart()
            }

            R.id.tv_pay -> {
                XLogUtil.d("去支付")
                //去付款
                pay()


            }

            else -> {}
        }
    }

    fun isAllowed(): Boolean {
        if (SBCHeartbeat.isPowerOn) {
            ToastUtil.switchToastStyleToError(UiUtil.getStringRes(R.string.base_not_startup))
            return false
        }
        var connectState = SpUtils.getString(MMKVName.CONNECT_STATE, "")
        if (!connectState.equals(ConnectStateEnum.CONNECTED.name)) {
            ToastUtil.switchToastStyleToError(UiUtil.getStringRes(R.string.base_not_connect_sevice))
            return false
        }

        return true
    }

    //付款方法
    private fun pay() {
        //校验：购物车里面是有商品
        if (mViewModel.getShoppingTrolleyList().isEmpty()) {
            ToastUtil.switchToastStyleToWarn(UiUtil.getStringRes(R.string.base_home_shopping_cart_null))
            return
        }
        stopTimeReturn()
        openPayDialog()
    }

    /**
     * 打开购物车
     * 购物车对话框
     */
    private fun openShoppingCart() {
        //购物车里面是否有内容
        if (mViewModel.getShoppingTrolleyList().isEmpty()) {
            ToastUtil.switchToastStyleToWarn(UiUtil.getStringRes(R.string.base_home_shopping_cart_null))
            return
        }
        stopTimeReturn()
        /*if (shoppingCartDialog == null) {
            shoppingCartDialog = ShoppingCartDialogFragment()
            shoppingCartDialog?.setListener(object : DialogClickListener {
                override fun onClickListener(type: Int, text: String?) {
                    when (type) {
                        shoppingCartDialog?.type1 -> {
                            startTimerReturn()
                        }

                        R.id.btn_pay -> {
                            promotionCode = text
                            pay()
                        }

                        else -> {}
                    }
                }
            })
            lifecycle.addObserver(shoppingCartDialog!!)
        }
//        shoppingCartDialog?.show(this.parentFragmentManager,"shoppingCartDialog")
        getParentFragmentManager().let {
            shoppingCartDialog!!.show(
                it,
                "shoppingCartDialog"
            )
        }
        shoppingCartDialog?.setData(mViewModel)*/
        shopping = WeakReference(ShoppingCartDialogFragment())
        shopping?.get()?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {


                when (type) {
                    shopping?.get()?.type1 -> {
                        Log.d(
                            "backinfo",
                            "onClickListeneronClickListeneronClickListeneronClickListener"
                        )
                        startTimerReturn()
                        startRefreshime()
                    }

                    R.id.btn_pay -> {
                        promotionCode = text
                        pay()
                    }

                    else -> {}
                }
            }
        })
        shopping?.get()?.show(this.parentFragmentManager, "shoppingCartDialog")
        shopping?.get()?.setData(mViewModel)
    }

    /**
     * 开启返回广告界面的倒计时
     */
    private fun startTimerReturn() {
        pauseTime = true
    }

    /**
     * 停止返回广告界面的倒计时
     */
    private fun stopTimeReturn() {
        pauseTime = false
        backTime = CLOSE_TIME
    }

    fun addAction(view: View?) {
        val nxHooldeView: NXHooldeIMGView =
            NXHooldeIMGView(this@HomeFragment.context, R.drawable.pic_sc_01)
        val position = IntArray(2)
        view?.getLocationInWindow(position)
        nxHooldeView.setStartPosition(Point(position[0], position[1]))
        val rootView = this.activity?.getWindow()?.getDecorView() as ViewGroup
        rootView.addView(nxHooldeView)
        val endPosition = IntArray(2)
        mBinding.clShoppingCart.getLocationInWindow(endPosition)
        nxHooldeView.setEndPosition(Point(endPosition[0], endPosition[1]))
        nxHooldeView.startBeizerAnimation()
    }


}