package com.base.filerecoveryrecyclebin.adapter

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.core.view.isVisible
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.bean.ChildBean
import com.base.filerecoveryrecyclebin.bean.ParentBean
import com.base.filerecoveryrecyclebin.databinding.ItemChildBinding
import com.base.filerecoveryrecyclebin.databinding.ItemParentBinding
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.utils.LogEx
import pokercc.android.expandablerecyclerview.ExpandableAdapter

class JunkExpandAdapter(private val chooseAction: (size: Long) -> Unit) : ExpandableAdapter<ExpandableAdapter.ViewHolder>() {

    private val TAG = "JunkExpandAdapter"

    private val parentBeanList by lazy {
        mutableListOf(
            ParentBean(
                title = "Residual file",
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Useless installation package",
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Temp File",
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Log File",
                isParentSelected = true,
                expanded = false
            )
        )
    }
    var animators = mutableMapOf<Int, ValueAnimator>()

    inner class ChildViewHolder(val binding: ItemChildBinding) : ViewHolder(binding.root)

    inner class ParentViewHolder(val binding: ItemParentBinding) : ViewHolder(binding.root)

    override fun getChildCount(groupPosition: Int): Int {
        return parentBeanList[groupPosition].childItem.size
    }

    override fun getGroupCount(): Int {
        return parentBeanList.size
    }

    override fun onCreateChildViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = ItemChildBinding.inflate(inflater, viewGroup, false)
        return ChildViewHolder(binding)
    }

    override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = ItemParentBinding.inflate(inflater, viewGroup, false)
        return ParentViewHolder(binding)
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onBindGroupViewHolder(holder: ViewHolder, groupPosition: Int, expand: Boolean, payloads: List<Any>) {
        val viewHolder = holder as? ParentViewHolder ?: return
        val parentBean = parentBeanList[groupPosition]

        viewHolder.binding.idTypeName.text = parentBean.title
        parentBean.expanded = expand

        if (parentBean.expanded) {
            viewHolder.binding.idXiala.setImageResource(R.mipmap.zhankai)
        } else {
            viewHolder.binding.idXiala.setImageResource(R.mipmap.shouqi)
        }
        if (parentBean.title == "Residual file") {
            viewHolder.binding.idTypeSize.text = parentBean.childItem.size.toString() + " items"
        } else {
            viewHolder.binding.idTypeSize.text = parentBean.parentSize.toFormatSize(1)
        }

        viewHolder.binding.idXiala.isVisible = true
        viewHolder.binding.idImgChoose.isSelected = parentBean.isParentSelected

        bindParentAnimation(parentBean, groupPosition, viewHolder)

        if (parentBean.childItem.isEmpty()) {
            viewHolder.binding.idImgChoose.setOnClickListener { }
        } else {
            viewHolder.binding.idImgChoose.setOnClickListener {
                viewHolder.binding.idImgChoose.isSelected = !viewHolder.binding.idImgChoose.isSelected
                parentBean.isParentSelected = viewHolder.binding.idImgChoose.isSelected

                parentBean.childItem.forEach {
                    it.isChildSelected = parentBean.isParentSelected
                }
                notifyDataSetChanged()

                chooseSizeChange()
            }
        }

    }

    override fun onGroupViewHolderExpandChange(holder: ViewHolder, groupPosition: Int, animDuration: Long, expand: Boolean) {}

    private fun chooseSizeChange() {
        val selectSize = parentBeanList.sumOf { it.childItem.filter { it.isChildSelected }.sumOf { it.childSize } }
        chooseAction.invoke(selectSize)
    }

    fun getChoosePath(): List<ChildBean> {
        return parentBeanList.flatMap { it.childItem }.filter { it.isChildSelected }
    }

    fun getAllChildItemCount(): Int {
        return parentBeanList.flatMap { it.childItem }.size
    }

    private fun bindParentAnimation(parentBean: ParentBean, groupPosition: Int, viewHolder: ParentViewHolder) {
        if (parentBean.isfinish) {
            viewHolder.binding.idImgLoad.isVisible = false
            viewHolder.binding.idImgChoose.isVisible = true
            animators[groupPosition]?.cancel()
        } else {
            LogEx.logDebug(TAG, "play parent ValueAnimator")
            animators[groupPosition] ?: ValueAnimator.ofFloat(0f, 360f).apply {
                duration = 1000
                repeatMode = ValueAnimator.RESTART
                repeatCount = ValueAnimator.INFINITE
                interpolator = LinearInterpolator()
                addUpdateListener {
                    viewHolder.binding.idImgLoad.rotation = it.animatedValue as Float
                }
                start()
                animators[groupPosition] = this
            }
            viewHolder.binding.idImgLoad.isVisible = true
            viewHolder.binding.idImgChoose.isVisible = false
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onBindChildViewHolder(holder: ViewHolder, groupPosition: Int, childPosition: Int, payloads: List<Any>) {
        val viewHolder = holder as? ChildViewHolder ?: return
        val childBean = parentBeanList[groupPosition].childItem[childPosition]
        val parentBean = parentBeanList[groupPosition]
        val context = holder.itemView.context

        viewHolder.binding.idTvAppName.text = childBean.childname
        viewHolder.binding.idImgSelect.isSelected = childBean.isChildSelected
        viewHolder.binding.idTvSize.text = childBean.childSize.toFormatSize()

        when (groupPosition) {
            0 -> {
                holder.binding.idImgIcon.setImageResource(R.mipmap.kongwenjian)
                viewHolder.binding.idTvAppName.text = childBean.chilepath
            }

            1 -> {
                try {
                    val apkFilePath = childBean.chilepath // 替换成您的APK文件路径
                    val packageInfo =
                        context.packageManager.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES)
                    if (packageInfo != null) {
                        val applicationInfo = packageInfo.applicationInfo
                        val appIcon: Drawable = context.packageManager.getApplicationIcon(applicationInfo)
                        viewHolder.binding.idImgIcon.setImageDrawable(appIcon)
                    } else {
                        holder.binding.idImgIcon.setImageResource(R.mipmap.apk)
                    }
                } catch (e: Exception) {
                    holder.binding.idImgIcon.setImageResource(R.mipmap.apk)
                }
            }

            2 -> {
                holder.binding.idImgIcon.setImageResource(R.mipmap.temp_clean)
            }

            3 -> {
                holder.binding.idImgIcon.setImageResource(R.mipmap.log_clean)
            }
        }


        viewHolder.itemView.setOnClickListener {
            viewHolder.binding.idImgSelect.isSelected = !viewHolder.binding.idImgSelect.isSelected
            childBean.isChildSelected = viewHolder.binding.idImgSelect.isSelected
            parentBean.isParentSelected = parentBean.childItem.all { it.isChildSelected }
            notifyDataSetChanged()
            chooseSizeChange()
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    fun addChildData(position: Int, childBeanList: List<ChildBean>) {
        val parentBean = parentBeanList[position]
        parentBean.isfinish = true
        parentBean.isParentSelected = true
        parentBean.childItem.addAll(childBeanList)
        parentBean.parentSize = childBeanList.sumOf { it.childSize }
        LogEx.logDebug(TAG, "addChildData parentBean=$parentBean")
        notifyDataSetChanged()
        chooseSizeChange()
    }

}