package com.zxhyis.toolss.ui.page.bigfileclean

import android.annotation.SuppressLint
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 androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.PermissionUtils
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.cx.FileBean
import com.zxhyis.toolss.cx.FileHelps
import com.zxhyis.toolss.databinding.ActivityBigFileCleanBinding
import com.zxhyis.toolss.databinding.ItemFileFilterBinding
import com.zxhyis.toolss.databinding.PopupwindowFileFilterBinding
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.logic.TimeUtils
import com.zxhyis.toolss.logic.TimeUtils.simpleDateFormat
import com.zxhyis.toolss.logic.XmlEx.inflate
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.ui.dialog.FileDeleteDialog.showFileDeleteDialog
import com.zxhyis.toolss.ui.dialog.FileDetailDialog.showFileDetailDialog
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_1_MONTH
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_1_WEEK
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_1_YEAR
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_3_MONTHS
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_6_MONTHS
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_ALL_TIME
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_ALL_TYPES
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_APK
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_ARCHIVES
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_AUDIO
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_DOCUMENT
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_IMAGE
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_OTHER_TYPES
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_SIZE_100_MB
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_SIZE_10_MB
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_SIZE_1_GB
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_SIZE_500_MB
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_SIZE_50_MB
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity.Filter.Companion.KEY_VIDEO
import java.io.File


/**
 * 大文件清理 5.11
 */
class BigFileCleanActivity : TopActivity<ActivityBigFileCleanBinding>() {

    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 TAG = "BigFileCleanActivity"

    private val bigFileList = arrayListOf<FileBean>()
    private lateinit var adapter: BigFileAdapter

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

    override fun getViewBinding1(): ActivityBigFileCleanBinding {
        return ActivityBigFileCleanBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetTextI18n")
    override fun init() {
        BarUtils.setStatusBarLightMode(this, true)
        window.statusBarColor = ContextCompat.getColor(this, R.color.white)
        vb.llType.isEnabled = false
        vb.llSize.isEnabled = false
        vb.llTime.isEnabled = false

        adapter = BigFileAdapter(
            itemClick = { fileBean ->
                this.showFileDetailDialog(fileBean)
            },
            selectClick = { files ->
                if (files.isNotEmpty()) {
                    vb.tvDelete.background = ContextCompat.getDrawable(this, R.drawable.bg_corners_4772ff)
                    vb.tvDelete.isEnabled = true
                    val size = files.sumOf { it.size }
                    val sizeF = Formatter.formatFileSize(this, size)
                    vb.tvDelete.text = "DELETE $sizeF"
                } else {
                    vb.tvDelete.background = ContextCompat.getDrawable(this, R.drawable.bg_corners_bfbfbf_26)
                    vb.tvDelete.isEnabled = false
                    vb.tvDelete.text = "DELETE"
                }
            }
        )
        vb.rv.adapter = adapter
        vb.tvDelete.setOnClick(javaClass.simpleName) {
            this.showFileDeleteDialog {
                val deleteList = arrayListOf<FileBean>()
                adapter.getSelectData().forEach {
                    val file = File(it.path)
                    try {
                        if (file.delete()) {
                            deleteList.add(it)
                        }
                    } catch (e: Exception) {
                    }
                }
                bigFileList.removeAll(deleteList.toSet())
                adapter.removeData(deleteList)
                vb.tvDelete.background = ContextCompat.getDrawable(this, R.drawable.bg_corners_bfbfbf_26)
                vb.tvDelete.isEnabled = false
                vb.tvDelete.text = "DELETE"
            }
        }

        vb.llType.setOnClick(javaClass.simpleName) {
            showPopupWindow(vb.llFilter, 0, listTypes)
        }
        vb.llSize.setOnClick(javaClass.simpleName) {
            showPopupWindow(vb.llFilter, 1, listSizes)
        }
        vb.llTime.setOnClick(javaClass.simpleName) {
            showPopupWindow(vb.llFilter, 2, listTimes)
        }
        vb.flBack.setOnClick(javaClass.simpleName) {
            AdmobUtils.showInterstitialAd(this) {
                finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            AdmobUtils.showInterstitialAd(this@BigFileCleanActivity) {
                finishToMain()
            }
        }
        vb.tvType.text = fileType
        vb.tvSize.text = filterSize
        vb.tvTime.text = filterTime
        checkPermission()

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            PermissionUtils.isGranted(PermissionConstants.STORAGE)
        }
        if (flag) {
            playlottie()
        }
    }

    private fun playlottie(showFinish: (() -> Unit)? = null) {
        vb.llLottie.isVisible = true
//        vb.lottie.imageAssetsFolder = "bigfilescan/images/"
//        vb.lottie.setAnimation("bigfilescan/lottie_large_file.json")
//        vb.lottie.playAnimation()

        LogEx.logDebug(TAG, "playlottie")
        vb.root.postDelayed({
            AdmobUtils.showInterstitialAd(this) {
                vb.llLottie.isVisible = false
                showFinish?.invoke()
                LogEx.logDebug(TAG, "playlottie finish")
            }
        }, 6000)
    }

    override fun onPermissionsResult(isGranted: Boolean) {
        super.onPermissionsResult(isGranted)
        if (isGranted) {
            playlottie()
            initList()
        } else {
            finishToMain()
        }
    }

    private fun initList() {
        FileHelps.getFileList(onUpdate = {
            FileHelps.fileList.toList().filter {
                it.isLargeFile() && it !in bigFileList
            }.onEach {
                it.isSelect = false
            }.let {
                if (it.isNotEmpty()) {
                    LogEx.logDebug(TAG, "it=${it}")

                    if (!vb.llType.isEnabled) {
                        vb.llType.isEnabled = true
                        vb.llSize.isEnabled = true
                        vb.llTime.isEnabled = true
                    }

                    bigFileList.addAll(it)
                    vb.progressbar.visibility = View.GONE
                    //反正我手机，显示不出来233
                    //adapter.notifyItemRangeInserted(bigFileList.size, it.size)
                    adapter.setData(bigFileList)
                }
            }
        }, onEnd = {
            LogEx.logDebug(TAG, "onEnd=调用")
            vb.progressbar.visibility = View.GONE
            adapter.setData(bigFileList)
        })
    }

    @SuppressLint("SetTextI18n")
    private fun showPopupWindow(view: View, type: Int = 0, list: List<Filter>) {
        val popupWindowView = layoutInflater.inflate(R.layout.popupwindow_file_filter, null)
        val location = IntArray(2)
        vb.llFilter.getLocationOnScreen(location)
        val anchorBottom: Int = location[1] + vb.llFilter.height
        val screenHeight: Int = getResources().displayMetrics.heightPixels
        val height = screenHeight - anchorBottom + this.resources.getDimensionPixelSize(R.dimen.dp_30)


//        val maxHeight = min(height.toDouble(), (screenHeight * 3 / 4).toDouble()).toInt() // 举例，最大高度为屏幕高度的 3/4
//        val popupWindowHeight =
//            ViewGroup.LayoutParams.MATCH_PARENT
        val popupWindow = PopupWindow(popupWindowView, view.width, height, true)
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popupWindow.isOutsideTouchable = true
        popupWindow.isTouchable = true
        val pBinding = PopupwindowFileFilterBinding.bind(popupWindowView)

        if (type == 0) {
            pBinding.tvTitle.visibility = View.GONE
        }
        if (type == 1) {
            pBinding.tvTitle.text = "Large than"
        }
        if (type == 2) {
            pBinding.tvTitle.text = "Earlier than"
        }
        class KKK(view: View) : ViewHolder(view)

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

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

            override fun onBindViewHolder(holder: KKK, position: Int) {
                val binding = ItemFileFilterBinding.bind(holder.itemView)
                val context = holder.itemView.context
                val data = list[position]
                binding.tv.text = data.keyName
                if (data.isSelect) {
                    binding.tv.setTextColor(ContextCompat.getColor(context, R.color.color_365cd9))
                    binding.ivSelector.visibility = View.VISIBLE
                } else {
                    binding.tv.setTextColor(ContextCompat.getColor(context, R.color.color_666666))
                    binding.ivSelector.visibility = View.INVISIBLE
                }
                binding.root.setOnClick("filterAdapter") {
                    val old = list.find { it.isSelect }
                    if (data == old) {
                        return@setOnClick
                    } else {
                        data.isSelect = true
                        old?.isSelect = false
                        filterTypeList(type, data.keyName)
                        popupWindow.dismiss()
                    }
                }
            }

        }
        pBinding.rv.adapter = filterAdapter
        pBinding.root.setOnClick(javaClass.simpleName) {
            popupWindow.dismiss()
        }

        popupWindow.showAsDropDown(view)
    }

