package com.swiftcleaner.chovey.view.activity

import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.business.EventUtils.event
import com.swiftcleaner.chovey.business.admob.AdmobManager
import com.swiftcleaner.chovey.business.admob.AdmobManager.showInterstitialAd
import com.swiftcleaner.chovey.business.admob.AdmobManager.showNativeAd
import com.swiftcleaner.chovey.databinding.ActivitySimilarPhotosBinding
import com.swiftcleaner.chovey.model.bean.ImageHelpers
import com.swiftcleaner.chovey.model.bean.SimilarBean
import com.swiftcleaner.chovey.model.tool.FileHelps
import com.swiftcleaner.chovey.model.tool.MediaHelps
import com.swiftcleaner.chovey.model.util.FinishMain.finishToMain
import com.swiftcleaner.chovey.view.MainActivity
import com.swiftcleaner.chovey.view.adapter.SimilarPhotosAdapter
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog
import com.swiftcleaner.chovey.view.dialog.LoadingDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.DecimalFormat
import java.util.concurrent.Semaphore

class SimilarPhotosActivity : AppCompatActivity() {
    private val binding by lazy {
        ActivitySimilarPhotosBinding.inflate(layoutInflater)
    }
    private lateinit var similarPhotosAdapter: SimilarPhotosAdapter
    private val semaphore = Semaphore(20)
    private val REQUEST_ALL_FILES_ACCESS_PERMISSION = 100
    private val REQUEST_PERMISSION_CODE = 101
    private var imageGroups: List<SimilarBean> = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        event("page_SimilarPhotosActivity", "", null)
        initBar()
        initAnimotorPer()
        initShow()
    }

    private fun initShow() {
        similarPhotosAdapter = SimilarPhotosAdapter(this, ArrayList())
        binding.similarPhotosExrecy.adapter = similarPhotosAdapter
        binding.similarPhotosExrecy.layoutManager = LinearLayoutManager(this)
        initData()
        binding.ivReturn.setOnClickListener { v: View? -> initCustDialog() }
        binding.similarPhotosDeleteButton.setOnClickListener { v: View? ->
            val selectedItems = similarPhotosAdapter.selectedItems
            cleanFiles(selectedItems)
            Log.d("selectedItems", "selectedItems=" + selectedItems.size)
        }
        binding.switchId.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { compoundButton, isChecked ->
            if (imageGroups.isEmpty()) return@OnCheckedChangeListener
            toggleSelection(isChecked)
        })
    }

    //全选
    private fun toggleSelection(isChecked: Boolean) {
        Thread {
            for (group in imageGroups) {
                if (group.items.size > 1) {
                    for (i in 1 until group.items.size) {
                        val item = group.items[i]
                        item.isSelect = isChecked
                    }
                }
            }
            // Notify the adapter on the main thread
            runOnUiThread { similarPhotosAdapter.notifyDataSetChanged() }
        }.start()
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val images = MediaHelps.findImageFiles(this@SimilarPhotosActivity, 1024 * 100)
            val similarBeans = images.mapNotNull { value ->
                lifecycleScope.async(Dispatchers.IO) {
                    semaphore.acquire() // 请求许可
                    try {
                        ImageHelpers.createImage(value.path)
                    } finally {
                        semaphore.release() // 释放许可
                    }
                }.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)
                    }
                }
            }
            imageGroups = similarBeans.filter { it.items.size > 1 }
            Log.d("imageGroups", "111: $imageGroups") // 添加日志


            if (imageGroups.isNotEmpty()) {
                Log.d("imageGroups", "222: $imageGroups") // 添加日志
                withContext(Dispatchers.Main) {
                    showNativeAd(this@SimilarPhotosActivity, { nativeAd: NativeAd? ->
                        binding.flAdDonghua.removeAllViews()
                        binding.flAdDonghua.setNativeAd(nativeAd!!, R.layout.layout_ad_native)
                        null
                    }, null, null)
                    similarPhotosAdapter.setData(imageGroups)
                    val loadingDialog = LoadingDialog(this@SimilarPhotosActivity)
                    loadingDialog.show()
                    //判断广告是否展成功
                    if (AdmobManager.isShowAdInter()) {
                        showInterstitialAd(
                            this@SimilarPhotosActivity,
                            {
                                null
                            },
                            {
                                checkAndRequestPermissions()
                                binding.similarPhotosDeleteButton.visibility = View.VISIBLE
                                binding.radarview.setSearching(false)
                                binding.clRadarview.visibility = View.GONE
                                binding.flAdDonghua.removeAllViews()
                                loadingDialog.dismiss()
                                null
                            },
                            {
                                checkAndRequestPermissions()
                                binding.similarPhotosDeleteButton.visibility = View.VISIBLE
                                binding.radarview.setSearching(false)
                                binding.clRadarview.visibility = View.GONE
                                binding.flAdDonghua.removeAllViews()
                                loadingDialog.dismiss()
                                null
                            }, false
                        )
                    } else {
                        checkAndRequestPermissions()
                        binding.similarPhotosDeleteButton.visibility = View.VISIBLE
                        binding.radarview.setSearching(false)
                        binding.clRadarview.visibility = View.GONE
                        binding.flAdDonghua.removeAllViews()
                        loadingDialog.dismiss()
                    }
                }
            } else {
                withContext(Dispatchers.Main) {
                    showNativeAd(this@SimilarPhotosActivity, { nativeAd: NativeAd? ->
                        binding.flAdDonghua.removeAllViews()
                        binding.flAdDonghua.setNativeAd(nativeAd!!, R.layout.layout_ad_native)
                        null
                    }, null, null)
                    val loadingDialog = LoadingDialog(this@SimilarPhotosActivity)
                    loadingDialog.show()
                    //判断广告是否展成功
                    if (AdmobManager.isShowAdInter()) {
                        showInterstitialAd(
                            this@SimilarPhotosActivity,
                            {
                                null
                            },
                            {
                                checkAndRequestPermissions()
                                binding.similarPhotosDeleteButton.visibility = View.VISIBLE
                                binding.radarview.setSearching(false)
                                binding.clRadarview.visibility = View.GONE
                                binding.tvNotFound.visibility = View.VISIBLE
                                binding.flAdDonghua.removeAllViews()
                                loadingDialog.dismiss()
                                null
                            },
                            {
                                checkAndRequestPermissions()
                                binding.similarPhotosDeleteButton.visibility = View.VISIBLE
                                binding.radarview.setSearching(false)
                                binding.clRadarview.visibility = View.GONE
                                binding.tvNotFound.visibility = View.VISIBLE
                                binding.flAdDonghua.removeAllViews()
                                loadingDialog.dismiss()
                                null
                            }, false
                        )
                    } else {
                        checkAndRequestPermissions()
                        binding.similarPhotosDeleteButton.visibility = View.VISIBLE
                        binding.radarview.setSearching(false)
                        binding.clRadarview.visibility = View.GONE
                        binding.tvNotFound.visibility = View.VISIBLE
                        binding.flAdDonghua.removeAllViews()
                        loadingDialog.dismiss()
                    }

                }
            }
            showNativeAd(this@SimilarPhotosActivity, { nativeAd: NativeAd? ->
                binding.flAd.removeAllViews()
                binding.flAd.setNativeAd(nativeAd!!, R.layout.layout_ad_native)
                null
            }, null, null)
        }
    }

    private fun cleanFiles(selectedFiles: List<SimilarBean>) {
        // 更新媒体库
        Log.d("selectedFiles", "更新媒体库")
        lifecycleScope.launch(Dispatchers.IO) {
            val paths = selectedFiles.map { it.url }.toTypedArray()
            paths.forEach { FileHelps.deleteFile(it) }
            withContext(Dispatchers.Main) {
                MediaHelps.updateMedia(applicationContext, paths)
                val intent = Intent(this@SimilarPhotosActivity, EndCleanJunkActivity::class.java)
                intent.putExtra("cleanstr", formatFileSize(selectedFiles.sumOf { it.size }))
                startActivity(intent)
                finish()
            }
        }
    }

    private fun initBar() {
        ImmersionBar.with(this)
            .transparentStatusBar() // 透明状态栏
            .statusBarDarkFont(false) // 状态栏字体颜色为浅色
            .navigationBarDarkIcon(true) // 导航栏图标颜色为浅色
            .init()
    }

    private fun initCustDialog() {
        val activity: Activity = this
        val customScoreDialog = CustomScoreDialog(this)
        customScoreDialog.setOnDialogClickListener(object :
            CustomScoreDialog.OnDialogClickListener {
            override fun onCancel() {
                customScoreDialog.dismiss()
            }

            override fun onSubmit() {
                if (AdmobManager.isShowAdBackInter()) {
                    showInterstitialAd(
                        this@SimilarPhotosActivity, {
                            finishToMain(activity)
                            null
                        },
                        { null },
                        {
                            finishToMain(activity)
                            null
                        }, false
                    )
                } else {
                    finishToMain(activity)
                }
            }
        })
        customScoreDialog.show()
    }

    private fun initAnimotorPer() {
        binding.clRadarview.visibility = View.VISIBLE
        binding.radarview.setSearching(true)
        binding.similarPhotosDeleteButton.visibility = View.GONE
    }

    override fun onBackPressed() {
        initCustDialog()
    }

    private fun formatFileSize(size: Long): String {
        if (size <= 0) return "0 Bytes"
        val units = arrayOf("Bytes", "KB", "MB", "GB", "TB")
        val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
        return DecimalFormat("#,##0.#").format(
            size / Math.pow(
                1024.0,
                digitGroups.toDouble()
            )
        ) + " " + units[digitGroups]
    }

    private fun checkAndRequestPermissions() {
        if (!checkFilesAccessPermission(this)) {
            // 没有权限，请求权限
            requestFilesAccessPermission()
        }
    }

    private fun checkFilesAccessPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            val readPermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            val writePermission = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED
        }
    }

    private fun requestFilesAccessPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.addCategory("android.intent.category.DEFAULT")
                intent.data = Uri.parse("package:$packageName")
                startActivityForResult(intent, REQUEST_ALL_FILES_ACCESS_PERMISSION)
            } catch (e: ActivityNotFoundException) {
                Toast.makeText(
                    this,
                    "Unable to request permission, please grant manually",
                    Toast.LENGTH_SHORT
                ).show()
            }

        } else {
            // 在Android 10及以下版本，请求READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
                REQUEST_PERMISSION_CODE
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            // 检查权限是否已经授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    // 权限已授予，刷新页面或执行相关操作
                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    // 权限未授予，提示用户
                    Toast.makeText(
                        this,
                        "Permission not granted, please grant manually",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(
                    this,
                    "Unauthorized permission, the page is about to close",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }
        } else if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以继续操作
            } else {
                // 权限未授予，直接关闭页面
                Toast.makeText(
                    this,
                    "Unauthorized permission, the page is about to close",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}