package aicg.wipf.keyu.bzsb

import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_1_MONTH
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_1_WEEK
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_1_YEAR
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_3_MONTHS
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_6_MONTHS
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_ALL_TIME
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_ALL_TYPES
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_APK
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_ARCHIVES
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_AUDIO
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_DOCUMENT
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_IMAGE
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_OTHER_TYPES
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_SIZE_100_MB
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_SIZE_10_MB
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_SIZE_1_GB
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_SIZE_500_MB
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_SIZE_50_MB
import aicg.wipf.keyu.bzsb.Dtvk.Filter.Companion.KEY_VIDEO
import aicg.wipf.ogbw.ezlb.rgmw.FileBean
import aicg.wipf.rxxn.Ayhm.inflate
import aicg.wipf.rxxn.Xbey.showFileDeleteDialog
import aicg.wipf.rxxn.Zbyi.showFileDetailDialog
import aicg.wipf.tzxq.Sesw
import aicg.wipf.vzuj.Bnpt
import aicg.wipf.vzuj.Hqlm
import aicg.wipf.vzuj.Kmqp.setTrackedOnClickListener
import aicg.wipf.vzuj.Kmqp.string
import aicg.wipf.vzuj.Sjdo
import aicg.wipf.vzuj.Tgsx
import aicg.wipf.vzuj.bcxo.Fnpc
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Environment
import android.text.format.Formatter
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.activity.addCallback
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.test.basd.smartjunkcleaner.R
import com.test.basd.smartjunkcleaner.databinding.DpqfyeBinding
import com.test.basd.smartjunkcleaner.databinding.KvhpuyBinding
import com.test.basd.smartjunkcleaner.databinding.LeotttBinding
import java.io.File

/**
 * 大文件清理
 */
class Dtvk : Hqlm<KvhpuyBinding>() {
    override val isLightMode = true
    private val TAG = R.string.ޥޔޤލއ_D.string()
    private val listTypes = listOf(
        Filter(KEY_ALL_TYPES, true), Filter(KEY_IMAGE), Filter(KEY_VIDEO), Filter(KEY_AUDIO), Filter(KEY_DOCUMENT), Filter(KEY_ARCHIVES), Filter(KEY_APK), Filter(KEY_OTHER_TYPES), )

    private val listSizes = listOf(
        Filter(KEY_SIZE_10_MB, true), Filter(KEY_SIZE_50_MB), Filter(KEY_SIZE_100_MB), Filter(KEY_SIZE_500_MB), Filter(KEY_SIZE_1_GB), )

    private val listTimes = listOf(
        Filter(KEY_ALL_TIME, true), Filter(KEY_1_WEEK), Filter(KEY_1_MONTH), Filter(KEY_3_MONTHS), Filter(KEY_6_MONTHS), Filter(KEY_1_YEAR), )

    private val largeFileList = arrayListOf<FileBean>()
    private lateinit var adapter: Sesw

    private var fileType = KEY_ALL_TYPES
    private var filterSize = KEY_SIZE_10_MB
    private var filterTime = KEY_ALL_TIME

    override val binding: KvhpuyBinding by lazy {
        KvhpuyBinding.inflate(layoutInflater)
    }

    override fun initView() {
        binding.jxzsjxc.isEnabled = false
        binding.mlbrdtp.isEnabled = false
        binding.zpeiolu.isEnabled = false

        adapter = Sesw(
            itemClick = { fileBean ->
                this.showFileDetailDialog(fileBean)
            }, selectClick = { files ->
                if (files.isNotEmpty()) {
                    binding.zrlichi.background = ContextCompat.getDrawable(this, R.drawable.gsiqnvjk)
                    binding.zrlichi.isEnabled = true
                    val size = files.sumOf { it.size }
                    val sizeF = Formatter.formatFileSize(this, size)
                    binding.zrlichi.text = R.string.ލޣޥޠޕ_D.string((sizeF).toString())
                } else {
                    binding.zrlichi.background = ContextCompat.getDrawable(this, R.drawable.nhoyutfo)
                    binding.zrlichi.isEnabled = false
                    binding.zrlichi.text = R.string.ޤޙމޓޘ_D.string()
                }
            }
        )
        binding.pvaiyzw.adapter = adapter

        binding.zrlichi.setTrackedOnClickListener {
            this.showFileDeleteDialog {
                val deleteList = arrayListOf<FileBean>()
                adapter.getSelectData().forEach {
                    val file = File(it.path)
                    try {
                        if (file.delete()) {
                            deleteList.add(it)
                        }
                    } catch (e: Exception) {
                    }
                }
                largeFileList.removeAll(deleteList.toSet())
                adapter.removeData(deleteList)
                binding.zrlichi.background = ContextCompat.getDrawable(this, R.drawable.nhoyutfo)
                binding.zrlichi.isEnabled = false
                binding.zrlichi.text = R.string.ޤޙމޓޘ_D.string()
            }
        }

        binding.jxzsjxc.setTrackedOnClickListener {
            showPopupWindow(binding.oirhned, 0, listTypes)
        }
        binding.mlbrdtp.setTrackedOnClickListener {
            showPopupWindow(binding.oirhned, 1, listSizes)
        }
        binding.zpeiolu.setTrackedOnClickListener {
            showPopupWindow(binding.oirhned, 2, listTimes)
        }
        binding.rvuxtkj.setTrackedOnClickListener {
            Fnpc.showInterstitialAd(this) {
                finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            Fnpc.showInterstitialAd(this@Dtvk) {
                finishToMain()
            }
        }

        binding.jqdzhtd.text = fileType
        binding.nimczzt.text = filterSize
        binding.oyfpmjp.text = filterTime

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            PermissionUtils.isGranted(PermissionConstants.STORAGE)
        }
        if (flag) {
            isplay += 1
            playLottie()
        }
        checkPermission()
    }

