package com.ux.video.file.filerecovery.sort

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.base.BaseActivity
import com.ux.video.file.filerecovery.databinding.ActivityPhotoSortingBinding
import com.ux.video.file.filerecovery.db.ResultDataFiles
import com.ux.video.file.filerecovery.db.isThumbnail
import com.ux.video.file.filerecovery.detail.DetailsActivity
import com.ux.video.file.filerecovery.success.RecoverySuccessActivity
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.Common.setItemSelect
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterByDuration
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterByDurationList
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterBySize
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterBySizeList
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterRemoveThumbnailsAsync
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterThumbnailsAsync
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterWithinDateRange
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterWithinDateRangeList
import com.ux.video.file.filerecovery.utils.ExtendFunctions.kbToBytes
import com.ux.video.file.filerecovery.utils.ExtendFunctions.mbToBytes
import com.ux.video.file.filerecovery.utils.ExtendFunctions.minutesToMillisecond
import com.ux.video.file.filerecovery.utils.ExtendFunctions.removeItem
import com.ux.video.file.filerecovery.utils.FileType
import com.ux.video.file.filerecovery.utils.GridSpacingItemDecoration
import com.ux.video.file.filerecovery.utils.ScanType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Date

class SortingActivity : BaseActivity<ActivityPhotoSortingBinding>() {

    companion object {
        //指定文件夹下的所有文件
        val KEY_PHOTO_FOLDER_FILE = "folder_file"

        val FILTER_DATE_ALL = -1
        val FILTER_DATE_1 = 1
        val FILTER_DATE_6 = 6
        val FILTER_DATE_24 = 24
        val FILTER_DATE_CUSTOMER = 0


        val SORT_ASC_SIZE = 0
        val SORT_DESC_SIZE = 1
        val SORT_ASC_DATE = 2
        val SORT_DESC_DATE = 3
    }

    private lateinit var fileType: FileType

    private var sortDialogFragment: SortDialogFragment? = null
    private var columns = 3
    private var dateAdapter: SortDisplayAdapter? = null

    //文件大小排序使用的适配器
    private var sizeSortAdapter: SortDisplayChildAdapter? = null


    private var dialogCustomerDateStart: DatePickerDialogFragment? = null
    private var dialogCustomerDateEnd: DatePickerDialogFragment? = null


    //默认倒序排序
    private var sortReverse = true

    //筛选时间，默认全部-1
    private var filterDate = FILTER_DATE_ALL

    //筛选大小，默认全部-1
    private var filterSize: String = "All"

    private var filterDatePopupWindows: DateFilterPopupWindows? = null
    private var filterStartDate: Date? = null
    private var filterEndDate: Date? = null

    private var filterSizePopupWindows: FilterPopupWindows? = null
    private var filterLayoutPopupWindows: FilterPopupWindows? = null


    private lateinit var sortBySizeBigToSmall: List<ResultDataFiles>
    private lateinit var sortBySizeSmallToBig: List<ResultDataFiles>
    private lateinit var sortByDateReverse: List<Pair<String, List<ResultDataFiles>>>
    private lateinit var sortedByDatePositive: List<Pair<String, List<ResultDataFiles>>>

    //最新显示的数据集合（包含缩略图 ,只保存当前筛选后或者排序后显示的数据，不受switch切换影响）
    private var currentDateList: List<Pair<String, List<ResultDataFiles>>>? = null
    private var currentSizeList: List<ResultDataFiles>? = null


    //选中的所有数据集合(实际选中)
    private lateinit var allSelectedSetList: Set<ResultDataFiles>

    //选中的所有数据集合(筛选后的数据实际显示的所有选中)
    private lateinit var filterSelectedSetList: Set<ResultDataFiles>

    private lateinit var mItemDecoration: GridSpacingItemDecoration

    private lateinit var sizeFilterItemArray: Array<String>

    private val viewModel: SortingViewModel by viewModels()
    private lateinit var list: List<ResultDataFiles>

    //    private lateinit var viewModel: SortingViewModel
    override fun inflateBinding(inflater: LayoutInflater): ActivityPhotoSortingBinding {

        return ActivityPhotoSortingBinding.inflate(inflater)
    }


