package xn.hxp.weidith

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.*
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import xn.hxp.R
import xn.hxp.comm.Constants
import xn.hxp.ui.adapter.CabinetDoorAdapter
import xn.hxp.ui.adapter.CabinetDoorRighAdapter
import xn.hxp.ui.adapter.DoorStoreyAdapter
import com.blankj.utilcode.util.LogUtils
import com.rc.httpcore.bean.ChemicalTypeBean
import com.rc.httpcore.bean.LockVoListBean
import com.rc.httpcore.bean.RuleBean

//化学品存储位置-归还位置
class StorageDialog(
    private val ct: Context,
    private var mType: Int = 0,
    private val listData: List<RuleBean>,
    private var lint: IonClickListener
) : Dialog(ct) {
    private val mAdapterLeft by lazy { CabinetDoorAdapter(ct) }  //左边柜子
    private val mAdapterRigh by lazy { CabinetDoorRighAdapter(ct) }  //右边柜子
    private val mAdapterStorey by lazy { DoorStoreyAdapter() }  //柜子层数
    private val mStoreyList = mutableListOf<Int>()  //层数
    private var cabinetName: String? = null
    private var cabinetId: String? = null
    private var mDoorName: String? = null
    private var mDoorUniqueId: String? = null
    private var mLockNum: String? = null
    private var mCounter = 0
    private var mUnlockingMethod: Int = 0
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var butClos: Button? = null

    init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.storage_dialog)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setGravity(Gravity.CENTER)
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        // 设置点击外部空白处不关闭对话框
        setCanceledOnTouchOutside(false)
        if (mType == 1) {
            findViewById<LinearLayout>(R.id.lin3).visibility = View.VISIBLE
            val rvStorey = findViewById<RecyclerView>(R.id.cabinetLayer)
            rvStorey.layoutManager = LinearLayoutManager(ct)
            rvStorey.adapter = mAdapterStorey
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val recyclerViewListLeft = findViewById<RecyclerView>(R.id.recyclerViewListLeft)
        recyclerViewListLeft.layoutManager = LinearLayoutManager(ct)
        recyclerViewListLeft.adapter = mAdapterLeft

        val recyclerViewListRight = findViewById<RecyclerView>(R.id.recyclerViewListRight)
        recyclerViewListRight.layoutManager = LinearLayoutManager(ct)
        recyclerViewListRight.adapter = mAdapterRigh

        mAdapterLeft.setNewInstance(listData.toMutableList())
        mAdapterLeft.setOnItemClickListener { adapter, view, position ->
            mAdapterLeft.data.forEach { it.isType = false }
            mAdapterLeft.data[position].isType = true
            mAdapterRigh.data.forEach { it.isType = false }  //柜门初始化
            mAdapterLeft.notifyDataSetChanged()
            if (mAdapterLeft.data[position].cabinetDoorVoList != null) {
                mLockNum = mAdapterLeft.data[position].lockNum
                cabinetName = mAdapterLeft.data[position].cabinetName
                cabinetId = mAdapterLeft.data[position].cabinetId
                mAdapterRigh.setNewInstance(mAdapterLeft.data[position].cabinetDoorVoList.toMutableList())
            }
        }

//        if (mType == 1) {
//            val doorLayers = mAdapterLeft.data[0].cabinetDoorVoList[0].doorLayers
//            for (i in 1..doorLayers) {
//                mStoreyList.add(i)
//                mAdapterStorey.setNewInstance(mStoreyList)
//            }
//        }

        mAdapterRigh.setOnItemClickListener { adapter, view, position ->
            val cabinetDoorVo = mAdapterRigh.data[position]
            mDoorName = cabinetDoorVo.doorName
            mDoorUniqueId = cabinetDoorVo.doorUniqueId
            mCabinetLockVoList = cabinetDoorVo.cabinetLockVoList
            mAdapterRigh.data.forEach { it.isType = false }
            mAdapterRigh.data[position].isType = true
            mAdapterRigh.notifyDataSetChanged()
            if (mType == 0) {
                lint.onClick(
                    cabinetId!!,
                    cabinetName!!,
                    mDoorName!!,
                    mDoorUniqueId!!,
                    mCabinetLockVoList!!,
                    cabinetDoorVo.doorLayers,
                    mLockNum!!
                )
                mCountDownHandler.removeMessages(Constants.WHAT_COUNT_DOWN_TWO)
                mCountDownHandler.sendEmptyMessage(Constants.WHAT_COUNT_DOWN_TWO)
                dismiss()
            } else {
                val doorLayers = cabinetDoorVo.doorLayers
                LogUtils.i("========层${doorLayers}")
                mStoreyList.clear()
                for (i in 1..doorLayers) {
                    mStoreyList.add(i)
                }
                if (mAdapterStorey.data != null && mAdapterStorey.data.size > 0) {
                    mAdapterStorey.data = mStoreyList
                    mAdapterStorey.notifyDataSetChanged()
                } else {
                    mAdapterStorey.setNewInstance(mStoreyList)
                }

            }

        }

        //选择得层数
        mAdapterStorey.setOnItemClickListener { adapter, view, position ->
            //当前选择得层数
            val layers = mAdapterStorey.data[position]
            lint.onClick(
                cabinetId!!,
                cabinetName!!,
                mDoorName!!,
                mDoorUniqueId!!,
                mCabinetLockVoList!!,
                layers,
                mLockNum!!
            )
            closHandle()
            dismiss()
        }


        findViewById<TextView>(R.id.butClos).setOnClickListener {
            closHandle()
            dismiss()
            lint.onClose()
        }
        mCountDownHandler.removeMessages(Constants.WHAT_COUNT_DOWN_TWO)
        mCountDownHandler.sendEmptyMessage(Constants.WHAT_COUNT_DOWN_TWO)
    }


    //存储位置:一柜子-左一门
    interface IonClickListener {
        fun onClick(
            cabinetId: String,
            cabinetName: String,
            doorName: String,
            doorId: String,
            cabinetLockVoList: List<LockVoListBean>,
            layers: Int,
            lockNum: String, //柜锁编号
        )

        fun onClose()
    }

    private fun closHandle() {
        mCountDownHandler.removeMessages(Constants.WHAT_COUNT_DOWN_TWO)
        mCountDownHandler.removeCallbacksAndMessages(null)
    }

    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            if (Constants.WHAT_COUNT_DOWN_TWO == msg.what) {

                val countDown = Constants.OFFTIME_TIME - mCounter
                Log.d("======返回时间", "$countDown")
                if (countDown <= 0) {
                    dismiss()
                } else {
                    sendEmptyMessageDelayed(Constants.WHAT_COUNT_DOWN_TWO, 1000)
                }
                mCounter++
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        // 在触摸事件发生时被调用
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                // 用户按下屏幕时的处理逻辑
                onUserInteraction()
            }
            MotionEvent.ACTION_MOVE -> {
                // 用户在屏幕上移动手指时的处理逻辑
            }
            MotionEvent.ACTION_UP -> {
                // 用户抬起手指时的处理逻辑
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun onUserInteraction() {
        // 在用户与对话框交互时的逻辑处理
        LogUtils.i("=========弹框触发了")
        mCounter = 0
    }
}