package com.base.superfilemanager.activity

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.base.superfilemanager.R
import com.base.superfilemanager.bean.ChildBean
import com.base.superfilemanager.bean.ParentBean
import com.base.superfilemanager.databinding.ActivityLayoutCleanJunkBinding
import com.base.superfilemanager.databinding.ItemChildBinding
import com.base.superfilemanager.databinding.ItemParentBinding
import com.base.superfilemanager.helps.BaseActivity
import com.base.superfilemanager.helps.FileHelps
import com.base.superfilemanager.helps.KotlinExt.toFormatSize
import com.base.superfilemanager.helps.ads.AdmobUtils
import com.base.superfilemanager.view.AFunOb
import pokercc.android.expandablerecyclerview.ExpandableAdapter

class CleanJunkActivity : BaseActivity<ActivityLayoutCleanJunkBinding>() {
    override val isLightMode = true
    private val parentList by lazy {
        mutableListOf(
            ParentBean(
                title = "Useless installation package",
                childItem = child3,
                parentSize = sizes[0],
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Residual cache junk",
                childItem = child4,
                parentSize = sizes[1],
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Clean up more",
                childItem = child5,
                parentSize = sizes[2],
                isParentSelected = true,
                expanded = false
            )
        )
    }

    //    private val child1 = ArrayList<ChildBean>()
//    private val child2 = ArrayList<ChildBean>()
    private val child3 = ArrayList<ChildBean>()
    private val child4 = ArrayList<ChildBean>()
    private val child5 = ArrayList<ChildBean>()
    private val sizes = MutableList(3) { 0L }
    private var ScanCount = 0
    private val selectList = mutableListOf<String>()
    private var selectSize = 0L
    override val binding: ActivityLayoutCleanJunkBinding by lazy {
        ActivityLayoutCleanJunkBinding.inflate(layoutInflater)
    }

