package com.wall.exquisite.wallpaper;

import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.ad.tradpluslibrary.TPAdManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.wall.exquisite.wallpaper.databinding.ActivityFullImageBinding;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

// 壁纸设置类型常量
interface WallpaperType {
    int TYPE_HOME = 1;    // 桌面
    int TYPE_LOCK = 2;     // 锁屏
    int TYPE_BOTH = 3;     // 桌面+锁屏
}

public class FullImageActivity extends AppCompatActivity implements WallpaperType {
    // 传递参数Key
    public static final String EXTRA_IMAGE_URL = "extra_image_url";
    public static final String EXTRA_IMAGE_ID = "extra_image_id";
    public static final String EXTRA_IMAGE_DESC = "extra_image_desc";

    private ActivityFullImageBinding binding;
    private String imageUrl;
    private String imageId;
    private String imageDesc;
    private File tempFile;
    private WallpaperManager wallpaperManager;
    private CollectionManager favoriteManager;
    private int screenWidth;  // 屏幕宽度
    private int screenHeight; // 屏幕高度（包含状态栏/导航栏，适配全面屏）
    private RequestManager glideRequestManager; // Glide生命周期管理
    private boolean isActivityDestroyed = false; // 标记Activity是否已销毁
    private Thread downloadThread; // 下载线程引用（用于销毁时中断）
    private Thread setWallpaperThread; // 设置壁纸线程引用（用于销毁时中断）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityFullImageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 1. 初始化Glide RequestManager，绑定Activity生命周期（避免内存泄漏）
        glideRequestManager = Glide.with(this);

        // 沉浸式全屏
        initFullScreen();
        // 获取屏幕尺寸（用于壁纸精准缩放）
        getScreenSize();
        // 初始化管理器
        wallpaperManager = WallpaperManager.getInstance(this);
        favoriteManager = new CollectionManager(this);

