package com.ux.video.file.filerecovery.photo

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
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.success.RecoverySuccessActivity
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.Common.KEY_SCAN_TYPE
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_audio
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_deleted_audio
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_deleted_documents
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_deleted_photo
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_deleted_video
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_documents
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_photo
import com.ux.video.file.filerecovery.utils.Common.VALUE_SCAN_TYPE_video
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.getParcelableArrayListExtraCompat
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.GridSpacingItemDecoration
import com.ux.video.file.filerecovery.utils.ScanRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Date

class PhotoSortingActivity : 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 FILTER_SIZE_ALL = -1
        val FILTER_SIZE_1 = 1
        val FILTER_SIZE_5 = 2
        val FILTER_SIZE_OVER_5 = 3

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

    private var scanType: Int = VALUE_SCAN_TYPE_photo

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

    //文件大小排序使用的适配器
    private var sizeSortAdapter: PhotoDisplayDateChildAdapter? = 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<ResultPhotosFiles>
    private lateinit var sortBySizeSmallToBig: List<ResultPhotosFiles>
    private lateinit var sortByDateReverse: List<Pair<String, List<ResultPhotosFiles>>>
    private lateinit var sortedByDatePositive: List<Pair<String, List<ResultPhotosFiles>>>

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

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

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

    private lateinit var mItemDecoration: GridSpacingItemDecoration

    private lateinit var sizeFilterItemArray: Array<String>


    private lateinit var viewModel: ScanRepository
    override fun inflateBinding(inflater: LayoutInflater): ActivityPhotoSortingBinding =
        ActivityPhotoSortingBinding.inflate(inflater)

    override fun initData() {
        super.initData()
        scanType = intent.getIntExtra(KEY_SCAN_TYPE, VALUE_SCAN_TYPE_photo)
        val list: ArrayList<ResultPhotosFiles>? =
            intent.getParcelableArrayListExtraCompat(KEY_PHOTO_FOLDER_FILE)
        mItemDecoration =
            GridSpacingItemDecoration(columns, Common.itemSpacing, Common.horizontalSpacing)
        updateButtonCounts(0)
        viewModel = ViewModelProvider(this).get(ScanRepository::class.java)

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

        viewModel.selectedDisplayLiveData.observe(this) { displaySet ->
            filterSelectedSetList = displaySet
            Common.showLog("当前显示筛选数据 选中状态更新: ${displaySet.size}")
            updateCurrentIsAllSelectStatus()
        }
        setScanTypeView()
        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 = PhotoDisplayDateChildAdapter(
                this@PhotoSortingActivity,
                scanType,
                columns, viewModel,
                { resultPhotosFiles, isAdd, allSelected ->
                    viewModel.toggleSelection(isAdd, resultPhotosFiles)
                }, { hide ->


                }) { item ->
                startActivity(
                    Intent(
                        this@PhotoSortingActivity,
                        PhotoInfoActivity::class.java
                    ).apply {
                        putExtra(KEY_SCAN_TYPE,scanType)
                        putExtra(PhotoInfoActivity.KEY_CLICK_ITEM, item)
                    })

            }
            dateAdapter =
                PhotoDisplayDateAdapter(
                    this@PhotoSortingActivity,
                    scanType,
                    columns,
                    viewModel,
                    { actionPath, isAdd ->
                        viewModel.toggleSelection(isAdd, actionPath)
                    }) { item ->
                    startActivity(
                        Intent(
                            this@PhotoSortingActivity,
                            PhotoInfoActivity::class.java
                        ).apply {
                            putExtra(KEY_SCAN_TYPE,scanType)
                            putExtra(PhotoInfoActivity.KEY_CLICK_ITEM, item)
                        })
                }.apply {
                    setData(sortByDateReverse)
                    resetCurrentDateList(sortByDateReverse)
                }
            setDateAdapter()
            setSingleDelete()
            setFilter()
            setAllClick()

        }

    }

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

                            }
                        }

                    }

                    is PhotoDisplayDateChildAdapter -> {
                        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 PhotoDisplayDateAdapter -> {
                        dateAdapter?.setAllSelected(it.isSelected)
                        dateAdapter?.getCurrentData()?.let {
                            it as List<Pair<String, List<ResultPhotosFiles>>>
                            if (it.size > 0)
                                Common.showLog("------------全选按钮  日期-${it.size} ${it[0].second[0].path}")
                        }

                    }

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


            }
        }
    }


    /**
     * 不同类型下的ui和功能点区分
     */
    private fun setScanTypeView() {
        binding.run {
            when (scanType) {
                VALUE_SCAN_TYPE_photo, VALUE_SCAN_TYPE_deleted_photo -> {
                    titleSize.text = getString(R.string.size)
                    filterLayoutLinearlayout.isVisible = true
                    relativeThumbnails.isVisible = true
                    sizeFilterItemArray = resources.getStringArray(R.array.filter_size_photo)
                }

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

                VALUE_SCAN_TYPE_audio, VALUE_SCAN_TYPE_deleted_audio -> {
                    titleSize.text = getString(R.string.duration)
                    filterLayoutLinearlayout.isVisible = false
                    relativeThumbnails.isVisible = false
                    sizeFilterItemArray =
                        resources.getStringArray(R.array.filter_duration_video_audio)
                }

                VALUE_SCAN_TYPE_documents, VALUE_SCAN_TYPE_deleted_documents -> {
                    titleSize.text = getString(R.string.size)
                    filterLayoutLinearlayout.isVisible = false
                    relativeThumbnails.isVisible = false
                    sizeFilterItemArray = resources.getStringArray(R.array.filter_documents_size)
                }
            }

        }
    }

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

                }

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


    }

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

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

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

    }

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

    private fun resetCurrentDateList(currentList: List<Pair<String, List<ResultPhotosFiles>>>) {
        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@PhotoSortingActivity)
            setPadding(0, 0, 0, 70.dpToPx(context))
            clipToPadding = false
        }
    }

    private fun setSizeAdapter() {
        binding.recyclerView.run {
            val aPx = 16.dpToPx(context)
            val bPx = 6.dpToPx(context)
            setPadding(aPx, 0, bPx, 70.dpToPx(context))
            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@PhotoSortingActivity,
                        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@PhotoSortingActivity,
                        data,
                        0,
                        { clickValue ->
                            titleSize.text = clickValue
                            filterSize = clickValue
//                            when (clickValue) {
//                                data[0] -> filterSize = clickValue
//                                data[1] -> filterSize = FILTER_SIZE_1
//                                data[2] -> filterSize = FILTER_SIZE_5
//                                data[3] -> filterSize = FILTER_SIZE_OVER_5
//                            }
                            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@PhotoSortingActivity,
                        data,
                        1,
                        { clickValue ->
                            when (clickValue) {
                                data[0] -> columns = 2
                                data[1] -> columns = 3
                                data[2] -> columns = 4
                            }
                            when (binding.recyclerView.adapter) {
                                is PhotoDisplayDateAdapter -> {
                                    dateAdapter?.setColumns(columns)
                                }

                                is PhotoDisplayDateChildAdapter -> {
                                    binding.recyclerView.layoutManager =
                                        GridLayoutManager(this@PhotoSortingActivity, 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(scanType, filterSize)
        when (binding.recyclerView.adapter) {
            //当前是时间排序
            is PhotoDisplayDateAdapter -> {
                //确定当前排序
                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 (scanType) {
                        VALUE_SCAN_TYPE_photo, VALUE_SCAN_TYPE_deleted_photo, VALUE_SCAN_TYPE_documents, VALUE_SCAN_TYPE_deleted_documents -> {
                            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 PhotoDisplayDateChildAdapter -> {
                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 (scanType) {
                        VALUE_SCAN_TYPE_photo, VALUE_SCAN_TYPE_deleted_photo, VALUE_SCAN_TYPE_documents, VALUE_SCAN_TYPE_deleted_documents -> {
                            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<ResultPhotosFiles>>>? = null,
        list2: List<ResultPhotosFiles>? = 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(scanType: Int, filterSize: String): Pair<Long, Long> {
        when (scanType) {
            VALUE_SCAN_TYPE_photo, VALUE_SCAN_TYPE_deleted_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)
                }
            }

            VALUE_SCAN_TYPE_video, VALUE_SCAN_TYPE_deleted_video, VALUE_SCAN_TYPE_audio, VALUE_SCAN_TYPE_deleted_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)
                }
            }

            VALUE_SCAN_TYPE_documents, VALUE_SCAN_TYPE_deleted_documents -> {
                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)
                }
            }
        }

        return 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@PhotoSortingActivity, RecoverySuccessActivity::class.java).apply {
            putExtra(RecoverySuccessActivity.KEY_SUCCESS_COUNT, number)
            putExtra(RecoverySuccessActivity.KEY_SUCCESS_TYPE, type)
        })
        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<ResultPhotosFiles>
                        Common.showLog("---------更新 sizeList = ${list.size}")
                        sizeSortAdapter?.setData(list)
                        resetCurrentSizeList(list)
                    }
                    deferredResults["dateList"]?.let { list ->
                        list as List<Pair<String, List<ResultPhotosFiles>>>
                        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<ResultPhotosFiles>
                        Common.showLog("---------更新 sizeList = ${list.size}")
                        sizeSortAdapter?.setData(list)
                        resetCurrentSizeList(list)
                    }
                    deferredResults["dateList"]?.let { list ->
                        list as List<Pair<String, List<ResultPhotosFiles>>>
                        Common.showLog("---------更新 dateList = ${list.size}")
                        dateAdapter?.setData(list)
                        resetCurrentDateList(list)
                    }

                }
            }
        }
    }


}