package com.ux.video.file.filerecovery.utils

import android.content.Context
import android.icu.text.SimpleDateFormat
import android.icu.util.Calendar
import android.os.Environment
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.ux.video.file.filerecovery.App
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.photo.ResultPhotosFiles
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
import java.util.Date
import java.util.Locale
import kotlin.collections.sortedBy

object Common {

    val itemSpacing = 10
    val horizontalSpacing = 16

    val KEY_SCAN_TYPE = "scan_type"
    val VALUE_SCAN_TYPE_photo = 0
    val VALUE_SCAN_TYPE_deleted_photo = 1
    val VALUE_SCAN_TYPE_video = 2
    val VALUE_SCAN_TYPE_deleted_video = 3
    val VALUE_SCAN_TYPE_audio = 4
    val VALUE_SCAN_TYPE_deleted_audio = 5
    val VALUE_SCAN_TYPE_documents = 6
    val VALUE_SCAN_TYPE_deleted_documents = 7


    val rootDir = Environment.getExternalStorageDirectory()
    val dateFormat = SimpleDateFormat("MMMM d,yyyy", Locale.ENGLISH)
    val chineseFormat = SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE)
    val recoveryPhotoDir = "MyAllRecovery/Photo"

    /**
     * 默认按照日期分类，将最新的排前面 降序
     */
    fun getSortByDayNewToOld(list: ArrayList<ResultPhotosFiles>): List<Pair<String, List<ResultPhotosFiles>>> {


        val grouped = list.groupBy {
            dateFormat.format(Date(it.lastModified))
        }
        val parentData: List<Pair<String, List<ResultPhotosFiles>>> = grouped
            .map { it.key to it.value }
            .sortedByDescending { dateFormat.parse(it.first)?.time ?: 0L }
        return parentData
    }

    /**
     * 按照日期排序， 时间最早的排前面 升序
     *
     */
    fun getSortByDayOldToNew(list: List<Pair<String, List<ResultPhotosFiles>>>) =
        list.sortedBy { dateFormat.parse(it.first)?.time ?: 0L }

    /**
     *  按照文件大小排序，将最大的排前面 降序
     */
    fun getSortBySizeBigToSmall(list: ArrayList<ResultPhotosFiles>) = list.sortedByDescending {
        it.size
    }

    /**
     *  按照文件大小排序，将最小的排前面 升序
     */
    fun getSortBySizeSmallToBig(list: ArrayList<ResultPhotosFiles>) = list.sortedBy {
        it.size
    }


    /**
     * 格式化文件大小显示
     */
    fun formatFileSize(context: Context, size: Long): String {
        if (size < 1024) {
            return "$size B"
        }
        val kb = size / 1024.0
        if (kb < 1024) {
            return String.format(context.getString(R.string.size_kb), kb)
        }
        val mb = kb / 1024.0
        if (mb < 1024) {
            return String.format(context.getString(R.string.size_kb), mb)
        }
        val gb = mb / 1024.0
        return String.format(context.getString(R.string.size_gb), gb)
    }


    /**
     *
     * @param months  筛选months月之内的数据
     */
    fun filterWithinOneMonthByDay(
        grouped: List<Pair<String, List<ResultPhotosFiles>>>, months: Int
    ): List<Pair<String, List<ResultPhotosFiles>>> {
        val today = Calendar.getInstance()
        val oneMonthAgo = Calendar.getInstance().apply {
            add(Calendar.MONTH, -months) // 1 个月前
        }

        return grouped.filter { (dayStr, _) ->
            val day = dateFormat.parse(dayStr)
            day != null && !day.before(oneMonthAgo.time) && !day.after(today.time)
        }
    }

    /**
     * @param months  筛选months月之内的数据
     */
    fun filterWithinOneMonth(list: List<ResultPhotosFiles>, months: Int): List<ResultPhotosFiles> {
        val today = Calendar.getInstance()
        val oneMonthAgo = Calendar.getInstance().apply {
            add(Calendar.MONTH, -months)
        }

        return list.filter {
            val cal = Calendar.getInstance().apply { timeInMillis = it.lastModified }
            !cal.before(oneMonthAgo) && !cal.after(today)
        }
    }

    /**
     *  设置全部子View的选中
     */
//    fun setItemSelect(view: ViewGroup, boolean: Boolean) {
//        for (i in 0 until view.childCount) {
//            val child = view.getChildAt(i)
//            child.isSelected = boolean
//        }
//    }
    fun setItemSelect(view: View, selected: Boolean) {
        view.isSelected = selected
        if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                val child = view.getChildAt(i)
                setItemSelect(child, selected)
            }
        }
    }


    /**
     * @param list  筛选后的显示的数据
     * @param selected  实际选中的数据集合
     * @return 显示的选中数量和选中集合
     */
    fun checkSelectListContainDate(
        list: List<Pair<String, List<ResultPhotosFiles>>>,
        selected: Set<String>
    ): Pair<Int, MutableSet<String>> {
        val currentSelected = mutableSetOf<String>()

        val totalSelectedCount = list.sumOf { pair ->
            pair.second.count {
                val isSelected = it.path in selected
                if (isSelected) currentSelected.add(it.path.toString())
                isSelected
            }
        }

        showLog("-------totalSelectedCount = $totalSelectedCount   currentSelected=${currentSelected.size}")
        return totalSelectedCount to currentSelected
    }


    fun checkSelectListContainSize(
        list: List<ResultPhotosFiles>,
        selected: Set<String>
    ): Pair<Int, MutableSet<String>> {
        val currentSelected = mutableSetOf<String>()
        val totalSelectedCount = list.count {
            val isSelected = it.path in selected
            if (isSelected) currentSelected.add(it.path.toString())
            isSelected
        }
        showLog("-------totalSelectedCount 222=${totalSelectedCount}")
        return totalSelectedCount to currentSelected
    }

    fun getFormatDate(time: Long): String {
        return dateFormat.format(Date(time))
    }

    fun getChineseFormatDate(date: Date): String {
        return chineseFormat.format(date)
    }

    fun getDateFromFormat(dateStr: String): Date? {
        return chineseFormat.parse(dateStr)

    }

    fun getColorInt(context: Context, colorId: Int): Int {
        return ContextCompat.getColor(context, colorId)
    }

    fun showLog(msg: String) {
        Log.d("============", msg)
    }
}