package com.gallery.free.wallpaper

import android.R
import android.app.WallpaperManager
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import android.media.MediaScannerConnection
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.viewpager2.widget.ViewPager2
import com.ad.ironsourcelibrary.ActionListener
import com.ad.ironsourcelibrary.ISAdManager

import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.gallery.free.wallpaper.database.FavorWpManager
import com.gallery.free.wallpaper.databinding.ActivityDetailwpBinding

import java.io.File
import java.io.FileOutputStream
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference

class DetailwpActivity : BaseActivity(), Dialog_SetWp.OnWallpaperTypeSelectedListener {

    private lateinit var binding: ActivityDetailwpBinding
    private var isLiked = false
    private var wallpaperName: String? = null
    private lateinit var wallpaperManager: WallpaperManager
    private var setWallpaperDialog: Dialog_SetWp? = null
    private var isSettingWallpaper = false
    private var isDownloading = false
    private var currentPosition = 0
    private var wallpaperItemList: ArrayList<WpItem> = ArrayList()
    private var wallpaperList: ArrayList<String> = ArrayList()
    private lateinit var viewPager: ViewPager2
    private lateinit var pagerAdapter: WpPagerAdapter
    private var screenWidth = 0
    private var screenHeight = 0

    companion object {
        private const val TAG = "DetailWallpaper"
        private const val DOWNLOAD_STATE_IDLE = 0
        private const val DOWNLOAD_STATE_LOADING = 1
        private const val DOWNLOAD_STATE_SUCCESS = 2
        private const val DOWNLOAD_STATE_FAILED = 3
        private const val SET_WALLPAPER_STATE_IDLE = 0
        private const val SET_WALLPAPER_STATE_LOADING = 1
        private const val SET_WALLPAPER_STATE_SUCCESS = 2
        private const val SET_WALLPAPER_STATE_FAILED = 3
        private const val PERMISSION_REQUEST_CODE = 1001
        const val ACTION_FAVORITE_CHANGED = "com.gallery.free.wallpaper.FAVORITE_CHANGED"
    }

    private var downloadState = DOWNLOAD_STATE_IDLE
    private var setWallpaperState = SET_WALLPAPER_STATE_IDLE
    private val handler = Handler(Looper.getMainLooper())

    // 数据库管理
    private lateinit var favoriteManager: FavorWpManager

    // 修改：使用SoftReference避免内存泄漏
    private var currentWallpaperBitmap: SoftReference<Bitmap>? = null
    // 添加：缓存加载任务，避免重复加载
    private val bitmapLoadTasks = mutableMapOf<Int, CustomTarget<Bitmap>>()

    // 添加：加载失败相关
    private lateinit var failedView: View
    private val failedImagePositions = mutableSetOf<Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDetailwpBinding.inflate(layoutInflater)
        Utils_com.initFull(this, true)
        setContentView(binding.root)
        ISAdManager.loadAllAd()
        ISAdManager.showIsAd(this@DetailwpActivity,object : ActionListener{
            override fun onAction() {

            }

        })


        Log.d(TAG, "=== onCreate ===")

        // 获取屏幕尺寸
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        screenWidth = displayMetrics.widthPixels
        screenHeight = displayMetrics.heightPixels
        Log.d(TAG, "Screen size: $screenWidth x $screenHeight")

        // 初始化数据库管理
        favoriteManager = FavorWpManager.Companion.getInstance(this)

        wallpaperManager = WallpaperManager.getInstance(this)
        wallpaperName = intent.getStringExtra("wallpaper_name")

        // 获取壁纸项列表和当前位置
        wallpaperItemList = intent.getParcelableArrayListExtra<WpItem>("wallpaper_item_list") ?: ArrayList()

        // 为了兼容现有代码，创建只包含fullUrl的列表
        wallpaperList.clear()
        wallpaperItemList.forEach { item ->
            wallpaperList.add(item.fullUrl)
        }

        currentPosition = intent.getIntExtra("current_position", 0)

        Log.d(TAG, "wallpaperItemList size = ${wallpaperItemList.size}")
        Log.d(TAG, "wallpaperList size = ${wallpaperList.size}")
        Log.d(TAG, "currentPosition = $currentPosition")

        hideSystemUI()
        setupViewPager()
        setupViews()
        loadFavoriteStatus()
        updateNavigationButtons()