    override fun initView() {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.ll.updatePadding(top = BarUtils.getStatusBarHeight())
        setAdapter()
        binding.idJunksBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finishToMain()
            }

        })
        binding.idClBtn.setOnClickListener {
            startActivity(
                Intent(this, CleaningActivity::class.java)
                    .putExtra("list", selectList.toTypedArray())
                    .putExtra("size", selectSize)
            )
            finish()
        }
    }

    private fun setAdapter() {
        binding.idExRl.adapter = mAdapter
        binding.idExRl.layoutManager = LinearLayoutManager(this)
        scanJunk()
    }

    private fun scanJunk() {
        FileHelps.getFileList({
            FileHelps.fileList.toList().let { it ->
                if (it.isNotEmpty()) {
                    child3.clear()
                    child4.clear()
                    child5.clear()
                    sizes[0] = 0
                    sizes[1] = 0
                    sizes[2] = 0
                    val a = it.filter { it.isApk() }
                    val halfSize = if (a.size % 2 == 1) a.size / 2 + 1 else a.size / 2
                    val firstHalf = a.subList(0, halfSize)
                    firstHalf.forEach { l ->
                        sizes[0] += l.size
                        //  junkList.add(p0.path)
                        val bean = ChildBean(R.mipmap.apk, l.name, l.path, l.size)
                        child3.add(bean)
                    }
                    ScanCount += 1
                    updateSize(doneIndex = 0)
//                    mData.addAll(it)
                    val b = it.filter { it.isJunk() }
                    val bhalfSize = if (b.size % 2 == 1) b.size / 2 + 1 else b.size / 2
                    val bfirstHalf = b.subList(0, bhalfSize)
                    bfirstHalf.forEach { l ->
                        sizes[1] += l.size
                        //  junkList.add(p0.path)
                        val bean = ChildBean(null, l.name, l.path, l.size)
                        child4.add(bean)
                    }
                    ScanCount += 1
                    updateSize(doneIndex = 1)
                    val c = it.filter { it.isOtherTrash() }
                    val chalfSize = if (c.size % 2 == 1) c.size / 2 + 1 else c.size / 2
                    val cfirstHalf = c.subList(0, chalfSize)
                    cfirstHalf.forEach { l ->
                        sizes[2] += l.size
                        //  junkList.add(p0.path)
                        val bean = ChildBean(null, l.name, l.path, l.size)
                        child5.add(bean)
                    }
                    ScanCount += 2
                    updateSize(doneIndex = 2)
                }
            }
        }, {
//            if (mData.isEmpty()) {
//
//
//            }
            Log.e("MXL", "scanJunk: " + "没扫到")

        })
    }

    @SuppressLint("SetTextI18n")
    private fun updateSize(doneIndex: Int = -1) {

        addData(index = doneIndex)
        val split = sizes.sum().toFormatSize(1).split(' ')
        binding.idKeCl.text = split[0]
        binding.idSizeUnit.text = split[1]
        if (ScanCount >= 3) {
            selectList.clear()
            selectSize = 0L
            for (i in parentList.indices) {
                if (parentList[i].childItem.isNotEmpty()) {
                    val childsize = parentList[i].childItem.filter {
                        it.isChildSelected
                    }.sumOf {
                        it.childSize
                    }
                    for (a in parentList[i].childItem) {
                        if (a.isChildSelected) {
                            if (a.pathList?.isNotEmpty() == true) {
                                for (o in a.pathList!!) {
                                    selectList.add(o)
                                }
                            }
                        }
                    }
                    selectSize += childsize
                } else {
                    if (parentList[i].isParentSelected) {
                        selectSize += parentList[i].parentSize
                    }
                }

            }
            parentList.forEach { parent ->
                selectList.addAll(parent.childItem.filter {
                    it.isChildSelected
                }.map { it.chilepath })
            }
        }
        binding.idClBtn.isVisible = ScanCount >= 3
        binding.idClBtn.isEnabled = sizes.sum() > 0
        if (ScanCount >= 3 && sizes.sum().toInt() == 0) {
            AdmobUtils.showInterstitialAd(this) {
                startActivity(
                    Intent(this, ResultActivity::class.java).putExtra(
                        "from",
                        AFunOb.JUNK_CLEANER
                    ).putExtra("clean_size", 0L)
                )
                finish()
            }
        }
        binding.idClBtn.text = "Clean up ${selectSize.toFormatSize(1)}"
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun addData(index: Int) {
        if (parentList.isNotEmpty()) {
            Log.e("MXL", "addData: $index")
            parentList[index].isfinish = true
            parentList[index].parentSize = sizes[index]
            mAdapter.notifyDataSetChanged()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateView() {
        selectList.clear()
        var allSize = 0L
        for (i in parentList.indices) {
            if (parentList[i].childItem.isNotEmpty()) {
                val childSize = parentList[i].childItem.filter {
                    it.isChildSelected
                }.sumOf {
                    it.childSize
                }
                for (a in parentList[i].childItem) {
                    if (a.isChildSelected) {
                        if (a.pathList?.isNotEmpty() == true) {
                            for (o in a.pathList!!) {
                                selectList.add(o)
                            }
                        }
                    }
                }
                allSize += childSize
            } else {
                if (parentList[i].isParentSelected) {
                    allSize += parentList[i].parentSize
                }
            }

        }
        selectSize = allSize
        binding.idClBtn.text = "Clean up ${allSize.toFormatSize()}"
        binding.idClBtn.isEnabled = allSize > 0
        parentList.forEach { parent ->
            selectList.addAll(parent.childItem.filter {
                it.isChildSelected
            }.map { it.chilepath })
        }
//        for (item in parentList) {
//            if (item.isParentSelected) {
//                Log.e("MXL", "updateView: " + item)
//            }
//        }

    }

    private val mAdapter by lazy {
        class ParentViewHolder(val binding: ItemParentBinding) :
            ExpandableAdapter.ViewHolder(binding.root)

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

        object : ExpandableAdapter<ExpandableAdapter.ViewHolder>() {
            override fun getChildCount(groupPosition: Int): Int {
                return parentList[groupPosition].childItem.size
            }

            override fun getGroupCount(): Int {
                return parentList.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)
            }

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

            }

            @SuppressLint("NotifyDataSetChanged")
            override fun onBindGroupViewHolder(
                holder: ViewHolder,
                groupPosition: Int,
                expand: Boolean,
                payloads: List<Any>
            ) {
                val viewHolder = holder as? ParentViewHolder ?: return
                val parentType = parentList[groupPosition]
                viewHolder.binding.idTypeName.text = parentType.title
                parentType.expanded = expand
                if (parentType.expanded) {
                    viewHolder.binding.idXiala.setImageResource(R.mipmap.shouqi)
                } else {
                    viewHolder.binding.idXiala.setImageResource(R.mipmap.zhankai)
                }
                if (parentType.isfinish) {
                    viewHolder.binding.idImgLoad.isVisible = false
                    viewHolder.binding.idImgChoose.isVisible = true
                } else {
                    ValueAnimator.ofFloat(0f, 360f).run {
                        duration = 1000
                        repeatMode = ValueAnimator.RESTART
                        repeatCount = ValueAnimator.INFINITE
                        interpolator = LinearInterpolator()
                        addUpdateListener {
                            viewHolder.binding.idImgLoad.rotation = it.animatedValue as Float
                        }
                        start()
                    }
                    viewHolder.binding.idImgLoad.isVisible = true
                    viewHolder.binding.idImgChoose.isVisible = false
                }
                viewHolder.binding.idTypeSize.text = parentType.parentSize.toFormatSize(1)
                viewHolder.binding.idXiala.isVisible = parentType.childItem.isNotEmpty()
                viewHolder.binding.idImgChoose.isSelected = parentType.isParentSelected

                viewHolder.binding.idImgChoose.setOnClickListener {
                    viewHolder.binding.idImgChoose.isSelected =
                        !viewHolder.binding.idImgChoose.isSelected
                    parentType.isParentSelected = !parentType.isParentSelected
                    if (parentType.isParentSelected) {
                        for (app in parentType.childItem) {
                            app.isChildSelected = true
                            notifyDataSetChanged()
                        }
                    } else {
                        for (app in parentType.childItem) {
                            app.isChildSelected = false
                            notifyDataSetChanged()
                        }
                    }
                    updateView()
                }
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun onBindChildViewHolder(
                holder: ViewHolder,
                groupPosition: Int,
                childPosition: Int,
                payloads: List<Any>
            ) {
                val viewHolder = holder as? ChildViewHolder ?: return
                val childType = parentList[groupPosition].childItem[childPosition]
                when (groupPosition) {
                    0 -> {
//                val c = ConfigHelper.appList?.firstOrNull {
//                    it.name == childType.childname
//                }
//                viewHolder.binding.idImgIcon.setImageDrawable(c?.icon)
                        val packageManager: PackageManager = this@CleanJunkActivity.packageManager
                        val apkFilePath = childType.chilepath // 替换成您的APK文件路径
                        val packageInfo =
                            packageManager.getPackageArchiveInfo(
                                apkFilePath,
                                PackageManager.GET_ACTIVITIES
                            )
                        if (packageInfo != null) {
                            val applicationInfo = packageInfo.applicationInfo
                            val appIcon = packageManager.getApplicationIcon(applicationInfo)
                            viewHolder.binding.idImgIcon.setImageDrawable(appIcon)
                        }
                    }

                    1 -> {
                        viewHolder.binding.idImgIcon.setImageResource(R.mipmap.junk)
                    }

                    2 -> {
                        viewHolder.binding.idImgIcon.setImageResource(R.mipmap.qita)
                    }

                    3 -> {

                    }

                    4 -> {

                    }
                }

                viewHolder.binding.idTvAppName.text = childType.childname
                viewHolder.binding.idImgSelect.isSelected = childType.isChildSelected
                viewHolder.binding.idTvSize.text = childType.childSize.toFormatSize()
                viewHolder.itemView.setOnClickListener {
                    when (childPosition) {
                        childPosition -> {
                            viewHolder.binding.idImgSelect.isSelected =
                                !viewHolder.binding.idImgSelect.isSelected
                            childType.isChildSelected = !childType.isChildSelected
                            if (!childType.isChildSelected) {
                                parentList[groupPosition].isParentSelected = false
                                notifyDataSetChanged()
                            }
                            updateView()
                        }
                    }
                }
            }

        }

    }
}