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.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.setItemSelect
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
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.filterWithinDateRange
import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterWithinDateRangeList
//import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterWithinMonths
//import com.ux.video.file.filerecovery.utils.ExtendFunctions.filterWithinMonthsList
import com.ux.video.file.filerecovery.utils.ExtendFunctions.getParcelableArrayListExtraCompat
import com.ux.video.file.filerecovery.utils.ExtendFunctions.mbToBytes
import com.ux.video.file.filerecovery.utils.GridSpacingItemDecoration
import com.ux.video.file.filerecovery.utils.ScanManager
import com.ux.video.file.filerecovery.utils.ScanManager.copySelectedFilesAsync
import com.ux.video.file.filerecovery.utils.ScanManager.deleteFilesAsync
import com.ux.video.file.filerecovery.utils.ScanRepository
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 sortDialogFragment: SortDialogFragment? = null
    private var columns = 3
    private var dateAdapter: PhotoDisplayDateAdapter? = null

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

    private var dialogRecovering: RecoveringDialogFragment? = null

    private var dialogDeleting: DeletingDialogFragment? = 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 = FILTER_SIZE_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>>>


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

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


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

    override fun initData() {
        super.initData()

        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()
        }
        binding.imageViewBack.setOnClickListener { finish() }
        list?.let {

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

            sizeSortAdapter = PhotoDisplayDateChildAdapter(
                this@PhotoSortingActivity,
                columns, viewModel,
                { path, isAdd, allSelected ->
                    viewModel.toggleSelection(isAdd, path)
                }) { item ->
                startActivity(
                    Intent(
                        this@PhotoSortingActivity,
                        PhotoInfoActivity::class.java
                    ).apply {
                        putExtra(PhotoInfoActivity.KEY_CLICK_ITEM, item)
                    })

            }
            dateAdapter =
                PhotoDisplayDateAdapter(
                    this@PhotoSortingActivity,
                    columns,
                    viewModel,
                    { actionPath, isAdd ->
                        viewModel.toggleSelection(isAdd, actionPath)
                    }) { item ->
                    startActivity(
                        Intent(
                            this@PhotoSortingActivity,
                            PhotoInfoActivity::class.java
                        ).apply {
                            putExtra(PhotoInfoActivity.KEY_CLICK_ITEM, item)
                        })
                }.apply {
                    setData(sortByDateReverse)
                }
            setDateAdapter()
            setFilter()
            binding.run {
                tvRecover.setOnClickListener {
                    showRecoveringDialog()
                    lifecycleScope.copySelectedFilesAsync(
                        selectedSet = filterSelectedSetList,
                        folder = Common.recoveryPhotoDir,
                        onProgress = { currentCounts: Int, fileName: String, success: Boolean ->
                            ScanManager.showLog(
                                "--------恢复图片 ",
                                "----------${currentCounts} ${fileName}"
                            )
                            dialogRecovering?.updateProgress(currentCounts)

                        }) { counts ->
                        dialogRecovering?.updateProgress(counts)
                        ScanManager.showLog("--------恢复图片 ", "----------恢复完成 ${counts}")
                    }

                }
                tvDelete.setOnClickListener {
                    showDeletingDialog()
                    lifecycleScope.deleteFilesAsync(
                        selectedSet = filterSelectedSetList,
                        onProgress = { currentCounts: Int, path: String, success: Boolean ->
                            ScanManager.showLog(
                                "--------删除图片 ",
                                "----------${currentCounts} ${path}"
                            )
                            dialogDeleting?.updateProgress(currentCounts)
                        }) { counts ->
                        dialogDeleting?.updateProgress(counts)
                        ScanManager.showLog("--------恢复图片 ", "----------恢复完成 ${counts}")
                    }

                }
                imSort.setOnClickListener {
                    sortDialogFragment = sortDialogFragment ?: SortDialogFragment {
                        when (it) {
                            SORT_ASC_DATE -> {
                                setDateAdapter()
                                dateAdapter?.setData(sortedByDatePositive)
                                sortReverse = false
                            }

                            SORT_DESC_DATE -> {
                                setDateAdapter()
                                dateAdapter?.setData(sortByDateReverse)
                                sortReverse = true
                            }

                            SORT_DESC_SIZE -> {
                                setSizeAdapter()
                                sizeSortAdapter?.setData(sortBySizeBigToSmall)
                                sortReverse = true
                            }

                            SORT_ASC_SIZE -> {
                                setSizeAdapter()
                                sizeSortAdapter?.setData(sortBySizeSmallToBig)
                                sortReverse = false
                            }
                        }
                    }
                    sortDialogFragment?.show(supportFragmentManager, "")
                }

                //全选按钮  只对当前显示的数据有效
                tvSelectAll.setOnClickListener {
                    it.isSelected = !it.isSelected
                    dateAdapter?.setAllSelected(it.isSelected)
                    sizeSortAdapter?.setAllSelected(it.isSelected)

                }
            }
        }

    }

    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
                    binding.tvSelectAll.isSelected = it == adapter.getTotalChildCount()
                }

                is PhotoDisplayDateChildAdapter -> {
                    binding.tvSelectAll.isSelected = it == binding.recyclerView.adapter?.itemCount
                }
            }
        }
    }

    private fun setDateAdapter() {
        binding.recyclerView.run {
            adapter = dateAdapter?.apply { setColumns(columns) }
            layoutManager = LinearLayoutManager(this@PhotoSortingActivity)
            val bPx = 16.dpToPx(context)
            setPadding(0, 0, 0, 0)
            clipToPadding = false


        }
    }

    private fun setSizeAdapter() {
        binding.recyclerView.run {
            val aPx = 16.dpToPx(context)
            val bPx = 6.dpToPx(context)
            setPadding(aPx, 0, bPx, 0)
            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
                                    startFilter()
                                }

                                data[1] -> {
                                    filterDate = FILTER_DATE_1
                                    startFilter()
                                }

                                data[2] -> {
                                    filterDate = FILTER_DATE_6
                                    startFilter()
                                }

                                data[3] -> {
                                    filterDate = FILTER_DATE_24
                                    startFilter()
                                }

                                data[4] -> {
                                    filterDate = FILTER_DATE_CUSTOMER
                                    if (showDialog)
                                        showStartDateDialog(true,null)
                                    else {
                                        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)
                resources.getStringArray(R.array.filter_size).let { data ->
                    filterSizePopupWindows = filterSizePopupWindows ?: FilterPopupWindows(
                        this@PhotoSortingActivity,
                        data,
                        0,
                        { clickValue ->
                            when (clickValue) {
                                data[0] -> filterSize = FILTER_SIZE_ALL
                                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)
        }


    }

    /**
     * 执行筛选结果
     */
    private fun startFilter() {
        Common.showLog("--------------开始筛选")
        when (binding.recyclerView.adapter) {
            //当前是时间排序
            is PhotoDisplayDateAdapter -> {
                //确定当前排序
                val list = if (sortReverse) sortByDateReverse else sortedByDatePositive
                val filterSizeCovert = filterSizeCovert(filterSize)
                list.filterWithinDateRange(
                    filterDate,
                    startDate = if (filterDate == FILTER_DATE_CUSTOMER) filterStartDate else null,
                    endDate = if (filterDate == FILTER_DATE_CUSTOMER) filterEndDate else null
                )
                    .filterBySize(filterSizeCovert.first, filterSizeCovert.second)
                    .let { currentList ->
                        //对筛选后的数据与实际选中集合对比 ，得出筛选后显示的数据中的选中数据
                        val checkSelectListContain =
                            Common.checkSelectListContainDate(currentList, allSelectedSetList)
                        updateButtonCounts(checkSelectListContain.first)
                        viewModel.filterResetDisplayFlow(checkSelectListContain.second)

                        Common.showLog("筛选后重置 allSelectedSetList=${allSelectedSetList.size}  filterSelectedSetList=${filterSelectedSetList.size}  Thread=${Thread.currentThread().name}")
                        dateAdapter?.resetAllValue(null)
                        dateAdapter?.setData(currentList)

                    }

            }
            //当前是大小排序
            is PhotoDisplayDateChildAdapter -> {
                val list = if (sortReverse) sortBySizeBigToSmall else sortBySizeSmallToBig
                val filterSizeCovert = filterSizeCovert(filterSize)
                list.filterWithinDateRangeList(
                    filterDate,
                    startDate = if (filterDate == FILTER_DATE_CUSTOMER) filterStartDate else null,
                    endDate = if (filterDate == FILTER_DATE_CUSTOMER) filterEndDate else null
                )
                    .filterBySizeList(filterSizeCovert.first, filterSizeCovert.second)
                    .let { currentList ->
                        //对筛选后的数据与实际选中集合对比 ，得出筛选后显示的数据中的选中数据
                        val checkSelectListContain =
                            Common.checkSelectListContainSize(currentList, allSelectedSetList)
                        updateButtonCounts(checkSelectListContain.first)
                        viewModel.filterResetDisplayFlow(checkSelectListContain.second)
                        sizeSortAdapter?.setData(currentList)
                    }
            }
        }
    }


    private fun filterSizeCovert(filterSize: Int): Pair<Long, Long> {
        return when (filterSize) {
            FILTER_SIZE_ALL -> Pair(-1L, -1L)
            FILTER_SIZE_1 -> Pair(0L, 1.mbToBytes())
            FILTER_SIZE_5 -> Pair(1L, 5.mbToBytes())
            FILTER_SIZE_OVER_5 -> Pair(5.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
//                filterDatePopupWindows?.updateStartEndDate(start = selectedDate)
                Log.d("showStartDateDialog", "isFirst=${isNeedSetSelected}--------")
                showEndDateDialog(isNeedSetSelected,null)

//                if (isFirst) {
//                    showEndDateDialog(true)
//                } else {
//                    if (filterDate == FILTER_DATE_CUSTOMER) {
//                        startFilter()
//                        filterDatePopupWindows?.dismiss()
//                    }
//                }
            }
            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()
                }else{
                    filterDatePopupWindows?.updateStartEndDate(filterStartDate,filterEndDate)
                    if (filterDate == FILTER_DATE_CUSTOMER) {
                        startFilter()
                        filterDatePopupWindows?.dismiss()
                    }
                }

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

    private fun showRecoveringDialog() {
        dialogRecovering =
            dialogRecovering ?: RecoveringDialogFragment(filterSelectedSetList.size) {
                complete()
            }
        dialogRecovering?.show(supportFragmentManager, "")
    }

    private fun showDeletingDialog() {
        dialogDeleting = dialogDeleting ?: DeletingDialogFragment(filterSelectedSetList.size) {
            complete()
        }
        dialogDeleting?.show(supportFragmentManager, "")
    }

    /**
     * 删除或者恢复完成
     */
    private fun complete() {
        dialogDeleting?.dismiss()
        dialogRecovering?.dismiss()
        startActivity(Intent(this@PhotoSortingActivity, RecoverySuccessActivity::class.java))
    }
}