    override fun initData() {
        super.initData()
        val intExtra = intent.getIntExtra(Common.KEY_FILE_TYPE, FileType.PHOTO.value)

        fileType = FileType.from(intExtra)!!
        mItemDecoration =
            GridSpacingItemDecoration(columns, Common.itemSpacing, Common.horizontalSpacing)
        updateButtonCounts(0)
        viewModel.sortingData.observe(this) { sortData ->
            list = sortData

            list.let {
                binding.tvThumbnailCounts.text =
                    getString(R.string.hide_thumbnails, it.filter { it.isThumbnail() }.size)

                //降序（最近的在前面）
                sortByDateReverse = Common.getSortByDayNewToOldInit(it)
                //升序（时间最远的在前面）
                sortedByDatePositive = Common.getSortByDayOldToNew(sortByDateReverse)
                sortBySizeBigToSmall = Common.getSortBySizeBigToSmall(it)
                sortBySizeSmallToBig = Common.getSortBySizeSmallToBig(it)

                sizeSortAdapter = SortDisplayChildAdapter(
                    this@SortingActivity,
                    fileType,
                    columns, viewModel,
                    { resultPhotosFiles, isAdd, allSelected ->
                        viewModel.toggleSelection(isAdd, resultPhotosFiles)
                    }, { hide ->


                    }) { item ->
                    startActivity(
                        Intent(
                            this@SortingActivity,
                            DetailsActivity::class.java
                        ).apply {
                            putExtra(Common.KEY_FILE_TYPE, item.fileType.value)
                            putExtra(DetailsActivity.KEY_CLICK_ITEM, item)
                        })

                }
                dateAdapter =
                    SortDisplayAdapter(
                        this@SortingActivity,
                        fileType,
                        columns,
                        viewModel,
                        { actionPath, isAdd ->
                            viewModel.toggleSelection(isAdd, actionPath)
                        }) { item ->
                        startActivity(
                            Intent(
                                this@SortingActivity,
                                DetailsActivity::class.java
                            ).apply {
                                putExtra(Common.KEY_FILE_TYPE, fileType.value)
                                putExtra(DetailsActivity.KEY_CLICK_ITEM, item)
                            })
                    }.apply {
                        setData(sortByDateReverse)
                        resetCurrentDateList(sortByDateReverse)
                    }
                setDateAdapter()
                setSingleDelete()
                setFilter()
                setAllClick()

            }
        }

        viewModel.selectedLiveData.observe(this) { selectedSet ->
            allSelectedSetList = selectedSet
            Common.showLog("所有数据 选中状态更新: ${selectedSet.size}")
        }

        viewModel.selectedDisplayLiveData.observe(this) { displaySet ->
            filterSelectedSetList = displaySet
            Common.showLog("当前显示筛选数据 选中状态更新: ${displaySet.size}")
            updateCurrentIsAllSelectStatus()
        }
        setScanTypeView()


    }

