package com.dlc.eboard.ui.home

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.BulletSpan
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.text.style.StyleSpan
import android.util.Log
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.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.FragmentLabBasicBinding
import com.dlc.eboard.sp.DeviceSp
import com.dlc.eboard.ui.common.SimpleFlipperAdapter
import com.rc.core.log.RcLog
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.core.ui.widget.decoration.GridSpacingItemDecoration
import com.rc.core.util.DeviceUtils
import com.rc.core.util.ifNullOrEmpty
import com.rc.httpcore.vo.response.LaboratoryVo
import com.rc.httpcore.vo.response.SafeClassify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

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

    companion object {
        const val TAG = "LabBasicFragment"

        fun newInstance() = LabBasicFragment()
    }

    private lateinit var handler: Handler
//    private val refreshInterval = 5000L // 刷新间隔，单位为毫秒
    private val refreshInterval =2 * 60 * 1000 // 刷新间隔，单位为毫秒  两分钟

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

    override fun initViews(savedInstanceState: Bundle?) {
        val laboratoryVo = DeviceSp.loadLaboratoryVo(requireContext())
        if (null == laboratoryVo) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(requireActivity())
            return
        }
        // 初始化Handler
        initLaboratoryInfo(laboratoryVo)
        handler = Handler(Looper.getMainLooper())

    }

    private var adapter: SubSafeAdapter? = null
    private fun initLaboratoryInfo(laboratoryVo: LaboratoryVo) {
        val dangerColor = try {
            Color.parseColor(laboratoryVo.dangerColor)
        } catch (e: Exception) {
            Color.parseColor("#15CA48")
        }
        val bgDrawable = GradientDrawable()
        bgDrawable.cornerRadius = DeviceUtils.dip2px(requireContext(), 31.0f).toFloat()
        bgDrawable.setSize(
            DeviceUtils.dip2px(requireContext(), 195.0f),
            DeviceUtils.dip2px(requireContext(), 62.0f)
        )
        bgDrawable.setColor(dangerColor)
        viewBinding.labLevel.background = bgDrawable
        // 特种设备类  |  二级
        viewBinding.labLevelInfo.text = "%s  |  %s".format(
            laboratoryVo.dangerName.ifNullOrEmpty(),
            laboratoryVo.dangerLevel.ifNullOrEmpty()
        )
        viewBinding.subjectName.text = laboratoryVo.address
        viewBinding.deptName.text = "责任单位：%s".format(laboratoryVo.deptName.ifNullOrEmpty())

        // 二维码
        GlobalScope.launch(Dispatchers.Main) {
            val bitmap = withContext(Dispatchers.IO) {
                QRCodeEncoder.syncEncodeQRCode(
                    laboratoryVo.qrCodeUrl,
                    BGAQRCodeUtil.dp2px(requireContext(), 150f)
                )
            }
            Glide.with(requireContext())
                .asBitmap()
                .load(bitmap)
                .error(R.mipmap.img_error)
                .into(viewBinding.qrCode)
        }

        // 实验室负责人
        viewBinding.adminUser.text = laboratoryVo.adminUserDesc
        // 安全责任人
        viewBinding.safeUser.text = laboratoryVo.safeUserDesc
        // 底部信息栏
        if (laboratoryVo.specialClassify.isNullOrEmpty()) {
            viewBinding.specialFlipper.visibility = View.GONE
        } else {
            viewBinding.specialFlipper.visibility = View.VISIBLE
            val adapter =
                SimpleFlipperAdapter(Color.parseColor("#FF333333"), 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()
        }


        if (adapter == null) {
            RcLog.info("===========进来了几次1")
            viewBinding.content.layoutManager =
//            StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
                GridLayoutManager(requireContext(), 2)
            val decor = GridSpacingItemDecoration(
                2,
                DeviceUtils.dip2px(requireContext(), 20f),
                DeviceUtils.dip2px(requireContext(), 12f), false
            )
            viewBinding.content.addItemDecoration(decor)
            adapter = SubSafeAdapter(requireActivity(), R.style.SafetyBoardContent_Black)
            viewBinding.content.adapter = adapter
            // 主要危险类别、风险防控措施、灭火要点、安全警示标示

            adapter!!.setNewInstance(laboratoryVo.safeClassifyList)

            adapter!!.setEmptyView(R.layout.view_list_empty)
        } else {
            adapter!!.data = laboratoryVo.safeClassifyList
            adapter!!.notifyDataSetChanged()
        }


    }

    override fun onResume() {
        super.onResume()
        // 开始定时刷新任务
        startRefreshTask()
    }

    override fun onPause() {
        super.onPause()
        // 停止定时刷新任务
        stopRefreshTask()
    }

    private fun startRefreshTask() {
        // 定义刷新任务
        val refreshRunnable = object : Runnable {
            override fun run() {
                // 延迟一段时间后再次执行刷新任务
                val laboratoryVo = DeviceSp.loadLaboratoryVo(requireContext())
                if (null == laboratoryVo) {
                    showToast("暂无实验室信息，即将重新获取")
                    CommonUtils.restartApp(requireActivity())
                    return
                }
                initLaboratoryInfo(laboratoryVo)
//                view?.invalidate()
                handler.postDelayed(this, 2 * 60 * 1000)
            }
        }
        // 开始刷新任务
        handler.postDelayed(refreshRunnable, 2 * 60 * 1000)
    }

    private fun stopRefreshTask() {
        // 移除刷新任务
        handler.removeCallbacksAndMessages(null)
    }


}

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

    var mPosition = -1

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

    private val subSafeStrAdapters = ArrayList<SubSafeStrAdapter>()

    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)
            }

        }


    }


    @SuppressLint("ResourceAsColor", "NewApi")
    private fun convertTypeText(holder: BaseViewHolder, item: SafeClassify) {
        Log.d("当前下标", "  ${holder.adapterPosition}")
        // 主要危险类别、风险防控措施、灭火要点
        val headerView = holder.getView<TextView>(R.id.header)
        headerView.text = item.classifyName
        headerView.background = generateHeaderBackground(item.showColour)
        val rvItem = holder.getView<RecyclerView>(R.id.rv_item)
        val subSafeStrAdapter = SubSafeStrAdapter()//item信息
        rvItem.layoutManager = LinearLayoutManager(ct)
        rvItem.isNestedScrollingEnabled = false
        rvItem.adapter = subSafeStrAdapter
        subSafeStrAdapter.setNewInstance(item.classifyList.toMutableList())
//
//        if (subSafeStrAdapters.size == 3) {
//            Log.d("==========有几条数据","下标 ${holder.adapterPosition}")
//            val rvItem = holder.getView<RecyclerView>(R.id.rv_item)
//            rvItem.layoutManager = LinearLayoutManager(ct)
//            rvItem.isNestedScrollingEnabled = false
//            subSafeStrAdapters[holder.adapterPosition].data=item.classifyList.toMutableList()
//            subSafeStrAdapters[holder.adapterPosition].notifyDataSetChanged()
//        } else {
//            // 主要危险类别、风险防控措施、灭火要点
//            val headerView = holder.getView<TextView>(R.id.header)
//            headerView.text = item.classifyName
//            headerView.background = generateHeaderBackground(item.showColour)
//            val rvItem = holder.getView<RecyclerView>(R.id.rv_item)
//            val subSafeStrAdapter = SubSafeStrAdapter()//item信息
//            rvItem.layoutManager = LinearLayoutManager(ct)
//            rvItem.isNestedScrollingEnabled = false
//            rvItem.adapter = subSafeStrAdapter
//            subSafeStrAdapter.setNewInstance(item.classifyList.toMutableList())
//            subSafeStrAdapters.add(subSafeStrAdapter)
//
//        }


//        item.classifyList?.forEach {
////            val textView = TextView(ContextThemeWrapper(context, themeResId))
//            val textView = TextView(ct)
//            textView.text = "  $it"
////            if (it.startsWith("(")) {
////                textView.text = "  $it"
////            } else {
////                // 在文本前面添加一个黑色圆点
////                val spannableString = SpannableString("● $it")
////
////                // 调整圆点位置稍微往上一点
////                val bulletSpan = BulletSpan(20, Color.BLACK, 10) // 第二个参数是圆点颜色，这里设置为黑色
////                spannableString.setSpan(bulletSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
////
////                // 将 SpannableString 设置到 TextView 中
////                textView.text = spannableString
////                textView.setTextColor(R.color.text_color_3333)
////                // 获取点图标
////                val dotDrawable: Drawable = ct.resources.getDrawable(R.drawable.black_point)
////                dotDrawable.setBounds(0, 0, dotDrawable.intrinsicWidth, dotDrawable.intrinsicHeight)
////                // 创建一个包含点的 SpannableString
////                val dot = SpannableString("• ")
////                dot.setSpan(ImageSpan(dotDrawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
////                val spannableText = SpannableString(it)
////                // 合并两个 SpannableString
////                val builder = SpannableStringBuilder()
////                builder.append(dot)
////                builder.append(spannableText)
////
////                // 设置样式
////                val dotLength = dot.length
////                builder.setSpan(ForegroundColorSpan(Color.RED),
////                    0,
////                    dotLength,
////                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
////                builder.setSpan(StyleSpan(Typeface.BOLD),
////                    0,
////                    dotLength,
////                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
////
////                // 设置到 TextView
////                textView.text = builder
////            }
//
//
//            holder.getView<LinearLayout>(R.id.hazardCategory).addView(textView)
//        }
    }

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


        item.classifyList?.forEach { iconUrl ->
//            val width = context.resources.getDimensionPixelSize(R.dimen.safe_sign_width)
            val width = LinearLayout.LayoutParams.WRAP_CONTENT
            val height = context.resources.getDimensionPixelSize(R.dimen.safe_sign_height)
            val layoutParams = LinearLayout.LayoutParams(width, height)
            val imageView = ImageView(context)
            imageView.scaleType = ImageView.ScaleType.FIT_START
            Glide.with(context)
                .load(iconUrl)
                .into(imageView)

            holder.getView<LinearLayout>(R.id.outfire).addView(imageView, layoutParams)
        }
    }

    private fun generateHeaderBackground(color: String): Drawable {
        return GradientDrawable().apply {
            val topRadius = DeviceUtils.dip2px(context, 11.0f).toFloat()
            cornerRadii = floatArrayOf(topRadius, topRadius, topRadius, topRadius, 0f, 0f, 0f, 0f)
            setColor(
                try {
                    Color.parseColor(color)
                } catch (e: Exception) {
                    Color.parseColor("#15CA48")
                }
            )
        }
    }

}

class SubSafeStrAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.sub_safe_str) {
    override fun convert(holder: BaseViewHolder, item: String) {
        holder.setText(R.id.tvCont, "$item")
    }

}