        // 获取传递的参数
        getIntentData();
        // 加载图片（使用统一的Glide管理器）
        loadImage(imageUrl);
        // 初始化点击事件
        initClick();
        // 初始化点赞状态
        initFavoriteState();
    }

    /**
     * 沉浸式全屏配置（隐藏状态栏/导航栏，支持滑动显示）
     */
    private void initFullScreen() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
        if (insetsController != null) {
            insetsController.hide(WindowInsetsCompat.Type.statusBars() | WindowInsetsCompat.Type.navigationBars());
            insetsController.setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
        }
    }

    /**
     * 获取屏幕真实尺寸（包含状态栏/导航栏，避免壁纸缩放后被裁剪）
     */
    private void getScreenSize() {
        DisplayMetrics metrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 直接获取真实屏幕尺寸
            getDisplay().getRealMetrics(metrics);
        } else {
            // Android 11以下 通过WindowManager获取
            getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        }
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        Log.d("ScreenSize", "宽：" + screenWidth + "，高：" + screenHeight);
    }

    /**
     * 接收从上个页面传递的参数（图片URL、ID、描述）
     */
    private void getIntentData() {
        Intent intent = getIntent();
        imageUrl = intent.getStringExtra(EXTRA_IMAGE_URL);
        imageId = intent.getStringExtra(EXTRA_IMAGE_ID);
        imageDesc = intent.getStringExtra(EXTRA_IMAGE_DESC);

        // 设置图片描述（无描述时显示应用名称）
        if (imageDesc != null && !imageDesc.isEmpty()) {
            binding.tvContent.setText(imageDesc);
        } else {
            binding.tvContent.setText(getString(R.string.app_name));
        }

        // 初始化临时文件（应用私有目录，无需存储权限）
        if (imageId == null) {
            imageId = "wallpaper_" + System.currentTimeMillis();
        }
        tempFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), imageId + ".jpg");
    }

    /**
     * 加载图片（优先加载本地临时文件，无则从网络加载）
     */
    private void loadImage(String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            Toast.makeText(this, "Image URL is empty, cannot load", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // Glide加载配置（优化性能，设置占位图/错误图）
        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565) // 节省内存
                .placeholder(R.drawable.loading) // 加载中占位图
                .error(R.drawable.load_ing); // 加载失败图

        // 检查临时文件是否存在（存在则加载本地文件）
        if (tempFile.exists()) {
            glideRequestManager
                    .load(tempFile)
                    .apply(options)
                    .transition(DrawableTransitionOptions.withCrossFade(500)) // 淡入动画
                    .into(binding.imageviewPreview);
        } else {
            // 从网络加载图片
            glideRequestManager
                    .asDrawable()
                    .load(imageUrl)
                    .apply(options)
                    .skipMemoryCache(true) // 跳过内存缓存（避免重复图片占用内存）
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            Log.e("FullImage", "Failed to load image：" + e.getMessage());
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .centerCrop() // 居中裁剪（适配ImageView）
                    .into(binding.imageviewPreview);
        }
    }

    /**
     * 初始化点赞状态（从FavoriteManager读取是否已收藏）
     */
    private void initFavoriteState() {
        if (imageId == null) return;
        boolean isFavorited = favoriteManager.isFavorite(imageId);
        binding.imageFavorite.setSelected(isFavorited);
        binding.imageFavorite.setImageResource(isFavorited ? R.drawable.like_red : R.drawable.like);
    }

    /**
     * 初始化所有点击事件（返回、下载、设置壁纸、点赞）
     */
    private void initClick() {
        // 返回按钮（关闭当前页面）
        binding.imageviewBack.setOnClickListener(v -> TPAdManager.INSTANCE.showTPAD(this,()-> {
            finish();
        return null;
        }));

        // 下载按钮（保存图片到相册，无需权限）
        binding.layoutDownload.setOnClickListener(v -> TPAdManager.INSTANCE.showTPAD(this,()-> {
            startDownload();
            return null;
        }));

        // 设置壁纸按钮（弹出选择弹窗）
        binding.buttonSet1.setOnClickListener(v -> showWallpaperTypeDialog());

        // 点赞按钮（收藏/取消收藏）
        binding.imageFavorite.setOnClickListener(v -> TPAdManager.INSTANCE.showTPAD(this,()-> {
            toggleFavorite();
            return null;
        }));

    }

    /**
     * 切换收藏状态（添加/移除收藏）
     */
    private void toggleFavorite() {
        if (imageId == null) {
            Toast.makeText(this, "Cannot add to favorites", Toast.LENGTH_SHORT).show();
            return;
        }

        // 构建收藏实体类
        Wallpaper_Item item = new Wallpaper_Item();
        item.setId(imageId);
        item.setAlt_description(imageDesc);

        Urls urls = new Urls();
        urls.setRegular(imageUrl);
        urls.setSmall(imageUrl);
        urls.setFull(imageUrl);
        item.setUrls(urls);

        // 检查当前是否已收藏
        boolean isFavorited = favoriteManager.isFavorite(imageId);
        if (isFavorited) {
            // 取消收藏
            favoriteManager.removeFavorite(imageId);
            binding.imageFavorite.setSelected(false);
            binding.imageFavorite.setImageResource(R.drawable.like);
            Toast.makeText(this, "Cancel collection", Toast.LENGTH_SHORT).show();
            Log.d("FullImageActivity", "Cancel collection: " + imageId);
        } else {
            // 添加收藏
            favoriteManager.addFavorite(item);
            binding.imageFavorite.setSelected(true);
            binding.imageFavorite.setImageResource(R.drawable.like_red);
            Toast.makeText(this, "Favorited", Toast.LENGTH_SHORT).show();
            Log.d("FullImageActivity", "Favorited: " + imageId);
        }
    }

    /**
     * 下载图片到相册（通过MediaStore，无需存储权限）
     */
    private void startDownload() {
        // 显示加载进度条，隐藏下载按钮
        showLoading(binding.pbDownload, binding.imageDownload, true);

        // 保存线程引用，便于销毁时中断
        downloadThread = new Thread(() -> {
            // 检查Activity是否已销毁，避免无效执行
            if (isActivityDestroyed) {
                runOnUiThread(() -> showLoading(binding.pbDownload, binding.imageDownload, false));
                return;
            }

            Bitmap bitmap = null;
            try {
                // 检查线程是否被中断（Activity销毁时触发）
                if (Thread.currentThread().isInterrupted()) throw new InterruptedException();

                // 1. 从网络下载图片
                URL url = new URL(imageUrl);
                URLConnection conn = url.openConnection();
                InputStream is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();

                // 检查图片是否解码成功
                if (bitmap == null) {
                    throw new IOException("Failed to decode image");
                }

                // 再次检查Activity状态和线程中断状态
                if (isActivityDestroyed || Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }

                // 2. 通过MediaStore写入相册（Android 10+ 适配）
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DISPLAY_NAME, imageId + ".jpg"); // 文件名
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // 文件类型
                values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/Wallpaper"); // 相册路径（DCIM/Wallpaper）
                values.put(MediaStore.Images.Media.WIDTH, bitmap.getWidth());
                values.put(MediaStore.Images.Media.HEIGHT, bitmap.getHeight());

                // Android 10+ 标记为待处理（避免相册立即扫描）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    values.put(MediaStore.Images.Media.IS_PENDING, 1);
                }

                // 插入到媒体库，获取图片Uri
                Uri imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                if (imageUri == null) {
                    throw new IOException("Failed to import to media library");
                }

                // 写入图片数据到Uri
                try (OutputStream os = getContentResolver().openOutputStream(imageUri)) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                }

                // Android 10+ 标记为完成（允许相册扫描）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    values.clear();
                    values.put(MediaStore.Images.Media.IS_PENDING, 0);
                    getContentResolver().update(imageUri, values, null, null);
                }

                // 保存临时文件（用于后续设置壁纸，无需重复下载）
                saveTempFile(bitmap);

                // 主线程更新UI（下载成功）
                if (!isActivityDestroyed && !Thread.currentThread().isInterrupted()) {
                    runOnUiThread(() -> {
                        showLoading(binding.pbDownload, binding.imageDownload, false);
                        Toast.makeText(this, "Download successful. Saved to your photo library", Toast.LENGTH_LONG).show();
                    });
                }

            } catch (InterruptedException e) {
                // 线程被中断（Activity销毁），直接退出，不提示错误
                Log.d("FullImage", "Download thread interrupted");
                runOnUiThread(() -> showLoading(binding.pbDownload, binding.imageDownload, false));
            } catch (Exception e) {
                // 其他异常（下载失败）
                e.printStackTrace();
                if (!isActivityDestroyed) {
                    runOnUiThread(() -> {
                        showLoading(binding.pbDownload, binding.imageDownload, false);
                        Toast.makeText(FullImageActivity.this, "Download failed：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            } finally {
                // 回收Bitmap，避免内存泄漏
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        });
        downloadThread.start();
    }

    /**
     * 保存临时文件到应用私有目录（用于设置壁纸，无需权限）
     */
    private void saveTempFile(Bitmap bitmap) throws IOException {
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs(); // 创建父目录（不存在则创建）
        }
        try (OutputStream os = new java.io.FileOutputStream(tempFile)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); // 100表示不压缩
        }
    }

    /**
     * 显示壁纸设置类型弹窗（桌面/锁屏/两者）
     */
    private void showWallpaperTypeDialog() {
        // 加载自定义弹窗布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_wallpapertype, null);

        // 获取弹窗中的三个选项
        LinearLayout layoutHome = dialogView.findViewById(R.id.layout_ic_home);
        LinearLayout layoutLock = dialogView.findViewById(R.id.layout_ic_lock);
        LinearLayout layoutBoth = dialogView.findViewById(R.id.layout_ic_both);

        // 创建弹窗（设置透明背景，避免遮挡圆角）
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .create();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        // 绑定选项点击事件
        layoutHome.setOnClickListener(v -> {
            setWallpaper(TYPE_HOME);
            dialog.dismiss();
        });
        layoutLock.setOnClickListener(v -> {
            setWallpaper(TYPE_LOCK);
            dialog.dismiss();
        });
        layoutBoth.setOnClickListener(v -> {
            setWallpaper(TYPE_BOTH);
            dialog.dismiss();
        });

        // 显示弹窗并设置宽度为全屏
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(params);
        }
    }

    /**
     * 设置壁纸（根据选择的类型设置桌面/锁屏/两者）
     */
    private void setWallpaper(int type) {
        // 显示加载进度条，隐藏设置按钮
        showLoading(binding.pbSet1, binding.buttonSet1, true);

        final int finalType = type; // Lambda表达式中使用的变量需为final

        // 保存线程引用，便于销毁时中断
        setWallpaperThread = new Thread(() -> {
            // 检查Activity是否已销毁
            if (isActivityDestroyed) {
                runOnUiThread(() -> showLoading(binding.pbSet1, binding.buttonSet1, false));
                return;
            }

            Bitmap originBitmap = null;
            Bitmap scaledBitmap = null;
            try {
                // 检查线程是否被中断
                if (Thread.currentThread().isInterrupted()) throw new InterruptedException();

                if (!tempFile.exists()) {
                    // 临时文件不存在，先从网络下载
                    URL url = new URL(imageUrl);
                    URLConnection conn = url.openConnection();
                    InputStream is = conn.getInputStream();
                    originBitmap = BitmapFactory.decodeStream(is);
                    is.close();

                    if (originBitmap == null) {
                        throw new IOException("Failed to decode image");
                    }

                    // 检查Activity状态和线程中断状态
                    if (isActivityDestroyed || Thread.currentThread().isInterrupted()) {
                        throw new InterruptedException();
                    }

                    // 缩放图片到屏幕尺寸（避免系统自动裁剪）
                    scaledBitmap = scaleBitmapToScreen(originBitmap);
                    // 保存缩放后的临时文件
                    saveTempFile(scaledBitmap);
                } else {
                    // 临时文件存在，直接读取并缩放
                    originBitmap = BitmapFactory.decodeFile(tempFile.getAbsolutePath());
                    if (originBitmap == null) {
                        throw new IOException("Failed to read temp file");
                    }

                    // 检查Activity状态和线程中断状态
                    if (isActivityDestroyed || Thread.currentThread().isInterrupted()) {
                        throw new InterruptedException();
                    }

                    // 缩放图片到屏幕尺寸
                    scaledBitmap = scaleBitmapToScreen(originBitmap);
                    // 覆盖保存缩放后的图片
                    saveTempFile(scaledBitmap);
                }

                // 检查状态后，执行设置壁纸操作
                if (!isActivityDestroyed && !Thread.currentThread().isInterrupted()) {
                    setWallpaperFromFile(tempFile, finalType);
                }

            } catch (InterruptedException e) {
                // 线程被中断，直接退出
                Log.d("FullImage", "Set wallpaper thread interrupted");
                runOnUiThread(() -> showLoading(binding.pbSet1, binding.buttonSet1, false));
            } catch (Exception e) {
                // 其他异常（设置失败）
                e.printStackTrace();
                if (!isActivityDestroyed) {
                    runOnUiThread(() -> {
                        showLoading(binding.pbSet1, binding.buttonSet1, false);
                        Toast.makeText(FullImageActivity.this, "Setup failed", Toast.LENGTH_SHORT).show();
                    });
                }
            } finally {
                // 回收所有Bitmap，避免内存泄漏
                if (originBitmap != null && !originBitmap.isRecycled()) {
                    originBitmap.recycle();
                }
                if (scaledBitmap != null && !scaledBitmap.isRecycled()) {
                    scaledBitmap.recycle();
                }
            }
        });
        setWallpaperThread.start();
    }

    /**
     * 图片缩放适配屏幕（保持比例，避免裁剪，适配全面屏）
     */
    private Bitmap scaleBitmapToScreen(Bitmap originBitmap) {
        if (originBitmap == null) return null;

        // 原始图片尺寸
        int originWidth = originBitmap.getWidth();
        int originHeight = originBitmap.getHeight();
        Log.d("ScaleBitmap", "原始宽：" + originWidth + "，原始高：" + originHeight);

        // 计算缩放比例（取最大比例，确保图片覆盖屏幕，无黑边）
        float scaleX = (float) screenWidth / originWidth;
        float scaleY = (float) screenHeight / originHeight;
        float scale = Math.max(scaleX, scaleY);

        // 缩放后的尺寸
        int scaledWidth = (int) (originWidth * scale);
        int scaledHeight = (int) (originHeight * scale);
        Log.d("ScaleBitmap", "缩放后宽：" + scaledWidth + "，缩放后高：" + scaledHeight);

        // 执行缩放（true表示使用双线性过滤，保持图片清晰）
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(originBitmap, scaledWidth, scaledHeight, true);

        // 裁剪超出屏幕的部分（居中裁剪，确保尺寸与屏幕一致）
        if (scaledWidth > screenWidth || scaledHeight > screenHeight) {
            int cropX = (scaledWidth - screenWidth) / 2;
            int cropY = (scaledHeight - screenHeight) / 2;
            scaledBitmap = Bitmap.createBitmap(
                    scaledBitmap,
                    cropX, // 裁剪起始X坐标（居中）
                    cropY, // 裁剪起始Y坐标（居中）
                    screenWidth, // 目标宽度（屏幕宽度）
                    screenHeight // 目标高度（屏幕高度）
            );
            Log.d("ScaleBitmap", "裁剪后宽：" + scaledBitmap.getWidth() + "，裁剪后高：" + scaledBitmap.getHeight());
        }

        return scaledBitmap;
    }

    /**
     * 从临时文件设置壁纸（适配Android 7.0+ 单独设置桌面/锁屏）
     */
    private void setWallpaperFromFile(File file, int type) {
        try {
            InputStream is = new java.io.FileInputStream(file);
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);

            switch (type) {
                case TYPE_HOME:
                    // 设置桌面壁纸（Android 7.0+ 适配）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        wallpaperManager.setStream(is, null, true, WallpaperManager.FLAG_SYSTEM);
                    } else {
                        wallpaperManager.setStream(is);
                    }
                    break;
                case TYPE_LOCK:
                    // 设置锁屏壁纸（Android 7.0+ 才支持）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        wallpaperManager.setStream(is, null, true, WallpaperManager.FLAG_LOCK);
                    } else {
                        // Android 7.0以下提示不支持
                        runOnUiThread(() -> Toast.makeText(this, "Android 7.0+ supports lock screen wallpaper setting", Toast.LENGTH_SHORT).show());
                        wallpaperManager.setStream(is);
                    }
                    break;
                case TYPE_BOTH:
                    // 设置桌面+锁屏壁纸
                    wallpaperManager.setStream(is);
                    break;
            }
            is.close(); // 关闭输入流，释放资源

            // 设置成功，更新UI
            runOnUiThread(() -> {
                showLoading(binding.pbSet1, binding.buttonSet1, false);
                Toast.makeText(this, "Wallpaper Updated", Toast.LENGTH_SHORT).show();
            });

        } catch (Exception e) {
            e.printStackTrace();
            // 设置失败，提示用户
            runOnUiThread(() -> {
                showLoading(binding.pbSet1, binding.buttonSet1, false);
                Toast.makeText(this, "Wallpaper setup failed：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            });
        }
    }

    /**
     * 显示/隐藏加载进度条（统一控制加载状态）
     */
    private void showLoading(ProgressBar pb, View view, boolean show) {
        pb.setVisibility(show ? View.VISIBLE : View.GONE);
        view.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    /**
     * 窗口焦点变化时，重新设置全屏（避免导航栏/状态栏重新显示）
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            initFullScreen();
        }
    }

    /**
     * Activity销毁时，释放所有资源（避免内存泄漏和线程孤儿运行）
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 标记Activity已销毁
        isActivityDestroyed = true;

        // 中断所有异步线程（避免线程持有Activity引用）
        if (downloadThread != null && downloadThread.isAlive()) {
            downloadThread.interrupt();
        }
        if (setWallpaperThread != null && setWallpaperThread.isAlive()) {
            setWallpaperThread.interrupt();
        }

        // 取消Glide所有未完成的请求（避免Glide持有ImageView引用）
        glideRequestManager.clear(binding.imageviewPreview);

        // 回收ImageView的Drawable资源
        Drawable drawable = binding.imageviewPreview.getDrawable();
        if (drawable != null) {
            drawable.setCallback(null); // 解除Drawable与ImageView的关联
        }
        binding.imageviewPreview.setImageDrawable(null); // 清空ImageView

        // 释放ViewBinding引用（避免内存泄漏）
        binding = null;
    }
}