    var isplay = 0
    override fun onPermissionsResult(isGranted: Boolean) {
        super.onPermissionsResult(isGranted)
        if (isGranted) {
            isplay += 1
            if (isplay == 1) {
                playLottie()
            }
            initList()
        } else {
            finishToMain()
        }
    }

    private fun initList() {
        Tgsx.getFileList(onUpdate = {
            Tgsx.fileList.toList().filter {
                it.isLargeFile() && it !in largeFileList
            }.onEach {
                it.isSelect = false
            }.let {
                if (it.isNotEmpty()) {
                    Bnpt.logDebug(TAG, R.string.ލޜޜޗގ_D.string((it).toString()))

                    if (!binding.jxzsjxc.isEnabled) {
                        binding.jxzsjxc.isEnabled = true
                        binding.mlbrdtp.isEnabled = true
                        binding.zpeiolu.isEnabled = true
                    }

                    largeFileList.addAll(it)
                    binding.ejvvoar.visibility = View.GONE

                    adapter.setData(largeFileList)
                }
            }
        }, onEnd = {
            Bnpt.logDebug(TAG, R.string.ޖޑޕޝޣ_D.string())
            binding.ejvvoar.visibility = View.GONE
            adapter.setData(largeFileList)
            if (largeFileList.isEmpty()) {
                binding.cmzduiw.visibility = View.VISIBLE
            }
        })
    }

    data class Filter(
        val keyName: String = "", var isSelect: Boolean = false, ) {
        companion object {
            val KEY_ALL_TYPES = R.string.ޖޓޒށޡ_D.string()
            val KEY_IMAGE = R.string.ޅޥޢދޞ_D.string()
            val KEY_VIDEO = R.string.ޒލޝޙޅ_D.string()
            val KEY_AUDIO = R.string.ޕޣޞރގ_D.string()
            val KEY_DOCUMENT = R.string.ޡމޑހޏ_D.string()
            val KEY_ARCHIVES = R.string.ޢމޠޠފ_D.string()
            val KEY_APK = R.string.ނނޗބޚ_D.string()
            val KEY_OTHER_TYPES = R.string.ޓފށޔފ_D.string()

            val KEY_SIZE_10_MB = R.string.ކމހޙޝ_D.string()
            val KEY_SIZE_50_MB = R.string.ޥލއޠއ_D.string()
            val KEY_SIZE_100_MB = R.string.ޘޒޣޛމ_D.string()
            val KEY_SIZE_500_MB = R.string.ސޚއޗޕ_D.string()
            val KEY_SIZE_1_GB = R.string.ޙކޔސތ_D.string()

            val KEY_ALL_TIME = R.string.އޛގށވ_D.string()
            val KEY_1_WEEK = R.string.ޜޞބޑޒ_D.string()
            val KEY_1_MONTH = R.string.ޅޅޚޡޣ_D.string()
            val KEY_3_MONTHS = R.string.ޏޏޡޟޢ_D.string()
            val KEY_6_MONTHS = R.string.ސތގގރ_D.string()
            val KEY_1_YEAR = R.string.ޖޡޥނޜ_D.string()
        }
    }

    private fun playLottie(showFinish: (() -> Unit)? = null) {
        binding.xemxhro.isVisible = true

        Bnpt.logDebug(TAG, R.string.ޣބފޜތ_D.string())
        binding.root.postDelayed({
            Fnpc.showInterstitialAd(this) {
                binding.xemxhro.isVisible = false
                showFinish?.invoke()
                Bnpt.logDebug(TAG, R.string.ޖބތޢޕ_D.string())
            }
        }, 6000)
    }

