package xn.xxp.widget

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import core.ui.widget.decoration.GridSpacingItemDecoration
import http.vo.response.LabWarnVo
import xn.xxp.R
import xn.xxp.databinding.DialogWaringBinding
import xn.xxp.home.adapter.SensorEnum
import xn.xxp.utils.AudioPlayer
import xn.xxp.utils.Tool

/**
 * info
 *
 * @author ReiChin_
 */
class WaringDialog(
    context: Context,
    private val waringData: List<LabWarnVo>
) :
    Dialog(context, R.style.AlertDialogStyle) {

    private val viewBinding: DialogWaringBinding by lazy {
        DialogWaringBinding.inflate(LayoutInflater.from(context))
    }

    private val mWaringAdapter by lazy { WaringAdapter() }

    fun updateWaringValue(waringData: List<LabWarnVo>) {
        val validWaringData =
            waringData.filter { null != it.firstTrigger() }.map { it.firstTrigger() }


        val newlyData = validWaringData.filter { SensorEnum.FIRE.funNum != it.code }
        if (newlyData.size < 3) {
            viewBinding.largeWaring.visibility = View.GONE
            viewBinding.smallWaring.visibility = View.VISIBLE
            when (newlyData.size) {
                1 -> {
                    viewBinding.item1.visibility = View.VISIBLE
                    viewBinding.item2.visibility = View.GONE
                    viewBinding.item1.text = newlyData[0].formatWaring()
                }

                2 -> {
                    viewBinding.item1.visibility = View.VISIBLE
                    viewBinding.item2.visibility = View.VISIBLE
                    viewBinding.item1.text = newlyData[0].formatWaring()
                    viewBinding.item2.text = newlyData[1].formatWaring()
                }

                else -> {
                    viewBinding.largeWaring.visibility = View.GONE
                    viewBinding.smallWaring.visibility = View.GONE
                }
            }
        } else {
            viewBinding.largeWaring.visibility = View.VISIBLE
            viewBinding.smallWaring.visibility = View.GONE
            mWaringAdapter.setNewInstance(newlyData.toMutableList())
        }
        val unFire = newlyData.size == waringData.size
        viewBinding.waringTitle.text = buildWaringTitle(newlyData, unFire)
    }

    private fun buildWaringTitle(newlyData: List<LabWarnVo.TriggerVo>, unFire: Boolean): String {
        if (newlyData.isEmpty()) return "火灾报警！请立即核实处理。"
        return if (unFire) "传感器监测数据异常报警，请立即核实处理。" else "火灾报警！传感器监测数据异常，请立即核实处理。"
    }

    private fun audioResId(): Int {
        val fireWaring = waringData.find { SensorEnum.FIRE.funNum == it.firstTrigger()?.code }
        return when {
            null == fireWaring -> R.raw.audio_waring_sensor
            waringData.size == 1 -> R.raw.audio_waring_fire
            else -> R.raw.audio_waring_fire_sensor
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        initWindowConfig()
        initViews()
        AudioPlayer.getInstance().play(audioResId())
    }

    override fun dismiss() {
        super.dismiss()
        AudioPlayer.getInstance().stop()
        if (mAnimDrawable.isRunning) mAnimDrawable.stop()
    }

    private fun initWindowConfig() {
        window?.apply {
            setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL)
            setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        }
    }

    private fun initViews() {
        viewBinding.close.setOnClickListener {
            dismiss()
        }

        viewBinding.waringImg.setImageDrawable(mAnimDrawable)
        mAnimDrawable.start()

        viewBinding.largeWaring.layoutManager = GridLayoutManager(context, 3)
        val decor = GridSpacingItemDecoration(
            3, Tool.INSTANCE.dip2px(8f), Tool.INSTANCE.dip2px(12f), true
        )
        viewBinding.largeWaring.addItemDecoration(decor)
        viewBinding.largeWaring.adapter = mWaringAdapter

        updateWaringValue(waringData)
    }

    private val mAnimDrawable by lazy {
        AnimationDrawable().apply {
            addFrame(ContextCompat.getDrawable(context, R.mipmap.img_waring1)!!, 200)
            addFrame(ContextCompat.getDrawable(context, R.mipmap.img_waring2)!!, 200)
            isOneShot = false
        }
    }

}

private class WaringAdapter :
    BaseQuickAdapter<LabWarnVo.TriggerVo, BaseViewHolder>(R.layout.item_waring) {

    override fun convert(holder: BaseViewHolder, item: LabWarnVo.TriggerVo) {
        holder.setText(R.id.content, item.formatWaring())
    }

}