    private fun setAllClick() {
        binding.run {
            imageViewBack.setOnClickListener { finish() }
            switchHideThumbnails.setOnCheckedChangeListener { _, isChecked ->
                when (recyclerView.adapter) {
                    is SortDisplayAdapter -> {
                        lifecycleScope.launch {
                            dateAdapter?.run {
                                initGetCurrentDateList().let { list ->
                                    val filterThumbnailsAsync =
                                        if (isChecked) list.filterThumbnailsAsync() else list
                                    setData(filterThumbnailsAsync)
                                    checkRefreshDisPlaySelected(list1 = filterThumbnailsAsync)
                                }

                            }
                        }

                    }

                    is SortDisplayChildAdapter -> {
                        lifecycleScope.launch {
                            sizeSortAdapter?.run {
                                initGetCurrentSizeList().let {
                                    val filterThumbnailsAsync =
                                        if (isChecked) it.filterRemoveThumbnailsAsync() else it
                                    setData(filterThumbnailsAsync)
                                    checkRefreshDisPlaySelected(list2 = filterThumbnailsAsync)
                                }

                            }
                        }

                    }
                }
                updateCurrentIsAllSelectStatus()

            }
            tvRecover.setOnClickListener {
                RecoverOrDeleteManager.showRecoveringDialog(
                    supportFragmentManager,
                    lifecycleScope,
                    filterSelectedSetList
                ) { count ->
                    complete(count, 0)
                }

            }
            tvDelete.setOnClickListener {
                RecoverOrDeleteManager.showConfirmDeleteDialog(
                    fragmentManager = supportFragmentManager,
                    scope = lifecycleScope,
                    selectedSetList = filterSelectedSetList
                ) { count ->
                    complete(count, 1)
                }

            }
            imSort.setOnClickListener {
                sortDialogFragment = sortDialogFragment ?: SortDialogFragment {
                    when (it) {
                        SORT_ASC_DATE -> {
                            setDateAdapter()
                            lifecycleScope.launch {
                                initGetCurrentDateList().let {
                                    val filterThumbnailsAsync =
                                        if (switchHideThumbnails.isChecked) it.filterThumbnailsAsync() else it
                                    val sortByDayOldToNew =
                                        Common.getSortByDayOldToNew(filterThumbnailsAsync)
                                    dateAdapter?.setData(sortByDayOldToNew)
                                    resetCurrentDateList(sortByDayOldToNew)
                                }
                                sortReverse = false
                            }

                        }

                        SORT_DESC_DATE -> {
                            setDateAdapter()
                            lifecycleScope.launch {
                                initGetCurrentDateList().let {
                                    val filterThumbnailsAsync =
                                        if (switchHideThumbnails.isChecked) it.filterThumbnailsAsync() else it
                                    val sortByDayNewToOld =
                                        Common.getSortByDayNewToOld(filterThumbnailsAsync)
                                    dateAdapter?.setData(sortByDayNewToOld)
                                    resetCurrentDateList(sortByDayNewToOld)
                                }
                                sortReverse = true
                            }
                        }

                        SORT_DESC_SIZE -> {
                            setSizeAdapter()
                            lifecycleScope.launch {
                                initGetCurrentSizeList().let {
                                    val filterThumbnailsAsync =
                                        if (switchHideThumbnails.isChecked) it.filterRemoveThumbnailsAsync() else it
                                    val sortBySizeBigToSmall =
                                        Common.getSortBySizeBigToSmall(filterThumbnailsAsync)
                                    sizeSortAdapter?.setData(sortBySizeBigToSmall)
                                    resetCurrentSizeList(sortBySizeBigToSmall)
                                }
                                sortReverse = true
                            }

                        }

                        SORT_ASC_SIZE -> {
                            setSizeAdapter()
                            lifecycleScope.launch {
                                initGetCurrentSizeList().let {
                                    val filterThumbnailsAsync =
                                        if (switchHideThumbnails.isChecked) it.filterRemoveThumbnailsAsync() else it
                                    val sortBySizeSmallToBig =
                                        Common.getSortBySizeSmallToBig(filterThumbnailsAsync)
                                    sizeSortAdapter?.setData(sortBySizeSmallToBig)
                                    resetCurrentSizeList(sortBySizeSmallToBig)
                                }
                                sortReverse = false
                            }
                        }
                    }
                }
                sortDialogFragment?.show(supportFragmentManager, "")
            }

            //全选按钮  只对当前显示的数据有效
            tvSelectAll.setOnClickListener {
                it.isSelected = !it.isSelected
                when (binding.recyclerView.adapter) {
                    is SortDisplayAdapter -> {
                        dateAdapter?.setAllSelected(it.isSelected)
                        dateAdapter?.getCurrentData()?.let {
                            it as List<Pair<String, List<ResultDataFiles>>>
                            if (it.size > 0)
                                Common.showLog("------------全选按钮  日期-${it.size} ${it[0].second[0].path}")
                        }

                    }

                    is SortDisplayChildAdapter -> {
                        sizeSortAdapter?.setAllSelected(it.isSelected)
                        sizeSortAdapter?.getCurrentData()?.let {
                            it as List<ResultDataFiles>
                            if (it.size > 0)
                                Common.showLog("------------全选按钮  大小-${it.size} ${it[0].path}")
                        }
                    }
                }


            }
        }
    }


