package xn.xxp.home.fragment

import android.graphics.Color
import android.os.AsyncTask
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.rc.view.flowlayout.FlowLayout
import core.ui.fragment.RcBaseFragment
import core.ui.widget.decoration.GridSpacingItemDecoration
import core.util.ifNullOrEmpty
import http.vo.response.LaboratoryVo
import http.vo.response.SafeClassify
import xn.xxp.R
import xn.xxp.databinding.FragmentLabBasicBinding
import xn.xxp.app.LabApp
import xn.xxp.utils.QrTool
import xn.xxp.utils.Tool
import xn.xxp.widget.SimpleFlipperAdapter

/**
 * 主页-实验室信息
 *
 * @author ReiChin_
 */
class LabBasicFragment :
    RcBaseFragment<FragmentLabBasicBinding>() {

    companion object {
        const val TAG = "LabBasicFragment"

        fun newInstance() = LabBasicFragment()
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentLabBasicBinding {
        return FragmentLabBasicBinding.inflate(inflater, container, false)
    }

    override fun initViews(savedInstanceState: Bundle?) {
        val laboratoryVo = LabApp.laboratory
        if (null == laboratoryVo) {
            showToast("暂无实验室信息，即将重新获取")
            Tool.INSTANCE.reStartApp("暂无实验室信息，即将重新获取")
            return
        }

        initLaboratoryInfo(laboratoryVo)
    }

    private fun initLaboratoryInfo(laboratoryVo: LaboratoryVo) {
        val dangerColor = try {
            Color.parseColor(laboratoryVo.dangerColor)
        } catch (e: Exception) {
            Color.parseColor("#15CA48")
        }
        viewBinding.labLevelInfo.setBackgroundColor(dangerColor)
        // 特种设备类
        viewBinding.dangerName.text = laboratoryVo.dangerName
        // 二级
        viewBinding.dangerLevel.text = laboratoryVo.dangerLevel
        viewBinding.subjectName.text = laboratoryVo.subName
        viewBinding.building.text = laboratoryVo.buildName
        viewBinding.address.text = laboratoryVo.room

        // 二维码
        AsyncTask.execute {
            val bitmap = QrTool.generateQRCode(laboratoryVo.qrCodeUrl, 150)
            requireActivity().runOnUiThread {
                Glide.with(requireActivity())
                    .asBitmap()
                    .load(bitmap)
                    .error(R.mipmap.img_error)
                    .into(viewBinding.qrCode)
            }
        }

        // 学院
        viewBinding.labSafePerson.text = "学院：%s    实验室负责人：%s    电话：%s".format(
            laboratoryVo.deptName.ifNullOrEmpty(),
            laboratoryVo.adminName.ifNullOrEmpty(),
            laboratoryVo.adminPhone.ifNullOrEmpty()
        )

        // 底部信息栏
        if (laboratoryVo.specialClassify.isNullOrEmpty()) {
            viewBinding.specialFlipper.visibility = View.INVISIBLE
        } else {
            viewBinding.specialFlipper.visibility = View.VISIBLE
            val adapter = SimpleFlipperAdapter(data = laboratoryVo.specialClassify)
            viewBinding.specialFlipper.adapter = adapter
            viewBinding.specialFlipper.flipInterval = 5000
            viewBinding.specialFlipper.setInAnimation(context, R.animator.anim_in)
            viewBinding.specialFlipper.setOutAnimation(context, R.animator.anim_out)
            viewBinding.specialFlipper.startFlipping()
        }

        // 安全须知
        val safeDataIdx = findSafeInfoIdx(laboratoryVo.safeClassifyList)
        if (-1 != safeDataIdx) {
            val safeData = laboratoryVo.safeClassifyList!![safeDataIdx]
            viewBinding.header.text = safeData.classifyName
            viewBinding.header.setBackgroundColor(
                try {
                    Color.parseColor(safeData.showColour)
                } catch (e: Exception) {
                    Color.parseColor("#15CA48")
                }
            )
            viewBinding.hazardCategory.removeAllViews()
            safeData.classifyList?.forEachIndexed { index, item ->
                val textView =
                    TextView(ContextThemeWrapper(context, R.style.SafetyBoardContentParent_Black))
                textView.text = "%d. %s".format(index + 1, item)
                viewBinding.hazardCategory.addView(textView)
            }
        }

        val simpleData =
            laboratoryVo.safeClassifyList?.filterIndexed { index, _ -> index != safeDataIdx }
        viewBinding.content.layoutManager =
//            NoScrollGridLayoutManager(requireActivity(), 2)
            GridLayoutManager(requireContext(), 2)
        val decor = GridSpacingItemDecoration(
            2,
            Tool.INSTANCE.dip2px(2f),
            Tool.INSTANCE.dip2px(2f),
            false
        ).apply {
            setDrawable(
                ContextCompat.getDrawable(
                    requireActivity(),
                    R.drawable.shape_grid_item_divider
                )!!
            )
        }
        viewBinding.content.addItemDecoration(decor)
        val adapter = SubSafeAdapter(R.style.SafetyBoardContent_Black)
        viewBinding.content.adapter = adapter
        // 危险类别、防护重点
        adapter.setNewInstance(simpleData?.toMutableList())
        adapter.setEmptyView(R.layout.view_list_empty)
    }

    private fun findSafeInfoIdx(source: List<SafeClassify>?): Int {
//        val index = findSafeInfoIdx(source) { 1 == it.classifyType && "安全须知" == it.classifyName }
//        return if (-1 != index) index else findSafeInfoIdx(source) { 1 == it.classifyType }
        return findSafeInfoIdx(source) { 1 == it.classifyType }
    }

    private fun findSafeInfoIdx(
        source: List<SafeClassify>?,
        block: (item: SafeClassify) -> Boolean
    ): Int {
        return source?.run {
            forEachIndexed { index, item ->
                if (block.invoke(item)) return@run index
            }
            -1
        } ?: -1
    }

}

private class SubSafeAdapter(private val themeResId: Int) :
    BaseDelegateMultiAdapter<SafeClassify, BaseViewHolder>() {

    companion object {
        const val TYPE_TEXT = 1
        const val TYPE_IMAGE = 2
    }

    init {
        setMultiTypeDelegate(object : BaseMultiTypeDelegate<SafeClassify>() {

            override fun getItemType(data: List<SafeClassify>, position: Int): Int {
                // 分类类型 1-文字 2-图片
                return data[position].classifyType
            }
        })
        getMultiTypeDelegate()!!
            .addItemType(TYPE_TEXT, R.layout.item_sub_safe_text)
            .addItemType(TYPE_IMAGE, R.layout.item_sub_safe_image)
    }

    override fun convert(holder: BaseViewHolder, item: SafeClassify) {
        when (holder.itemViewType) {
            TYPE_TEXT -> convertTypeText(holder, item)
            TYPE_IMAGE -> convertTypeImage(holder, item)
        }
    }

    private fun convertTypeText(holder: BaseViewHolder, item: SafeClassify) {
        // 主要危险类别、风险防控措施、灭火要点
        val headerView = holder.getView<TextView>(R.id.header)
        headerView.text = item.classifyName
        headerView.setBackgroundColor(generateHeaderBackground(item.showColour))

        val containerView = holder.getView<LinearLayout>(R.id.hazardCategory)
        containerView.removeAllViews()
        item.classifyList?.forEach {
            val textView = TextView(
                androidx.appcompat.view.ContextThemeWrapper(
                    context,
                    themeResId
                )
            )
            textView.text = it
            containerView.addView(textView)
        }
    }

    private fun convertTypeImage(holder: BaseViewHolder, item: SafeClassify) {
        val headerView = holder.getView<TextView>(R.id.header)
        headerView.text = item.classifyName
        headerView.setBackgroundColor(generateHeaderBackground(item.showColour))

        val containerView = holder.getView<FlowLayout>(R.id.outfire)
        containerView.removeAllViews()
        containerView.post {
            item.classifyList?.forEach { iconUrl ->
                val width = containerView.width / 4
                val height = containerView.height / 3
                val layoutParams = ViewGroup.MarginLayoutParams(width, height)
                val imageView = ImageView(context)
                Glide.with(context)
                    .load(iconUrl)
                    .into(imageView)
                containerView.addView(imageView, layoutParams)
            }
        }
    }

    private fun generateHeaderBackground(color: String): Int {
        return try {
            Color.parseColor(color)
        } catch (e: Exception) {
            Color.parseColor("#15CA48")
        }
    }

}