package com.base.scanqrclear.luma

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.scanqrclear.R
import com.base.scanqrclear.bean.SimilarBean
import com.base.scanqrclear.databinding.ActivitySimilarPhotosBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.Semaphore

class SimilarPhotosActivity : BaseActivity2() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, SimilarPhotosActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var adapter: SimilarPhotosAdapter

    private val semaphore = Semaphore(20)
    private var isScanning = true

    private val binding by lazy {
        ActivitySimilarPhotosBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
        showAnimationAd(LottieType.SIMILAR_PHOTOS) {
            if (isScanning) {
//                loadingDialog = DialogHelps.showLoadingDialog(this)
            }
        }
        AdmobHelps.showNativeAd(this, completed = {
            binding.adNative.setNativeAd(it)
        }, maxCompleted = { nativeAdLoader, nativeMaxAd ->
            binding.adNative.setNativeAd(nativeAdLoader, nativeMaxAd)
        })
        onBackPressedDispatcher.addCallback {
            handleBackPressed(this@SimilarPhotosActivity)
        }
    }

    private fun initView() {
        adapter = SimilarPhotosAdapter()
        adapter.callback = object : BaseAdapter.OnClickCallback<SimilarBean> {
            override fun onClicked(view: View, position: Int, item: SimilarBean) {
                val list = getAllList(adapter.list)
                val total = list.filter { it.isSelect }.sumOf { it.size }
                showSelection(total > 0, total)
            }
        }
        binding.rvPhoto.adapter = adapter
        binding.rvPhoto.layoutManager = LinearLayoutManager(this)

        binding.flBack.setOnClickListener { backPressed() }
        binding.ivSelect.setOnCheckedChangeListener { _, isChecked ->
            setSelectAll(isChecked, adapter.list)
        }
        binding.tvDelete.setOnClickListener {
            val list = getAllList(adapter.list).filter { it.isSelect }
            if (list.isEmpty()) return@setOnClickListener
            val total = list.sumOf { it.size }
            DialogHelps.showDeleteDialog(this, binding.tvDelete) {
                showAnimationAd {
                    toCleanResult(total, getString(R.string.similar_photos))
                }
                deleteFiles(list)
            }
        }
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val images = MediaHelps.findImageFiles(this@SimilarPhotosActivity)
            val similarBeans = images.mapNotNull { value ->
                lifecycleScope.async(Dispatchers.IO) {
                    semaphore.acquire() // 请求许可
                    try {
                        ImageHelpers.createImage(value.path)
                    } finally {
                        semaphore.release() // 释放许可
                    }
                }.await()
            }
//            val similarBeans = deferredSimilarBeans.mapNotNull { it.await() }
            val hasSame = mutableSetOf<String>()
            similarBeans.forEach { similar ->
                if (hasSame.contains(similar.url)) return@forEach
                hasSame.add(similar.url)
                similar.items.add(similar)
                similarBeans.forEach {
                    if (!hasSame.contains(it.url) && ImageHelpers.similarCondition(similar, it)) {
                        hasSame.add(it.url)
                        similar.items.add(it)
                    }
                }
            }
            val list = similarBeans.filter { it.items.size > 1 }
            withContext(Dispatchers.Main) {
                isScanning = false
                loadingDialog?.dismiss()
                setSelectAll(true, list)
            }
        }
    }

    private fun setSelectAll(isSelected: Boolean, list: List<SimilarBean>) {
        binding.ivSelect.isSelected = isSelected
        list.forEach { similar ->
            similar.items.forEachIndexed { index, similarBean ->
                similarBean.isSelect = if (index > 0) isSelected else false
            }
        }
        adapter.submitList(list)
        val total = getAllList(adapter.list).filter { it.isSelect }.sumOf { it.size }
        showSelection(isSelected && list.isNotEmpty(), total)
    }

    private fun deleteFiles(list: List<SimilarBean>) {
        lifecycleScope.launch(Dispatchers.IO) {
            val paths = list.map { it.url }.toTypedArray()
            paths.forEach { FileHelps.deleteFile(it) }
            withContext(Dispatchers.Main) {
                MediaHelps.updateMedia(applicationContext, paths)
            }
        }
    }

    private fun showSelection(isSelection: Boolean, total: Long) {
        binding.tvDelete.setBackgroundResource(if (isSelection) R.drawable.gradient else R.drawable.gradient_not_clickable)
        val delete = getString(R.string.delete)
        binding.tvDelete.text =
            if (total > 0) "${delete} (${Utils.getFormatSize(total)})" else delete
    }

    private fun getAllList(beans: List<SimilarBean>): MutableList<SimilarBean> {
        val list = mutableListOf<SimilarBean>()
        beans.forEach { it.items.forEach { list.add(it) } }
        return list
    }
}