    /**
     * 不同类型下的ui和功能点区分
     */
    private fun setScanTypeView() {
        binding.run {
          fileType?.let {
              when (it) {
                  FileType.PHOTO -> {
                      titleSize.text = getString(R.string.size)
                      filterLayoutLinearlayout.isVisible = true
                      relativeThumbnails.isVisible = true
                      layoutSearch.isVisible = false
                      sizeFilterItemArray = resources.getStringArray(R.array.filter_size_photo)
                  }

                  FileType.VIDEO -> {
                      titleSize.text = getString(R.string.duration)
                      filterLayoutLinearlayout.isVisible = true
                      relativeThumbnails.isVisible = false
                      layoutSearch.isVisible = false
                      sizeFilterItemArray =
                          resources.getStringArray(R.array.filter_duration_video_audio)
                  }

                  FileType.AUDIO -> {
                      titleSize.text = getString(R.string.duration)
                      filterLayoutLinearlayout.isVisible = false
                      relativeThumbnails.isVisible = false
                      layoutSearch.isVisible = true
                      sizeFilterItemArray =
                          resources.getStringArray(R.array.filter_duration_video_audio)
                      initSearch()
                  }

                  FileType.DOCUMENT -> {
                      titleSize.text = getString(R.string.size)
                      filterLayoutLinearlayout.isVisible = false
                      relativeThumbnails.isVisible = false
                      layoutSearch.isVisible = true
                      sizeFilterItemArray = resources.getStringArray(R.array.filter_documents_size)
                      initSearch()
                  }


              }
          }

        }
    }

    private fun updateCurrentIsAllSelectStatus() {
        filterSelectedSetList.size.let {
            binding.tvSelectCounts.text = it.toString()
            updateButtonCounts(it)
            when (binding.recyclerView.adapter) {
                is SortDisplayAdapter -> {
                    val adapter = binding.recyclerView.adapter as SortDisplayAdapter
                    if (it > 0) {
                        binding.tvSelectAll.isSelected = it == adapter.getTotalChildCount(false)
                    } else {
                        binding.tvSelectAll.isSelected = false
                    }

                }

                is SortDisplayChildAdapter -> {
                    val adapter = binding.recyclerView.adapter as SortDisplayChildAdapter
                    if (it > 0) {
                        binding.tvSelectAll.isSelected =
                            it == adapter.itemCount
                    } else {
                        binding.tvSelectAll.isSelected = false
                    }
                }
            }
        }


    }

    private fun initGetCurrentSizeList(): List<ResultDataFiles> {
        currentSizeList = currentSizeList ?: currentDateList?.flatMap { it.second }
        return currentSizeList!!
    }

    private fun resetCurrentSizeList(currentList: List<ResultDataFiles>) {
        currentSizeList = currentList
        currentDateList = null

        binding.tvThumbnailCounts.text =
            getString(R.string.hide_thumbnails, currentList.filter { it.isThumbnail() }.size)

    }

    private fun initGetCurrentDateList(): List<Pair<String, List<ResultDataFiles>>> {
        currentDateList = currentDateList ?: Common.getSortByDayNewToOldInit(currentSizeList!!)
        return currentDateList!!
    }

    private fun resetCurrentDateList(currentList: List<Pair<String, List<ResultDataFiles>>>) {
        currentDateList = currentList
        currentSizeList = null
        val totalSelectedCount = currentList.sumOf { pair ->
            pair.second.filter { it.isThumbnail() }.size
        }
        binding.tvThumbnailCounts.text =
            getString(R.string.hide_thumbnails, totalSelectedCount)

    }

    /**
     * 重置适配器 日期显示和大小显示适配器切换
     */
    private fun setDateAdapter() {
        binding.recyclerView.run {
            adapter = dateAdapter?.apply { setColumns(columns) }
            layoutManager = LinearLayoutManager(this@SortingActivity)
            setPadding(0, 0, 0, 70.dpToPx(context))
            clipToPadding = false
        }
    }

    private fun setSizeAdapter() {
        binding.recyclerView.run {
            val aPx = 16.dpToPx(context)
            val bottom = 70.dpToPx(context)
            when (fileType) {
                FileType.AUDIO, FileType.DOCUMENT-> {
                    layoutManager = LinearLayoutManager(context)
                    setPadding(aPx, 0, 0, bottom)
                }

                else -> {
                    val bPx = 6.dpToPx(context)
                    setPadding(aPx, 0, bPx, bottom)
                    clipToPadding = false
                    layoutManager = GridLayoutManager(context, columns)
                }
            }
            adapter = sizeSortAdapter

        }
    }

