package com.quyunshuo.module.home.dialog

import android.os.Handler
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.plc.message.Message
import com.quyunshuo.androidbaseframemvvm.base.ktx.invisible
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.mvvm.v.BaseFrameDialogFragment
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.listener.ShoppingAdapterClickListener
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.adapter.ShoppingCartAdapter
import com.quyunshuo.module.home.databinding.BackstageDialogShoppingCartBinding
import com.quyunshuo.module.home.fragment.vm.BuyFragmentVM
import com.quyunshuo.module.home.fragment.vm.HomeFragmentVM
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


/**
 * 购物车列表对话框
 */
class ShoppingCartDialogFragment :
    BaseFrameDialogFragment<BackstageDialogShoppingCartBinding, BuyFragmentVM>(),
    LifecycleObserver, View.OnClickListener {

    private var homeFragmentVM: HomeFragmentVM? = null
    var type1: Int = 1
    var type2: Int = 2
    private val CLOSE_TIME = 120
    private var backTime: Int = CLOSE_TIME
    private val myHandler: MyHandler = MyHandler(this@ShoppingCartDialogFragment)
    private val TAG = "PayChooseDialogFragment"
    private var connectionServerDialoglistener: DialogClickListener? = null
    override val mViewModel: BuyFragmentVM by viewModels()
    private var shoppingTrolleyList: List<ShoppingCartBean> = ArrayList()

    private var shoppingCartAdapter: ShoppingCartAdapter? = null
    override fun getAnimationType(): Int {
        return 1
    }

    fun setListener(listener: DialogClickListener) {
        this.connectionServerDialoglistener = listener
    }

    override fun BackstageDialogShoppingCartBinding.initView() {
        with(rvSpList) {
            val gridLayoutManager =
                GridLayoutManager(
                    this@ShoppingCartDialogFragment.context,
                    1,
                    GridLayoutManager.VERTICAL,
                    false
                )
            layoutManager = gridLayoutManager
            //设置adapter
            shoppingCartAdapter = ShoppingCartAdapter(shoppingTrolleyList)
            shoppingCartAdapter?.setOnclickListener(object : ShoppingAdapterClickListener {
                override fun onClickListener(
                    view: View?,
                    position: Int,
                    data: String?,
                    tvCount: TextView
                ) {
                    when (view?.id) {
                        R.id.tv_delete -> {
                            homeFragmentVM?.shoppingTrolleyRemove(position)
                            shoppingCartAdapter?.notifyItemRemoved(position)
                        }

                        R.id.tv_add -> {
                            val isAddSuccess =
                                homeFragmentVM?.shoppingTrolleyUpdateCount(
                                    data?.toInt()!!,
                                    position
                                )
                            if (isAddSuccess == false) {
                                tvCount.text = (tvCount.text.toString().toInt() - 1).toString()

                            }
                        }

                        R.id.tv_subtract -> {
                            XLogUtil.d("点击3: ")
                            if (data.toString().toInt() <= 0) {
                                homeFragmentVM?.shoppingTrolleyRemove(position)
                                shoppingCartAdapter?.notifyItemRemoved(position)
                                return
                            }
                            homeFragmentVM?.shoppingTrolleyUpdateCount(data?.toInt()!!, position)

                        }

                        else -> {}
                    }
                }
            })
            adapter = shoppingCartAdapter
        }
        btnClean.setOnClickListener(this@ShoppingCartDialogFragment)
        btnCancle.setOnClickListener(this@ShoppingCartDialogFragment)
        btnPay.setOnClickListener(this@ShoppingCartDialogFragment)
        initUI()
    }

    private fun initUI() {

        if (!SpUtils.getBoolean(MMKVName.PROMOTION_CODE, false)!!) {
            mBinding.etPromotionCode.invisible()
        }
    }


    override fun createVB() = BackstageDialogShoppingCartBinding.inflate(layoutInflater)
    override fun initObserve() {
        lifecycle.addObserver(myHandler)
        observeLiveData(homeFragmentVM!!.shoppingCarSumPrice, ::shoppingCarSumPrice)
    }

    private fun shoppingCarSumPrice(d: Double) {
        mBinding.tvPrice.text = "合计：$d"
    }

    override fun initRequestData() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    override fun onDestroyView() {
        mBinding.rvSpList.adapter = null
        dismiss()
        super.onDestroyView()
    }

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

        override fun handleMessage(msg: android.os.Message) {
            //as用来强转
            var fragment: ShoppingCartDialogFragment =
                mWeakReference.get() as ShoppingCartDialogFragment
            when (msg.what) {
                1 -> {
                    fragment.backTime--
                    if (fragment.backTime <= 0) {
                        fragment.connectionServerDialoglistener?.onClickListener(fragment.type1, "")
                        fragment.dismiss()
                    }
                }

                else -> {

                }
            }
        }

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


    private var jobTimer: Job? = null

    private fun startRefreshime() {
        backTime = CLOSE_TIME
        stopRefreshTime()
        // 启动协程
        jobTimer = CoroutineScope(Dispatchers.IO).launch {
            while (true) {
                myHandler.sendEmptyMessage(1)
                delay(1000) // 每隔1秒重复执行
            }
        }
    }

    private fun stopRefreshTime() {
        jobTimer?.cancel()
    }

    override fun onStart() {
        startRefreshime()
        super.onStart()
        val dialog = dialog ?: return
        val window = dialog.window
        if (window != null) {
            // 设置对话框宽高和位置
            val display = window.windowManager.defaultDisplay
            val defaultKeyWidth = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                1080f,
                context?.resources?.displayMetrics
            ).toInt()
            window.setLayout(display.width, defaultKeyWidth)
        }
    }

    override fun onStop() {
        stopRefreshTime()
        super.onStop()
    }

    fun setData(mViewModel: HomeFragmentVM) {
        if (this.homeFragmentVM == null) {
            this.homeFragmentVM = mViewModel
        }
        shoppingTrolleyList = this.homeFragmentVM!!.getShoppingTrolleyList()

        shoppingCartAdapter?.setData(shoppingTrolleyList)
        shoppingCartAdapter?.notifyDataSetChanged()
    }



    override fun onClick(v: View?) {
        when (v?.id) {
            mBinding.btnClean.id -> {
                homeFragmentVM?.shoppingTrolleyRemoveAll()
                shoppingCartAdapter?.notifyDataSetChanged()
                connectionServerDialoglistener?.onClickListener(type1, "")
                dismiss()
            }

            mBinding.btnCancle.id -> {
                connectionServerDialoglistener?.onClickListener(type1, "")
                dismiss()
            }

            mBinding.btnPay.id -> {
                //获得优惠码，传递过去。
                val proCode = mBinding.etPromotionCode.text.toString()

                connectionServerDialoglistener?.onClickListener(mBinding.btnPay.id, proCode)
                dismiss()

            }

            else -> {}
        }
    }


}