package com.base.filerecoveryrecyclebin.activity.junkclean

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.filerecoveryrecyclebin.BuildConfig
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.ResultActivity
import com.base.filerecoveryrecyclebin.ads.admob.AdmobInterstitialUtils
import com.base.filerecoveryrecyclebin.bean.ChildBean
import com.base.filerecoveryrecyclebin.bean.ConstObject.JUNK_CLEANER
import com.base.filerecoveryrecyclebin.bean.ParentBean
import com.base.filerecoveryrecyclebin.databinding.ActivityLayoutCleanJunkBinding
import com.base.filerecoveryrecyclebin.databinding.ItemChildBinding
import com.base.filerecoveryrecyclebin.databinding.ItemParentBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.utils.BarUtils
import com.base.filerecoveryrecyclebin.utils.MediaStoreUtils
import com.base.filerecoveryrecyclebin.view.DialogViews.showExitFunctionDialog
import pokercc.android.expandablerecyclerview.ExpandableAdapter
import kotlin.random.Random

/**
 * 清理数据获取页面
 */
class CleanJunkActivity : BaseActivity<ActivityLayoutCleanJunkBinding>() {

    private val parentList by lazy {
        mutableListOf(
            ParentBean(
                title = "Useless installation package",
                childItem = child3,
                parentSize = sizes[0],
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Temp File",
                childItem = child4,
                parentSize = sizes[1],
                isParentSelected = true,
                expanded = false
            ),
            ParentBean(
                title = "Log File",
                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.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
//        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        setAdapter()
    }

    override fun initListener() {
        binding.idJunksBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showExitFunctionDialog {
                    if (it) {
                        AdmobInterstitialUtils.showInterstitialAd(this@CleanJunkActivity) {
                            finishToMain()
                        }
                    } else {
                        finishToMain()
                    }
                }
            }

        })
        binding.idClBtn.setOnClickListener {
            if (binding.idClBtn.text == "Got it") {
                startActivity(Intent(this@CleanJunkActivity, ResultActivity::class.java).apply {
                    putExtra("clean_size", JUNK_CLEANER)
                    putExtra("from", 0)
                })
            } else {
                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() {

        val apk = MediaStoreUtils.queryFiles(this, MediaStoreUtils.FileType.APK) ?: listOf()
        apk.forEach { l ->
            sizes[0] += l.size
            val bean = ChildBean(R.mipmap.apk, l.name, l.path, l.size)
            child3.add(bean)
        }
//        testApk()
        scanCount += 1
        updateSize(doneIndex = 0)


        val temp = MediaStoreUtils.queryFiles(this, MediaStoreUtils.FileType.TMP) ?: listOf()
        temp.forEach { l ->
            sizes[1] += l.size
            val bean = ChildBean(null, l.name, l.path, l.size)
            child4.add(bean)
        }
//        testTemp()
        scanCount += 1
        updateSize(doneIndex = 1)

        val log = MediaStoreUtils.queryFiles(this, MediaStoreUtils.FileType.LOG) ?: listOf()
        log.forEach { l ->
            sizes[2] += l.size
            val bean = ChildBean(null, l.name, l.path, l.size)
            child5.add(bean)
        }
//        testLog()
        scanCount += 2
        updateSize(doneIndex = 2)
    }

    private fun testLog() {
        if (BuildConfig.DEBUG) {
            repeat(5) {
                sizes[2] += Random.nextLong()
                val bean = ChildBean(null, "log", "", Random.nextLong())
                child5.add(bean)
            }
        }
    }

    private fun testTemp() {
        if (BuildConfig.DEBUG) {
            repeat(5) {
                sizes[1] += Random.nextLong()
                val bean = ChildBean(null, "temp", "", Random.nextLong())
                child4.add(bean)
            }
        }
    }

    private fun testApk() {
        if (BuildConfig.DEBUG) {
            repeat(5) {
                sizes[0] += Random.nextLong(1500)
                val bean = ChildBean(R.mipmap.apk, "apk", "", Random.nextLong())
                child3.add(bean)
            }
        }
    }

    @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) {
            binding.idClBtn.text = "Got it"
        } else {
            binding.idClBtn.text = "Clean up ${selectSize.toFormatSize(1)}"
        }
        binding.idClBtn.isEnabled = true
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun addData(index: Int) {
        if (parentList.isNotEmpty()) {
            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 })
        }
    }

    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>() {
            var animators = mutableMapOf<Int, ValueAnimator>()

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

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

            override fun onViewDetachedFromWindow(holder: ViewHolder) {
                super.onViewDetachedFromWindow(holder)
                animators[holder.adapterPosition]?.pause()
            }

            override fun onViewAttachedToWindow(holder: ViewHolder) {
                super.onViewAttachedToWindow(holder)
                animators[holder.adapterPosition]?.resume()
            }

            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.zhankai)
                } else {
                    viewHolder.binding.idXiala.setImageResource(R.mipmap.shouqi)
                }
                if (parentType.isfinish) {
                    viewHolder.binding.idImgLoad.isVisible = false
                    viewHolder.binding.idImgChoose.isVisible = true
                } else {

                    val animator =
                        animators[groupPosition] ?: ValueAnimator.ofFloat(0f, 360f).apply {
                            duration = 1000
                            repeatMode = ValueAnimator.RESTART
                            repeatCount = ValueAnimator.INFINITE
                            interpolator = LinearInterpolator()
                            addUpdateListener {
                                holder.binding.idImgLoad.rotation = it.animatedValue as Float
                            }
                            start()
                            animators[groupPosition] = this
                        }
                    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 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)
                        } else {
                            viewHolder.binding.idImgIcon.setImageResource(R.mipmap.apk)
                        }
                    }

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

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

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

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        for (animator in mAdapter.animators.values) {
            animator.cancel()
        }
    }
}