    /**
     * 筛选和布局设置
     */
    private fun setFilter() {
        //日期筛选

        binding.run {
            filterDateLayout.setOnClickListener {
                setItemSelect(it as LinearLayout, true)
                resources.getStringArray(R.array.filter_date).let { data ->
                    filterDatePopupWindows = filterDatePopupWindows ?: DateFilterPopupWindows(
                        this@SortingActivity,
                        0,
                        { clickValue, showDialog ->
                            when (clickValue) {
                                data[0] -> {
                                    filterDate = FILTER_DATE_ALL
                                    titleDate.text = clickValue
                                    startFilter()
                                }

                                data[1] -> {
                                    filterDate = FILTER_DATE_1
                                    titleDate.text = clickValue
                                    startFilter()
                                }

                                data[2] -> {
                                    filterDate = FILTER_DATE_6
                                    titleDate.text = clickValue
                                    startFilter()
                                }

                                data[3] -> {
                                    filterDate = FILTER_DATE_24
                                    titleDate.text = clickValue
                                    startFilter()
                                }

                                data[4] -> {
                                    filterDate = FILTER_DATE_CUSTOMER
                                    if (showDialog)
                                        showStartDateDialog(true, null)
                                    else {
                                        titleDate.text = clickValue
                                        startFilter()
                                    }

                                }
                            }

                        }, onResetDate = { isStart, currentDate ->
                            if (isStart) {
                                showStartDateDialog(false, currentDate)
                            } else {
                                showEndDateDialog(false, currentDate)
                            }

                        }) {
                        //dismiss

                        setItemSelect(it, false)
                    }

                    filterDatePopupWindows?.show(it)
                }


            }
            //大小筛选
            filterSizeLayout.setOnClickListener {
                setItemSelect(it as LinearLayout, true)
                sizeFilterItemArray.let { data ->
                    filterSizePopupWindows = filterSizePopupWindows ?: FilterPopupWindows(
                        this@SortingActivity,
                        data,
                        0,
                        { clickValue ->
                            titleSize.text = clickValue
                            filterSize = clickValue
                            startFilter()
                        }) {
                        setItemSelect(it, false)
                    }
                    filterSizePopupWindows?.show(it)

                }


            }

            //布局设置
            filterLayoutLinearlayout.setOnClickListener {
                setItemSelect(it as LinearLayout, true)
                resources.getStringArray(R.array.filter_layout).let { data ->
                    filterLayoutPopupWindows = filterLayoutPopupWindows ?: FilterPopupWindows(
                        this@SortingActivity,
                        data,
                        1,
                        { clickValue ->
                            when (clickValue) {
                                data[0] -> columns = 2
                                data[1] -> columns = 3
                                data[2] -> columns = 4
                            }
                            when (binding.recyclerView.adapter) {
                                is SortDisplayAdapter -> {
                                    dateAdapter?.setColumns(columns)
                                }

                                is SortDisplayChildAdapter -> {
                                    binding.recyclerView.layoutManager =
                                        GridLayoutManager(this@SortingActivity, columns)
                                    sizeSortAdapter?.setColumns(columns)
                                }
                            }
                        }) {
                        setItemSelect(it, false)
                    }
                }
                filterLayoutPopupWindows?.show(it)

            }


        }
    }


    /**
     * 根据当前显示的实际数据选中的数量来更新按钮文字和状态
     */
    private fun updateButtonCounts(selectedCounts: Int) {
        binding.run {
            if (selectedCounts <= 0) {
                tvDelete.isEnabled = false
                tvRecover.isEnabled = false
            } else {
                tvDelete.isEnabled = true
                tvRecover.isEnabled = true
            }
            tvDelete.text = getString(R.string.delete_placeholder, selectedCounts)
            tvRecover.text = getString(R.string.recover_placeholder, selectedCounts)
        }
    }