    private fun showPopupWindow(view: View, type: Int = 0, list: List<Filter>) {
        val popupWindowView = layoutInflater.inflate(R.layout.dpqfye, null)
        val location = IntArray(2)
        binding.oirhned.getLocationOnScreen(location)
        val anchorBottom: Int = location[1] + binding.oirhned.height
        val screenHeight: Int = getResources().displayMetrics.heightPixels
        val height = screenHeight - anchorBottom + this.resources.getDimensionPixelSize(R.dimen.ބޙޚޓގ)

        val popupWindow = PopupWindow(popupWindowView, view.width, height, true)
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popupWindow.isOutsideTouchable = true
        popupWindow.isTouchable = true
        val pBinding = DpqfyeBinding.bind(popupWindowView)

        if (type == 0) {
            pBinding.bkcsqdl.visibility = View.GONE
        }
        if (type == 1) {
            pBinding.bkcsqdl.text = R.string.ޛޘފޤޚ_D.string()
        }
        if (type == 2) {
            pBinding.bkcsqdl.text = R.string.ރޓޡޗޙ_D.string()
        }
        class KKK(view: View) : RecyclerView.ViewHolder(view)

        val filterAdapter = object : RecyclerView.Adapter<KKK>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KKK {
                return KKK(R.layout.leottt.inflate(parent))
            }

            override fun getItemCount(): Int {
                return list.size
            }

            override fun onBindViewHolder(holder: KKK, position: Int) {
                val binding = LeotttBinding.bind(holder.itemView)
                val context = holder.itemView.context
                val data = list[position]
                binding.lwovtub.text = data.keyName
                if (data.isSelect) {
                    binding.lwovtub.setTextColor(ContextCompat.getColor(context, R.color.ފތޠޙޘ))
                    binding.gybhbxn.visibility = View.VISIBLE
                } else {
                    binding.lwovtub.setTextColor(ContextCompat.getColor(context, R.color.ހޓދމށ))
                    binding.gybhbxn.visibility = View.INVISIBLE
                }
                binding.root.setTrackedOnClickListener {
                    val old = list.find { it.isSelect }
                    if (data == old) {
                        return@setTrackedOnClickListener
                    } else {
                        data.isSelect = true
                        old?.isSelect = false
                        filterTypeList(type, data.keyName)
                        popupWindow.dismiss()
                    }
                }
            }

        }
        pBinding.pvaiyzw.adapter = filterAdapter
        pBinding.root.setTrackedOnClickListener {
            popupWindow.dismiss()
        }

        popupWindow.showAsDropDown(view)
    }

    private fun filterTypeList(filterType: Int, keyName: String) {
        Bnpt.logDebug(TAG, R.string.ޟޑއނނ_D.string((filterType).toString(), (keyName).toString()))
        if (filterType == 0) {
            binding.jqdzhtd.text = keyName
            fileType = keyName
        }
        if (filterType == 1) {
            binding.nimczzt.text = keyName
            filterSize = keyName
        }
        if (filterType == 2) {
            binding.oyfpmjp.text = keyName
            filterTime = keyName
        }

        val tempList1 = when (fileType) {
            KEY_ALL_TYPES -> largeFileList
            KEY_IMAGE -> largeFileList.filter { it.isImage() }
            KEY_VIDEO -> largeFileList.filter { it.isVideo() }
            KEY_AUDIO -> largeFileList.filter { it.isAudio() }
            KEY_DOCUMENT -> largeFileList.filter { it.isDoc() }
            KEY_ARCHIVES -> largeFileList.filter { it.isZip() }
            KEY_APK -> largeFileList.filter { it.isApk() }
            KEY_OTHER_TYPES -> largeFileList.filter { it.isOther() }
            else -> largeFileList
        }
        val tempList2 = when (filterSize) {
            KEY_SIZE_10_MB -> tempList1.filter { it.size > 1024 * 1024 * 10 }
            KEY_SIZE_50_MB -> tempList1.filter { it.size > 1024 * 1024 * 50 }
            KEY_SIZE_100_MB -> tempList1.filter { it.size > 1024 * 1024 * 100 }
            KEY_SIZE_500_MB -> tempList1.filter { it.size > 1024 * 1024 * 500 }
            KEY_SIZE_1_GB -> tempList1.filter { it.size > 1024 * 1024 * 1024 }
            else -> tempList1
        }
        val tempList3 = when (filterTime) {
            KEY_ALL_TIME -> tempList2
            KEY_1_WEEK -> tempList2.filter {
                val flag = Sjdo.isDaysAgo(it.time, 7)

                flag
            }

            KEY_1_MONTH -> tempList2.filter {
                val flag = Sjdo.isDaysAgo(it.time, 30)

                flag
            }

            KEY_3_MONTHS -> tempList2.filter { Sjdo.isDaysAgo(it.time, 90) }
            KEY_6_MONTHS -> tempList2.filter { Sjdo.isDaysAgo(it.time, 180) }
            KEY_1_YEAR -> tempList2.filter { Sjdo.isDaysAgo(it.time, 365) }
            else -> tempList2
        }
        adapter.setData(tempList3)
    }

}