package com.module.backstage.dialog

import android.os.Handler
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.recyclerview.widget.GridLayoutManager
import com.hboxs.serialport.plc.DialogClickListener
import com.module.backstage.adapter.ErrorCheckAdapter
import com.module.backstage.databinding.BackstageDialogErrorCheckBinding
import com.module.backstage.model.ErrorCheckTask
import com.module.backstage.vm.ErrorStatFragmentVM
import com.quyunshuo.androidbaseframemvvm.base.ktx.invisible
import com.quyunshuo.androidbaseframemvvm.base.mvvm.v.BaseFrameDialogFragment
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference

/**
 * 购物车列表对话框
 */
class ErrorDialogFragment :
    BaseFrameDialogFragment<BackstageDialogErrorCheckBinding, ErrorStatFragmentVM>(),
    LifecycleObserver, View.OnClickListener {

    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@ErrorDialogFragment)
    private val TAG = "PayChooseDialogFragment"
    private var connectionServerDialoglistener: DialogClickListener? = null
    override val mViewModel: ErrorStatFragmentVM by viewModels()
    private var shoppingTrolleyList: List<ErrorCheckTask> = ArrayList()

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

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

    override fun BackstageDialogErrorCheckBinding.initView() {
        with(rvSpList) {
            val gridLayoutManager =
                GridLayoutManager(
                    this@ErrorDialogFragment.context,
                    1,
                    GridLayoutManager.VERTICAL,
                    false
                )
            layoutManager = gridLayoutManager
            //设置adapter
            shoppingCartAdapter = ErrorCheckAdapter(shoppingTrolleyList)

            adapter = shoppingCartAdapter
        }
        initUI()
    }

    private fun initUI() {

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


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


    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: ErrorDialogFragment =
                mWeakReference.get() as ErrorDialogFragment
            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(shoppingTrolleyList: List<ErrorCheckTask>) {
        this.shoppingTrolleyList =shoppingTrolleyList
        shoppingCartAdapter?.setData(this.shoppingTrolleyList)
        shoppingCartAdapter?.notifyDataSetChanged()
        XLogUtil.d("setData:"+this.shoppingTrolleyList)
    }

    override fun onClick(v: View?) {
    }
}