    /**
     * 执行筛选结果  todo
     */
    private fun startFilter() {
        Common.showLog("--------------开始筛选")

        val filterSizeCovert = filterSizeCovert(fileType, filterSize)
        when (binding.recyclerView.adapter) {
            //当前是时间排序
            is SortDisplayAdapter -> {
                //确定当前排序
                val list = if (sortReverse) sortByDateReverse else sortedByDatePositive
                list.filterWithinDateRange(
                    filterDate,
                    startDate = if (filterDate == FILTER_DATE_CUSTOMER) filterStartDate else null,
                    endDate = if (filterDate == FILTER_DATE_CUSTOMER) filterEndDate else null
                ).run {
                    when (fileType) {
                        FileType.PHOTO,FileType.DOCUMENT -> {
                            filterBySize(filterSizeCovert.first, filterSizeCovert.second)
                        }

                        else -> {
                            filterByDuration(filterSizeCovert.first, filterSizeCovert.second)
                        }
                    }

                }.let { currentList ->
                    checkRefreshDisPlaySelected(list1 = currentList)
                    dateAdapter?.resetAllValue(null)
                    dateAdapter?.setData(currentList)
                    resetCurrentDateList(currentList)
                }

            }
            //当前是大小排序
            is SortDisplayChildAdapter -> {
                val list = if (sortReverse) sortBySizeBigToSmall else sortBySizeSmallToBig
                list.filterWithinDateRangeList(
                    filterDate,
                    startDate = if (filterDate == FILTER_DATE_CUSTOMER) filterStartDate else null,
                    endDate = if (filterDate == FILTER_DATE_CUSTOMER) filterEndDate else null
                ).run {
                    when (fileType) {
                        FileType.PHOTO,FileType.DOCUMENT-> {
                            filterBySizeList(filterSizeCovert.first, filterSizeCovert.second)
                        }

                        else -> {
                            filterByDurationList(filterSizeCovert.first, filterSizeCovert.second)
                        }
                    }
                }.let { currentList ->
                    checkRefreshDisPlaySelected(list2 = currentList)
                    sizeSortAdapter?.setData(currentList)
                    resetCurrentSizeList(currentList)
                }
            }
        }
    }


    /**
     * 数据筛选或者缩略图切换显示后，对比刷新实际显示的选中数据
     */
    private fun checkRefreshDisPlaySelected(
        list1: List<Pair<String, List<ResultDataFiles>>>? = null,
        list2: List<ResultDataFiles>? = null
    ) {
        lifecycleScope.launch {
            list1?.let {
                val checkSelectListContain =
                    Common.checkSelectListContainDateAsync(it, allSelectedSetList)
                viewModel.filterResetDisplayFlow(checkSelectListContain.second)
            }

            list2?.let {
                val checkSelectListContain =
                    Common.checkSelectListContainSize(it, allSelectedSetList)
                viewModel.filterResetDisplayFlow(checkSelectListContain.second)
            }


        }

    }


    private fun filterSizeCovert(fileType: FileType, filterSize: String): Pair<Long, Long> {
        when (fileType) {
            FileType.PHOTO -> {
                val stringArray = resources.getStringArray(R.array.filter_size_photo)
                return when (filterSize) {
                    stringArray[0] -> Pair(-1L, -1L)
                    stringArray[1] -> Pair(0L, 1.mbToBytes())
                    stringArray[2] -> Pair(1.mbToBytes(), 5.mbToBytes())
                    stringArray[3] -> Pair(5.mbToBytes(), Long.MAX_VALUE)
                    else -> Pair(-1L, -1L)
                }
            }

            FileType.VIDEO, FileType.AUDIO -> {
                val stringArray = resources.getStringArray(R.array.filter_duration_video_audio)
                return when (filterSize) {
                    stringArray[0] -> Pair(-1L, -1L)
                    stringArray[1] -> Pair(0L, 5.minutesToMillisecond())
                    stringArray[2] -> Pair(5.minutesToMillisecond(), 20.minutesToMillisecond())
                    stringArray[3] -> Pair(20.minutesToMillisecond(), 60.minutesToMillisecond())
                    stringArray[4] -> Pair(60.minutesToMillisecond(), Long.MAX_VALUE)
                    else -> Pair(-1L, -1L)
                }
            }

            FileType.DOCUMENT-> {
                val stringArray = resources.getStringArray(R.array.filter_documents_size)
                return when (filterSize) {
                    stringArray[0] -> Pair(-1L, -1L)
                    stringArray[1] -> Pair(0L, 500.kbToBytes())
                    stringArray[2] -> Pair(500.kbToBytes(), 1.mbToBytes())
                    stringArray[3] -> Pair(1.mbToBytes(), Long.MAX_VALUE)
                    else -> Pair(-1L, -1L)
                }
            }
        }

    }

