package com.quyunshuo.module.home.dialog

import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.util.TypedValue
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.NavHostFragment
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hboxs.serialport.plc.DialogClickListener
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PayEnum
import com.quyunshuo.androidbaseframemvvm.base.mvvm.v.BaseFrameDialogFragment
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.PayTypeBean
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.PayName
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.listener.AdapterClickListener
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.module.home.enums.PayNavEnum
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.adapter.PayChooseDialogAdapter
import com.quyunshuo.module.home.databinding.HomeDialogPayChooseBinding
import com.quyunshuo.module.home.fragment.vm.HomeFragmentVM
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 java.lang.ref.WeakReference

/**
 * 选择支付方式的对话框
 */

@AndroidEntryPoint
class PayChooseDialogFragment :
    BaseFrameDialogFragment<HomeDialogPayChooseBinding, HomeFragmentVM>(), LifecycleObserver {
    var typeBack: Int = 1
    var type2: Int = 2
    private val CLOSE_TIME = 120
    private var backTime: Int = CLOSE_TIME
    private val myHandler: MyHandler = MyHandler(this@PayChooseDialogFragment)
    private val TAG = "PayChooseDialogFragment1"
    private var connectionServerDialoglistener: DialogClickListener? = null
    override val mViewModel: HomeFragmentVM by viewModels()
    var arrayListState: HashMap<String, PayTypeBean> = HashMap() //支付方式
    private lateinit var homeProductAdapter: PayChooseDialogAdapter
    private var promotionCode: String? = null //优惠码
    private lateinit var shoppingTrolleyList: List<ShoppingCartBean> //购物车内容
    private var sumPrice: Double = 0.0//总金额  没有优惠的

    override fun getAnimationType(): Int {
        return 1
    }

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

    override fun HomeDialogPayChooseBinding.initView() {
        ivBack.setOnClickListener {
            connectionServerDialoglistener?.onClickListener(typeBack, "")
            dismiss()
        }

        with(rvPay) {
            val gridLayoutManager: GridLayoutManager =
                GridLayoutManager(
                    this@PayChooseDialogFragment.context,
                    3,
                    GridLayoutManager.VERTICAL,
                    false
                )
            layoutManager = gridLayoutManager
            //设置adapter
            val productStr = SpUtils.getString(MMKVName.PAY_TYPE, "")
            if (productStr != "") {
                arrayListState = Gson().fromJson(
                    productStr,
                    object : TypeToken<HashMap<String, PayTypeBean>?>() {}.type
                )
            } else {
                if (Heartbeat.isForeign) {
                    arrayListState[PayEnum.BILL_COIN.code] =
                        PayTypeBean(PayEnum.BILL_COIN.code, true)
                } else {
                    arrayListState[PayEnum.TWO_CODE.code] = PayTypeBean(PayEnum.TWO_CODE.code, true)
                }
            }
            Log.d("arrayListState", "arrayListState initView: " + arrayListState.size)
            homeProductAdapter = PayChooseDialogAdapter(arrayListState)
            homeProductAdapter.setOnclickListener(object : AdapterClickListener {
                override fun onClickListener(view: View?, position: Int, data: String?) {
                    backTime = CLOSE_TIME
                    payMentNav(data!!)

                }
            })
            adapter = homeProductAdapter
        }
        for (mutableEntry in arrayListState) {
            payMentNav(mutableEntry.key)
            break

        }
    }


    /**
     * 不同的支付方式跳转不同的nav
     */
    private fun payMentNav(data: String) {
        val enumByValue = PayNavEnum.getEnumByValue(data)
        val navHostFragment =
            childFragmentManager.findFragmentById(R.id.fcv_pay) as NavHostFragment
        val navController = navHostFragment.navController
        var bundle = Bundle()
        bundle.putString("SELECT_PRO", Gson().toJson(shoppingTrolleyList))
        bundle.putDouble("PRICE", sumPrice)
        bundle.putString("PROMOTION_CODE", promotionCode)
        bundle.putString("PayType", UiUtil.getStringRes(enumByValue.payType))
        navController.navigate(enumByValue.navId, bundle)
        //点击取消的时候发送一个event，这样统一一点，因为mdb刷卡器也可以取消，nayax也可以取消。。
        EventBus.getDefault().post(ApiMessageEvent(PayName.CANCEL_PAY, ""))
    }

    override fun createVB() = HomeDialogPayChooseBinding.inflate(layoutInflater)
    override fun initObserve() {
        lifecycle.addObserver(myHandler)
    }

    override fun initRequestData() {

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    override fun onDestroyView() {
        Log.d("PayChooseDialogFragment", "onDestroyView1: ")
        stopRefreshTime()
        mBinding.rvPay.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: PayChooseDialogFragment = mWeakReference.get() as PayChooseDialogFragment
            when (msg.what) {
                1 -> {
                    fragment.mBinding.tvTime.text = fragment.backTime.toString() + "s "+UiUtil.getStringRes(R.string.base_down_time)
                    fragment.backTime--
                    if (fragment.backTime <= 0) {
                        fragment.connectionServerDialoglistener?.onClickListener(
                            fragment.typeBack,
                            ""
                        )
                        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,
                900f,
                context!!.resources.displayMetrics
            ).toInt()
            window.setLayout(display.width, defaultKeyWidth)
        }
    }

    fun setData(
        shoppingTrolleyList: List<ShoppingCartBean>,
        promotionCode: String?,
        shoppingTrolleySumPrice: Double
    ) {
        this.shoppingTrolleyList = shoppingTrolleyList
        this.promotionCode = promotionCode
        this.sumPrice = shoppingTrolleySumPrice
    }


}