        // 预加载当前页面的Bitmap
        preloadCurrentBitmap()
    }

    private fun preloadCurrentBitmap() {
        val currentUrl = getCurrentWallpaperUrl()
        if (currentUrl.isEmpty()) return

        // 取消之前的加载任务
        bitmapLoadTasks[currentPosition]?.let {
            Glide.with(this).clear(it)
        }

        val target = object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                // 使用SoftReference缓存
                currentWallpaperBitmap = SoftReference(resource)
                // 从任务映射中移除
                bitmapLoadTasks.remove(currentPosition)
                // 如果当前页面是失败状态，移除失败标记
                failedImagePositions.remove(currentPosition)
            }

            override fun onLoadCleared(placeholder: Drawable?) {
                // 清理时也从任务映射中移除
                bitmapLoadTasks.remove(currentPosition)
            }

            override fun onLoadFailed(errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                bitmapLoadTasks.remove(currentPosition)
                // 记录加载失败
                failedImagePositions.add(currentPosition)
                // 如果当前正在查看这个位置，显示失败布局
                if (currentPosition == viewPager.currentItem) {
                    showFailedView()
                }
            }
        }

        bitmapLoadTasks[currentPosition] = target

        Glide.with(this)
            .asBitmap()
            .load(currentUrl)
            .into(target)
    }

    private fun hideSystemUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.let { controller ->
                controller.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
                controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )
        }
    }

    private fun setupViewPager() {
        viewPager = binding.wallpaperViewPager

        viewPager.offscreenPageLimit = 1

        pagerAdapter = WpPagerAdapter(wallpaperItemList, object : WpPagerAdapter.OnImageLoadListener {
            override fun onImageLoadSuccess(position: Int) {
                // 图片加载成功，从失败集合中移除
                failedImagePositions.remove(position)
                // 如果当前正在查看这个位置，隐藏失败布局
                if (position == currentPosition) {
                    hideFailedView()
                }
            }

            override fun onImageLoadFailed(position: Int, error: Throwable) {
                // 图片加载失败，记录失败位置
                failedImagePositions.add(position)
                // 如果当前正在查看这个位置，显示失败布局
                if (position == currentPosition) {
                    showFailedView()
                }
                Log.e(TAG, "Image load failed at position $position: ${error.message}")
            }
        })

        viewPager.adapter = pagerAdapter
        viewPager.setCurrentItem(currentPosition, false)

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                Log.d(TAG, "onPageSelected: position = $position")

                if (position != currentPosition) {
                    currentPosition = position
                    currentWallpaperBitmap = null

                    // 检查当前页面是否加载失败
                    if (failedImagePositions.contains(position)) {
                        showFailedView()
                    } else {
                        hideFailedView()
                    }

                    preloadCurrentBitmap()
                    loadFavoriteStatus()
                    updateNavigationButtons()
                    resetButtonStates()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                // 当开始拖动时，可以预加载相邻页面
                if (state == ViewPager2.SCROLL_STATE_DRAGGING) {
                    preloadAdjacentBitmaps()
                }
            }
        })
    }

    private fun preloadAdjacentBitmaps() {
        // 预加载前后页面的Bitmap
        val positionsToPreload = listOf(
            currentPosition - 1,
            currentPosition + 1
        ).filter { it in 0 until wallpaperList.size }

        positionsToPreload.forEach { position ->
            if (!bitmapLoadTasks.containsKey(position)) {
                val url = wallpaperList[position]
                val target = object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        bitmapLoadTasks.remove(position)
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                        bitmapLoadTasks.remove(position)
                    }

                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        super.onLoadFailed(errorDrawable)
                        bitmapLoadTasks.remove(position)
                        // 记录加载失败
                        failedImagePositions.add(position)
                    }
                }

                bitmapLoadTasks[position] = target

                Glide.with(this)
                    .asBitmap()
                    .load(url)
                    .into(target)
            }
        }
    }

    private fun setupViews() {
        Log.d(TAG, "setupViews")

        binding.imageviewBack.setOnClickListener {
            Log.d(TAG, "Back button clicked")
            onBackPressedDispatcher.onBackPressed()
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        }
        binding.buttonLike.setOnClickListener {
            Log.d(TAG, "Like button clicked")
            toggleLike()
        }
        binding.buttonSetWallpaper.setOnClickListener {
            Log.d(TAG, "Set wallpaper button clicked")
            if (setWallpaperState != SET_WALLPAPER_STATE_LOADING) {
                showSetWallpaperDialog()
            }
        }
        binding.buttonSave.setOnClickListener {

            ISAdManager.showIsAd(this@DetailwpActivity,object : ActionListener{
                override fun onAction() {
                    Log.d(TAG, "Save button clicked")
                    if (downloadState != DOWNLOAD_STATE_LOADING) {
                        downloadWallpaper()
                    }

                }

            })
        }

        binding.buttonPrev.setOnClickListener {
            Log.d(TAG, "PREV button clicked - currentPosition: $currentPosition")
            if (currentPosition > 0) {
                val newPosition = currentPosition - 1
                viewPager.setCurrentItem(newPosition, true)
            } else {
                Toast.makeText(this, "already the first one", Toast.LENGTH_SHORT).show()
            }
        }

        binding.buttonNext.setOnClickListener {
            Log.d(TAG, "NEXT button clicked - currentPosition: $currentPosition")
            if (currentPosition < wallpaperList.size - 1) {
                val newPosition = currentPosition + 1
                viewPager.setCurrentItem(newPosition, true)
            } else {
                Toast.makeText(this, "already the last one", Toast.LENGTH_SHORT).show()
            }
        }

        updateDownloadButtonState()
        updateSetWallpaperButtonState()
    }

    private fun showFailedView() {
        // 禁用操作按钮（收藏、设置壁纸、下载）
        binding.buttonLike.isEnabled = false
        binding.buttonSetWallpaper.isEnabled = false
        binding.buttonSave.isEnabled = false
    }

    private fun hideFailedView() {
        // 启用操作按钮
        binding.buttonLike.isEnabled = true
        binding.buttonSetWallpaper.isEnabled = true
        binding.buttonSave.isEnabled = true
    }

    // 重试加载当前图片
    private fun retryLoadCurrentImage() {
        val currentUrl = getCurrentWallpaperUrl()
        if (currentUrl.isEmpty()) return

        failedImagePositions.remove(currentPosition)
        pagerAdapter.retryLoadImage(currentPosition)
        preloadCurrentBitmap()
    }

    // 重置按钮状态
    private fun resetButtonStates() {
        downloadState = DOWNLOAD_STATE_IDLE
        setWallpaperState = SET_WALLPAPER_STATE_IDLE
        updateDownloadButtonState()
        updateSetWallpaperButtonState()
    }

    // 获取当前壁纸的URL
    private fun getCurrentWallpaperUrl(): String {
        return if (wallpaperList.isNotEmpty() && currentPosition in wallpaperList.indices) {
            wallpaperList[currentPosition]
        } else {
            ""
        }
    }

    private fun getCurrentWallpaperItem(): WpItem? {
        return if (wallpaperItemList.isNotEmpty() && currentPosition in wallpaperItemList.indices) {
            wallpaperItemList[currentPosition]
        } else {
            null
        }
    }

    // 更新导航按钮状态
    private fun updateNavigationButtons() {
        Log.d(TAG, "updateNavigationButtons - listSize: ${wallpaperList.size}, currentPos: $currentPosition")

        if (wallpaperList.isEmpty()) {
            Log.d(TAG, "No wallpapers - showing outline and disabling")
            binding.buttonPrev.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_left_disabled)
            binding.buttonNext.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_right_disabled)
            binding.buttonPrev.isEnabled = false
            binding.buttonNext.isEnabled = false
            binding.buttonPrev.alpha = 0.5f
            binding.buttonNext.alpha = 0.5f
        } else {
            val canGoPrevious = currentPosition > 0
            val canGoNext = currentPosition < wallpaperList.size - 1

            Log.d(TAG, "canGoPrevious: $canGoPrevious, canGoNext: $canGoNext")

            // 即使当前图片加载失败，导航按钮依然可用
            binding.buttonPrev.isEnabled = canGoPrevious
            binding.buttonNext.isEnabled = canGoNext
            binding.buttonPrev.alpha = if (canGoPrevious) 1.0f else 0.5f
            binding.buttonNext.alpha = if (canGoNext) 1.0f else 0.5f

            if (canGoPrevious) {
                binding.buttonPrev.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_left)
            } else {
                binding.buttonPrev.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_left_disabled)
            }

            if (canGoNext) {
                binding.buttonNext.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_right)
            } else {
                binding.buttonNext.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_right_disabled)
            }
        }
    }

    private fun loadFavoriteStatus() {
        val currentUrl = getCurrentWallpaperUrl()
        if (currentUrl.isEmpty()) return
        isLiked = favoriteManager.isFavorite(currentUrl)
        updateLikeButton()
    }

    private fun toggleLike() {
        val currentUrl = getCurrentWallpaperUrl()
        if (currentUrl.isEmpty()) return

        val wallpaperDescription = intent.getStringExtra("wallpaper_description") ?: ""

        isLiked = !isLiked
        updateLikeButton()

        if (isLiked) {
            // 添加收藏时保存描述
            val added = favoriteManager.addOrUpdateFavorite(currentUrl, wallpaperDescription)
            if (added) {
                notifyFavoriteChanged()
            }
        } else {
            val removed = favoriteManager.removeFavorite(currentUrl)
            if (removed) {
                notifyFavoriteChanged()
            }
        }
    }

    private fun notifyFavoriteChanged() {
        val intent = Intent(ACTION_FAVORITE_CHANGED)
        sendBroadcast(intent)
    }

    private fun updateLikeButton() {
        val likeIcon = if (isLiked) {
            com.gallery.free.wallpaper.R.drawable.ic_like
        } else {
            com.gallery.free.wallpaper.R.drawable.ic_like_disabled
        }
        binding.buttonLike.setImageResource(likeIcon)
    }

    private fun updateDownloadButtonState() {
        when (downloadState) {
            DOWNLOAD_STATE_IDLE -> {
                binding.buttonSave.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_savewp)
                binding.buttonSave.isEnabled = true
            }
            DOWNLOAD_STATE_LOADING -> {
                binding.buttonSave.setImageResource(com.gallery.free.wallpaper.R.drawable.loading_animation)
                binding.buttonSave.isEnabled = false
            }
            DOWNLOAD_STATE_SUCCESS -> {
                binding.buttonSave.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_success)
                binding.buttonSave.isEnabled = false

                handler.postDelayed({
                    downloadState = DOWNLOAD_STATE_IDLE
                    updateDownloadButtonState()
                }, 1500)
            }
            DOWNLOAD_STATE_FAILED -> {
                binding.buttonSave.setImageResource(com.gallery.free.wallpaper.R.drawable.close_detailwp)
                binding.buttonSave.isEnabled = true
                Toast.makeText(this, "saving failed...", Toast.LENGTH_SHORT).show()

                handler.postDelayed({
                    downloadState = DOWNLOAD_STATE_IDLE
                    updateDownloadButtonState()
                }, 2000)
            }
        }
    }

    private fun updateSetWallpaperButtonState() {
        when (setWallpaperState) {
            SET_WALLPAPER_STATE_IDLE -> {
                binding.buttonSetWallpaper.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_setwp)
                binding.buttonSetWallpaper.isEnabled = true
            }
            SET_WALLPAPER_STATE_LOADING -> {
                binding.buttonSetWallpaper.setImageResource(com.gallery.free.wallpaper.R.drawable.loading_animation)
                binding.buttonSetWallpaper.isEnabled = false
            }
            SET_WALLPAPER_STATE_SUCCESS -> {
                binding.buttonSetWallpaper.setImageResource(com.gallery.free.wallpaper.R.drawable.ic_success)
                binding.buttonSetWallpaper.isEnabled = false

                handler.postDelayed({
                    setWallpaperState = SET_WALLPAPER_STATE_IDLE
                    updateSetWallpaperButtonState()
                }, 500)
            }
            SET_WALLPAPER_STATE_FAILED -> {
                binding.buttonSetWallpaper.setImageResource(com.gallery.free.wallpaper.R.drawable.close_detailwp)
                binding.buttonSetWallpaper.isEnabled = true
                Toast.makeText(this, "setting failed...", Toast.LENGTH_SHORT).show()

                handler.postDelayed({
                    setWallpaperState = SET_WALLPAPER_STATE_IDLE
                    updateSetWallpaperButtonState()
                }, 500)
            }
        }
    }

    private fun showSetWallpaperDialog() {
        if (setWallpaperDialog == null) {
            setWallpaperDialog = Dialog_SetWp()
            setWallpaperDialog?.setListener(this)
        }
        if (setWallpaperDialog?.isAdded != true) {
            setWallpaperDialog?.show(supportFragmentManager, "SetWallpaperDialog")
        }
    }

    override fun onWallpaperTypeSelected(type: Int) {
        ISAdManager.showIsAd(this@DetailwpActivity,object : ActionListener{
            override fun onAction() {
                setWallpaper(type)
            }
        })

    }

    private fun setWallpaper(type: Int) {
        if (isSettingWallpaper) return

        // 如果当前图片加载失败，不能设置壁纸
        if (failedImagePositions.contains(currentPosition)) {
            Toast.makeText(this, "cannot set wallpaper", Toast.LENGTH_SHORT).show()
            return
        }

        isSettingWallpaper = true
        setWallpaperState = SET_WALLPAPER_STATE_LOADING
        updateSetWallpaperButtonState()

        // 首先尝试从缓存获取Bitmap
        val cachedBitmap = currentWallpaperBitmap?.get()
        if (cachedBitmap != null) {
            SetWallpaperTask(this@DetailwpActivity, type, cachedBitmap).execute()
            return
        }

        // 缓存中没有，从网络加载
        val currentUrl = getCurrentWallpaperUrl()
        if (currentUrl.isNotEmpty()) {
            Glide.with(this)
                .asBitmap()
                .load(currentUrl)
                .into(object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        // 缓存bitmap供后续使用
                        currentWallpaperBitmap = SoftReference(resource)
                        SetWallpaperTask(this@DetailwpActivity, type, resource).execute()
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                        // 清理资源
                    }

                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        setWallpaperState = SET_WALLPAPER_STATE_FAILED
                        updateSetWallpaperButtonState()
                        isSettingWallpaper = false
                        Toast.makeText(this@DetailwpActivity, "图片加载失败，无法设置壁纸", Toast.LENGTH_SHORT).show()
                    }
                })
        } else {
            setWallpaperState = SET_WALLPAPER_STATE_FAILED
            updateSetWallpaperButtonState()
            isSettingWallpaper = false
        }
    }

    private fun downloadWallpaper() {
        if (isDownloading) return

        // 如果当前图片加载失败，不能下载
        if (failedImagePositions.contains(currentPosition)) {
            Toast.makeText(this, "cannot download wallpaper", Toast.LENGTH_SHORT).show()
            return
        }

        if (!checkAndRequestStoragePermission()) {
            return
        }

        isDownloading = true
        downloadState = DOWNLOAD_STATE_LOADING
        updateDownloadButtonState()

        // 首先尝试从缓存获取Bitmap
        val cachedBitmap = currentWallpaperBitmap?.get()
        if (cachedBitmap != null) {
            DownloadWallpaperTask(this@DetailwpActivity, cachedBitmap).execute()
            return
        }

        val currentUrl = getCurrentWallpaperUrl()
        if (currentUrl.isNotEmpty()) {
            Glide.with(this)
                .asBitmap()
                .load(currentUrl)
                .into(object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        // 缓存bitmap
                        currentWallpaperBitmap = SoftReference(resource)
                        DownloadWallpaperTask(this@DetailwpActivity, resource).execute()
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                        // 清理资源
                    }

                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        downloadState = DOWNLOAD_STATE_FAILED
                        updateDownloadButtonState()
                        isDownloading = false
                        Toast.makeText(this@DetailwpActivity, "图片加载失败，无法下载", Toast.LENGTH_SHORT).show()
                    }
                })
        } else {
            downloadState = DOWNLOAD_STATE_FAILED
            updateDownloadButtonState()
            isDownloading = false
        }
    }

    private fun checkAndRequestStoragePermission(): Boolean {
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
                if (ContextCompat.checkSelfPermission(
                        this,
                        android.Manifest.permission.READ_MEDIA_IMAGES
                    ) == android.content.pm.PackageManager.PERMISSION_GRANTED
                ) {
                    true
                } else {
                    requestPermissions(
                        arrayOf(android.Manifest.permission.READ_MEDIA_IMAGES),
                        PERMISSION_REQUEST_CODE
                    )
                    false
                }
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                true
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                if (ContextCompat.checkSelfPermission(
                        this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) == android.content.pm.PackageManager.PERMISSION_GRANTED
                ) {
                    true
                } else {
                    requestPermissions(
                        arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        PERMISSION_REQUEST_CODE
                    )
                    false
                }
            }
            else -> {
                true
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    if (isDownloading.not()) {
                        downloadWallpaper()
                    }
                } else {
                    Toast.makeText(this, "permission needed", Toast.LENGTH_SHORT).show()
                    downloadState = DOWNLOAD_STATE_FAILED
                    updateDownloadButtonState()
                    isDownloading = false
                }
            }
        }
    }

    private class SetWallpaperTask(
        activity: DetailwpActivity,
        private val type: Int,
        private val bitmap: Bitmap
    ) : AsyncTask<Void, Void, Boolean>() {

        private val activityRef = WeakReference(activity)

        private fun createCenteredWallpaperBitmap(originalBitmap: Bitmap, screenWidth: Int, screenHeight: Int): Bitmap {
            val bitmapWidth = originalBitmap.width.toFloat()
            val bitmapHeight = originalBitmap.height.toFloat()

            val scaleX = screenWidth / bitmapWidth
            val scaleY = screenHeight / bitmapHeight
            val scale = maxOf(scaleX, scaleY)

            val matrix = Matrix()
            matrix.postScale(scale, scale)
            val scaledBitmap = Bitmap.createBitmap(
                originalBitmap,
                0, 0,
                originalBitmap.width, originalBitmap.height,
                matrix, true
            )

            val scaledWidth = scaledBitmap.width
            val scaledHeight = scaledBitmap.height

            val startX = (scaledWidth - screenWidth) / 2
            val startY = (scaledHeight - screenHeight) / 2

            val safeStartX = maxOf(0, startX)
            val safeStartY = maxOf(0, startY)
            val safeEndX = minOf(safeStartX + screenWidth, scaledWidth)
            val safeEndY = minOf(safeStartY + screenHeight, scaledHeight)
            val safeWidth = safeEndX - safeStartX
            val safeHeight = safeEndY - safeStartY

            return Bitmap.createBitmap(
                scaledBitmap,
                safeStartX, safeStartY,
                safeWidth, safeHeight
            )
        }

        override fun doInBackground(vararg params: Void?): Boolean {
            val activity = activityRef.get() ?: return false

            return try {
                val centeredBitmap = createCenteredWallpaperBitmap(bitmap, activity.screenWidth, activity.screenHeight)

                when (type) {
                    Dialog_SetWp.TYPE_HOME -> {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            activity.wallpaperManager.setBitmap(
                                centeredBitmap,
                                null,
                                true,
                                WallpaperManager.FLAG_SYSTEM
                            )
                        } else {
                            activity.wallpaperManager.setBitmap(centeredBitmap)
                        }
                    }
                    Dialog_SetWp.TYPE_LOCK -> {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            activity.wallpaperManager.setBitmap(
                                centeredBitmap,
                                null,
                                true,
                                WallpaperManager.FLAG_LOCK
                            )
                        } else {
                            activity.wallpaperManager.setBitmap(centeredBitmap)
                        }
                    }
                    Dialog_SetWp.TYPE_BOTH -> {
                        activity.wallpaperManager.setBitmap(centeredBitmap)
                    }
                }
                true
            } catch (e: Exception) {
                Log.e("SetWallpaperTask", "设置壁纸失败: ${e.message}", e)
                false
            }
        }

        override fun onPostExecute(success: Boolean) {
            val activity = activityRef.get() ?: return

            activity.isSettingWallpaper = false

            if (success) {
                activity.setWallpaperState = SET_WALLPAPER_STATE_SUCCESS
            } else {
                activity.setWallpaperState = SET_WALLPAPER_STATE_FAILED
                Toast.makeText(activity, "setting failed...", Toast.LENGTH_SHORT).show()
            }

            activity.updateSetWallpaperButtonState()
        }
    }

    private class DownloadWallpaperTask(
        activity: DetailwpActivity,
        private val bitmap: Bitmap
    ) : AsyncTask<Void, Void, Boolean>() {

        private val activityRef = WeakReference(activity)

        override fun doInBackground(vararg params: Void?): Boolean {
            val activity = activityRef.get() ?: return false

            return try {
                activity.saveBitmapToGallery(bitmap, activity.wallpaperName ?: "wallpaper")
            } catch (e: Exception) {
                e.printStackTrace()
                false
            }
        }

        override fun onPostExecute(success: Boolean) {
            val activity = activityRef.get() ?: return

            activity.isDownloading = false

            if (success) {
                activity.downloadState = DOWNLOAD_STATE_SUCCESS
            } else {
                activity.downloadState = DOWNLOAD_STATE_FAILED
            }

            activity.updateDownloadButtonState()
        }
    }

    private fun saveBitmapToGallery(bitmap: Bitmap, fileName: String): Boolean {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                saveBitmapWithMediaStore(bitmap, fileName)
            } else {
                saveBitmapLegacy(bitmap, fileName)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun saveBitmapWithMediaStore(bitmap: Bitmap, fileName: String): Boolean {
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/Wallpapers")
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }

        val contentResolver = this.contentResolver
        val collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        val imageUri = contentResolver.insert(collection, contentValues)

        return imageUri?.let { uri ->
            try {
                contentResolver.openOutputStream(uri)?.use { outputStream ->
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                }
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                contentResolver.update(uri, contentValues, null, null)
                true
            } catch (e: Exception) {
                e.printStackTrace()
                false
            }
        } ?: false
    }

    @Suppress("DEPRECATION")
    private fun saveBitmapLegacy(bitmap: Bitmap, fileName: String): Boolean {
        return try {
            val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            val wallpapersDir = File(imagesDir, "Wallpapers")
            if (!wallpapersDir.exists()) {
                wallpapersDir.mkdirs()
            }

            var validFileName = fileName
            if (validFileName.isNullOrEmpty() || validFileName == "null") {
                validFileName = "wallpaper_${System.currentTimeMillis()}"
            }

            validFileName = validFileName.replace(Regex("[^a-zA-Z0-9._-]"), "_")
            if (!validFileName.endsWith(".jpg")) {
                validFileName += ".jpg"
            }

            val imageFile = File(wallpapersDir, validFileName)
            val outputStream = FileOutputStream(imageFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            outputStream.flush()
            outputStream.close()

            MediaScannerConnection.scanFile(
                this,
                arrayOf(imageFile.absolutePath),
                null,
                null
            )
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }


    override fun onDestroy() {
        // 清理所有资源
        isSettingWallpaper = false
        isDownloading = false

        // 检查 Activity 状态
        if (!isFinishing && !isDestroyed) {
            // 使用安全的方式来清理 Glide
            bitmapLoadTasks.values.forEach { target ->
                try {
                    Glide.with(this).clear(target as com.bumptech.glide.request.target.Target<*>)
                } catch (e: IllegalArgumentException) {
                    // 如果已经销毁，使用 Application Context
                    Glide.with(applicationContext).clear(target as com.bumptech.glide.request.target.Target<*>)
                }
            }
        } else {
            // Activity 已经销毁，使用 Application Context
            bitmapLoadTasks.values.forEach { target ->
                Glide.with(applicationContext).clear(target as com.bumptech.glide.request.target.Target<*>)
            }
        }
        bitmapLoadTasks.clear()
        failedImagePositions.clear()

        // 清理Handler
        handler.removeCallbacksAndMessages(null)

        // 清理适配器缓存
        pagerAdapter?.clearAllCache()

        // 清理Bitmap缓存
        currentWallpaperBitmap?.clear()
        currentWallpaperBitmap = null

        super.onDestroy()
    }

    override fun onStop() {
        super.onStop()
        // 进入后台时暂停Glide
        Glide.with(this).pauseRequests()
    }

    override fun onStart() {
        super.onStart()
        // 回到前台时恢复Glide
        Glide.with(this).resumeRequests()
    }


    protected override fun shouldInterceptBackPress(): Boolean {
        return true
    }

    protected override fun onInterceptBackPressed() {
        ISAdManager.showIsAd(this@DetailwpActivity,object : ActionListener{
            override fun onAction() {

            }

        })
        if (backPressedCallback != null) {
            backPressedCallback?.isEnabled = false
        }
        onBackPressedDispatcher.onBackPressed()
    }

}