    /**
     * 显示筛选开始日期弹窗
     */
    private fun showStartDateDialog(isNeedSetSelected: Boolean, currentDate: Date?) {

        dialogCustomerDateStart = dialogCustomerDateStart ?: DatePickerDialogFragment(
            this,
            getString(R.string.start_date),
            onPickerChooseListener = {}, onClickCancel = {})
        dialogCustomerDateStart?.run {
            currentDate?.let {
                setCurrentSelectedDate(it)
            }
            onPickerChooseListener = { selectedDate ->
                filterStartDate = selectedDate
                Log.d("showStartDateDialog", "isFirst=${isNeedSetSelected}--------")
                showEndDateDialog(isNeedSetSelected, null)

            }
            onClickCancel = {

            }
            show(supportFragmentManager, "")

        }

    }

    /**
     * 显示筛选结束日期弹窗
     */
    private fun showEndDateDialog(isNeedSetSelected: Boolean, currentDate: Date?) {
        dialogCustomerDateEnd = dialogCustomerDateEnd ?: DatePickerDialogFragment(
            this,
            getString(R.string.end_date),
            onPickerChooseListener = {}, onClickCancel = {})
        dialogCustomerDateEnd?.run {
            currentDate?.let {
                setCurrentSelectedDate(it)
            }
            filterStartDate?.let { setRangeDate(it) }
            onPickerChooseListener = { selectedDate ->
                filterEndDate = selectedDate
                if (isNeedSetSelected) {
                    filterDatePopupWindows?.updateSelectPos(4, filterStartDate!!, filterEndDate!!)
                    startFilter()
                    filterDatePopupWindows?.dismiss()
                    binding.titleDate.text = resources.getStringArray(R.array.filter_date)[4]
                } else {
                    filterDatePopupWindows?.updateStartEndDate(filterStartDate, filterEndDate)
                    if (filterDate == FILTER_DATE_CUSTOMER) {
                        startFilter()
                        filterDatePopupWindows?.dismiss()
                    }
                }

            }
            onClickCancel = {
//                filterDatePopupWindows?.dismiss()
            }
            show(supportFragmentManager, "")
        }
    }


    /**
     * 删除或者恢复完成
     * @param type 0  恢复  1 删除
     */
    private fun complete(number: Int, type: Int) {
        startActivity(Intent(this@SortingActivity, RecoverySuccessActivity::class.java).apply {
            putExtra(RecoverySuccessActivity.KEY_SUCCESS_COUNT, number)
            putExtra(RecoverySuccessActivity.KEY_SUCCESS_TYPE, type)
            putExtra(Common.KEY_FILE_TYPE, fileType.value)
        })
        if (type == 1) {
            lifecycleScope.launch {
                val deferredResults = withContext(Dispatchers.Default) {
                    filterSelectedSetList.let { deletedData ->
                        //删除后，处理当前实际显示的数据
                        val newSizeList = currentSizeList?.let {
                            Common.removeSelectedFromSizeList(
                                it,
                                deletedData
                            )
                        }
                        val newDateList = currentDateList?.let {
                            Common.removeSelectedFromList(it, deletedData)
                        }

                        //后续用于筛选的原始数据更新
                        sortBySizeBigToSmall =
                            Common.removeSelectedFromSizeList(sortBySizeBigToSmall, deletedData)
                        sortBySizeSmallToBig =
                            Common.removeSelectedFromSizeList(sortBySizeSmallToBig, deletedData)
                        sortByDateReverse =
                            Common.removeSelectedFromList(sortByDateReverse, deletedData)
                        sortedByDatePositive =
                            Common.removeSelectedFromList(sortedByDatePositive, deletedData)


                        // 一次性返回结果
                        mapOf(
                            "sizeList" to newSizeList,
                            "dateList" to newDateList,
                        )
                    }
                }

                withContext(Dispatchers.Main) {
                    //选中集合的更新
                    viewModel.afterDeleted()
                    deferredResults["sizeList"]?.let { list ->
                        list as List<ResultDataFiles>
                        Common.showLog("---------更新 sizeList = ${list.size}")
                        sizeSortAdapter?.setData(list)
                        resetCurrentSizeList(list)
                    }
                    deferredResults["dateList"]?.let { list ->
                        list as List<Pair<String, List<ResultDataFiles>>>
                        Common.showLog("---------更新 dateList = ${list.size}")
                        dateAdapter?.setData(list)
                        resetCurrentDateList(list)
                    }

                }
            }
        }
    }