    private fun filterTypeList(filterType: Int, keyName: String) {
        LogEx.logDebug(TAG, "type=$filterType keyName=$keyName")
        if (filterType == 0) {
            vb.tvType.text = keyName
            fileType = keyName
        }
        if (filterType == 1) {
            vb.tvSize.text = keyName
            filterSize = keyName
        }
        if (filterType == 2) {
            vb.tvTime.text = keyName
            filterTime = keyName
        }

        val tempList1 = when (fileType) {
            KEY_ALL_TYPES -> bigFileList
            KEY_IMAGE -> bigFileList.filter { it.isImage() }
            KEY_VIDEO -> bigFileList.filter { it.isVideo() }
            KEY_AUDIO -> bigFileList.filter { it.isAudio() }
            KEY_DOCUMENT -> bigFileList.filter { it.isDoc() }
            KEY_ARCHIVES -> bigFileList.filter { it.isZip() }
            KEY_APK -> bigFileList.filter { it.isApk() }
            KEY_OTHER_TYPES -> bigFileList.filter { it.isOther() }
            else -> bigFileList
        }
        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 = TimeUtils.isDaysAgo(it.time, 7)
//                val time = simpleDateFormat.format(it.time)
//                LogEx.logDebug(TAG, "filterTime=$filterTime  file.time=$time flag=$flag")
                flag
            }

            KEY_1_MONTH -> tempList2.filter {
                val flag = TimeUtils.isDaysAgo(it.time, 30)
//                val time = simpleDateFormat.format(it.time)
//                LogEx.logDebug(TAG, "filterTime=$filterTime  file.time=$time flag=$flag")
                flag
            }

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

    data class Filter(
        val keyName: String = "",
        var isSelect: Boolean = false,
    ) {
        companion object {
            const val KEY_ALL_TYPES = "All types"
            const val KEY_IMAGE = "Image"
            const val KEY_VIDEO = "Video"
            const val KEY_AUDIO = "Audio"
            const val KEY_DOCUMENT = "Document"
            const val KEY_ARCHIVES = "Archives"
            const val KEY_APK = "APK"
            const val KEY_OTHER_TYPES = "Other types"


            const val KEY_SIZE_10_MB = "10 MB"
            const val KEY_SIZE_50_MB = "50 MB"
            const val KEY_SIZE_100_MB = "100 MB"
            const val KEY_SIZE_500_MB = "500 MB"
            const val KEY_SIZE_1_GB = "1 GB"

            const val KEY_ALL_TIME = "All time"
            const val KEY_1_WEEK = "1 week"
            const val KEY_1_MONTH = "1 month"
            const val KEY_3_MONTHS = "3 months"
            const val KEY_6_MONTHS = "6 months"
            const val KEY_1_YEAR = "1 year"
        }
    }

}