    private fun setSingleDelete() {
        RecoverOrDeleteManager.setOnSingleDeleteCompleteListener { deletedData ->
            lifecycleScope.launch {
                val deferredResults = withContext(Dispatchers.Default) {
                    //删除后，处理当前实际显示的数据
                    val newSizeList = currentSizeList?.let {
                        it.filterNot { it == deletedData }
                    }
                    val newDateList = currentDateList?.removeItem(deletedData)

                    //后续用于筛选的原始数据更新
                    sortBySizeBigToSmall = sortBySizeBigToSmall.filterNot { it == deletedData }
                    sortBySizeSmallToBig = sortBySizeSmallToBig.filterNot { it == deletedData }
                    sortByDateReverse = sortByDateReverse.removeItem(deletedData)
                    sortedByDatePositive = sortedByDatePositive.removeItem(deletedData)

                    // 一次性返回结果
                    mapOf(
                        "sizeList" to newSizeList,
                        "dateList" to newDateList,
                    )

                }

                withContext(Dispatchers.Main) {
                    //选中集合的更新
                    viewModel.afterSingleDeleted(deletedData)
                    deferredResults["sizeList"]?.let { list ->
                        list as List<ResultDataFiles>
                        Common.showLog("---------更新 sizeList = ${list.size}")
                        sizeSortAdapter?.setData(list)
                        resetCurrentSizeList(list)
                    }
                    deferredResults["dateList"]?.let { list ->
                        list as List<Pair<String, List<ResultDataFiles>>>
                        Common.showLog("---------更新 dateList = ${list.size}")
                        dateAdapter?.setData(list)
                        resetCurrentDateList(list)
                    }

                }
            }
        }
    }

    private fun initSearch() {
        binding.run {
            iconClearSearch.setOnClickListener {
                etSearch.text.clear()
                checkTypeAfter {
                    if (it) {
                        currentDateList?.let { data ->
                            dateAdapter?.setData(data)
                            checkRefreshDisPlaySelected(list1 = data)
                        }

                    } else {
                        currentSizeList?.let { data ->
                            sizeSortAdapter?.setData(data)
                            checkRefreshDisPlaySelected(list2 = data)
                        }
                    }
                }

            }
            etSearch.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    val toString = s?.trim().toString()
                    toString.let { keyword ->
                        checkTypeAfter {
                            if (it) {
                                currentDateList?.let {
                                    val searchByName = Common.searchByName(it, keyword)
                                    dateAdapter?.setData(searchByName)
                                    Common.showLog("----------搜索更新数据0000000000")
                                    checkRefreshDisPlaySelected(list1 = searchByName)
                                }
                            } else {
                                currentSizeList?.let {
                                    val searchByName = Common.searchByNameList(it, keyword)
                                    sizeSortAdapter?.setData(searchByName)
                                    Common.showLog("----------搜索更新数据111111")
                                    checkRefreshDisPlaySelected(list2 = searchByName)
                                }
                            }
                        }
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(
                    s: CharSequence?,
                    start: Int,
                    before: Int,
                    count: Int
                ) {

                }

            })
        }

    }

    private fun checkTypeAfter(onAction: (isDateSort: Boolean) -> Unit) {
        when (binding.recyclerView.adapter) {
            is SortDisplayAdapter -> {
                onAction(true)
            }

            is SortDisplayChildAdapter -> {
                onAction(false)
            }
        }
    }

}