package cc.winboll.studio.powerbell.activities;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
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.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import cc.winboll.studio.powerbell.App;
import cc.winboll.studio.powerbell.R;
import cc.winboll.studio.powerbell.dialogs.BackgroundPicturePreviewDialog;
import cc.winboll.studio.powerbell.dialogs.YesNoAlertDialog;
import cc.winboll.studio.powerbell.models.BackgroundBean;
import cc.winboll.studio.powerbell.utils.BackgroundSourceUtils;
import cc.winboll.studio.powerbell.utils.BitmapCacheUtils;
import cc.winboll.studio.powerbell.utils.FileUtils;
import cc.winboll.studio.powerbell.utils.ImageCropUtils;
import cc.winboll.studio.powerbell.utils.UriUtils;
import cc.winboll.studio.powerbell.views.BackgroundView;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class BackgroundSettingsActivity extends WinBoLLActivity {

    // ====================== 常量定义 ======================
    public static final String TAG = "BackgroundSettingsActivity";
    private static final int SDK_VERSION_TIRAMISU = 33;

    public static final int REQUEST_SELECT_PICTURE = 0;
    public static final int REQUEST_TAKE_PHOTO = 1;
    public static final int REQUEST_CROP_IMAGE = 2;
	private static final int REQUEST_PIXELPICKER = 1001;

    // ====================== 成员变量 ======================
    private BackgroundSourceUtils mBgSourceUtils;
    private BitmapCacheUtils mBitmapCache;

    private Toolbar mToolbar;
    private BackgroundView mBackgroundView;
    private File mfTakePhoto;
    volatile boolean isCommitSettings = false;
    volatile boolean isPreviewBackgroundChanged = false;

    // ====================== 生命周期方法 ======================
    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public String getTag() {
        return TAG;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_background_settings);
        LogUtils.d(TAG, "【生命周期】onCreate 开始初始化");

        // 初始化视图与工具类
        mBackgroundView = findViewById(R.id.background_view);
        mBgSourceUtils = BackgroundSourceUtils.getInstance(this);
        mBgSourceUtils.loadSettings();
        mBitmapCache = BitmapCacheUtils.getInstance();

        // 初始化临时文件与目录
        File tempDir = new File(App.getTempDirPath());
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
        mfTakePhoto = new File(tempDir, "TakePhoto.jpg");

//        File selectTempDir = new File(mBgSourceUtils.getBackgroundSourceDirPath(), "SelectTemp");
//        if (!selectTempDir.exists()) {
//            selectTempDir.mkdirs();
//            LogUtils.d(TAG, "【目录初始化】选图临时目录创建完成：" + selectTempDir.getAbsolutePath());
//        }

        // 初始化界面与事件
        initToolbar();
        initClickListeners();

        // 处理分享意图或初始化预览
        if (handleShareIntent()) {
            ToastUtils.show("handleShareIntent");
        } else {
            mBgSourceUtils.setCurrentSourceToPreview();
        }

        mBgSourceUtils.createAndUpdatePreviewEnvironmentForCropping(mBgSourceUtils.getPreviewBackgroundBean());
        doubleRefreshPreview();
        LogUtils.d(TAG, "【生命周期】onCreate 初始化完成");
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        doubleRefreshPreview();
        LogUtils.d(TAG, "【生命周期】onPostCreate 执行双重刷新");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.d(TAG, "【回调触发】requestCode：" + requestCode + "，resultCode：" + resultCode);

        try {
            if (resultCode != RESULT_OK) {
                handleOperationCancelOrFail();
                return;
            }

            switch (requestCode) {
                case REQUEST_SELECT_PICTURE:
                    handleSelectPictureResult(resultCode, data);
                    break;
                case REQUEST_TAKE_PHOTO:
                    handleTakePhotoResult(resultCode, data);
                    break;
                case REQUEST_CROP_IMAGE:
                    handleCropImageResult(requestCode, resultCode, data);
                    break;
				case REQUEST_PIXELPICKER:
                    handlePixelPickerResult(requestCode, resultCode, data);
                    break;
                default:
                    LogUtils.d(TAG, "【回调忽略】未知requestCode");
                    break;
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "【回调异常】" + e.getMessage());
            ToastUtils.show("操作失败");
        }
    }

    @Override
    public void finish() {
        LogUtils.d(TAG, "【生命周期】finish 触发，isCommitSettings：" + isCommitSettings + "，isPreviewBackgroundChanged：" + isPreviewBackgroundChanged);
        if (isCommitSettings) {
            super.finish();
        } else {
            if (isPreviewBackgroundChanged) {
                YesNoAlertDialog.show(this, "背景更换问题", "是否确定背景图片设置？", new YesNoAlertDialog.OnDialogResultListener() {
						@Override
						public void onYes() {
							//ToastUtils.show("onYes");
							mBgSourceUtils.commitPreviewSourceToCurrent();
							isCommitSettings = true;
							finish();
						}

						@Override
						public void onNo() {
							isCommitSettings = true;
							finish();
						}
					});
            } else {
                isCommitSettings = true;
                finish();
            }
        }
    }

    // ====================== 界面初始化方法 ======================
    private void initToolbar() {
        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setSubtitle(getTag());
        mToolbar.setTitleTextAppearance(this, R.style.Toolbar_TitleText);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					LogUtils.d(TAG, "【导航栏】点击返回");
					finish();
				}
			});
    }

    private void initClickListeners() {
        LogUtils.d(TAG, "【界面初始化】绑定按钮点击事件");
        findViewById(R.id.activitybackgroundpictureAButton5).setOnClickListener(onOriginNullClickListener);
        findViewById(R.id.activitybackgroundpictureAButton4).setOnClickListener(onReceivedPictureClickListener);
        findViewById(R.id.activitybackgroundpictureAButton1).setOnClickListener(onTakePhotoClickListener);
        findViewById(R.id.activitybackgroundpictureAButton2).setOnClickListener(onSelectPictureClickListener);
        findViewById(R.id.activitybackgroundpictureAButton3).setOnClickListener(onCropPictureClickListener);
        findViewById(R.id.activitybackgroundpictureAButton6).setOnClickListener(onCropFreePictureClickListener);
        findViewById(R.id.activitybackgroundpictureAButton7).setOnClickListener(onPixelPickerClickListener);
        findViewById(R.id.activitybackgroundpictureAButton8).setOnClickListener(onCleanPixelClickListener);
    }

    // ====================== 按钮点击事件 ======================
    private View.OnClickListener onOriginNullClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】取消背景图片");
            BackgroundBean previewBackgroundBean = mBgSourceUtils.getPreviewBackgroundBean();
            previewBackgroundBean.setIsUseBackgroundFile(false);
            doubleRefreshPreview();
        }
    };

    private View.OnClickListener onSelectPictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】选择图片");
			launchImageSelector();
        }
    };

    private View.OnClickListener onCropPictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】固定比例裁剪");
            ImageCropUtils.startImageCrop(BackgroundSettingsActivity.this,
										  mBgSourceUtils.getPreviewBackgroundBean(),
										  mBackgroundView.getWidth(),
										  mBackgroundView.getHeight(),
										  false,
										  REQUEST_CROP_IMAGE
										  );
        }
    };

    private View.OnClickListener onCropFreePictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】自由裁剪");
            ImageCropUtils.startImageCrop(BackgroundSettingsActivity.this,
										  mBgSourceUtils.getPreviewBackgroundBean(),
										  0,
										  0,
										  true,
										  REQUEST_CROP_IMAGE
										  );
        }
    };

    private View.OnClickListener onTakePhotoClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】拍照");
            // 移除：旧文件删除逻辑
            try {
                boolean createSuccess = mfTakePhoto.createNewFile();
                LogUtils.d(TAG, "【拍照准备】创建新文件：" + (createSuccess ? "成功" : "失败"));
                if (!createSuccess) {
                    ToastUtils.show("拍照文件创建失败");
                    return;
                }
            } catch (IOException e) {
                LogUtils.e(TAG, "【拍照异常】" + e.getMessage());
                ToastUtils.show("拍照文件创建失败");
                return;
            }

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			try {
				Uri photoUri = getFileProviderUri(mfTakePhoto);
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
				LogUtils.d(TAG, "【拍照启动】Uri：" + photoUri.toString());
			} catch (Exception e) {
				String errMsg = "拍照启动异常：" + e.getMessage();
				ToastUtils.show(errMsg.substring(0, 20));
				LogUtils.e(TAG, "【拍照失败】" + e.getMessage());
			}
        }
    };

    private View.OnClickListener onReceivedPictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ToastUtils.show("图片接收功能暂未实现");
            LogUtils.d(TAG, "【按钮点击】图片接收");
        }
    };

    private View.OnClickListener onPixelPickerClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】像素拾取");
            String targetImagePath = mBgSourceUtils.getPreviewBackgroundBean().getBackgroundFilePath();
            File targetFile = new File(targetImagePath);
            if (targetFile == null || !targetFile.exists() || targetFile.length() <= 0) {
                ToastUtils.show("无有效图片可拾取像素");
                LogUtils.e(TAG, "【像素拾取失败】文件无效：" + targetImagePath);
                return;
            }
            Intent intent = new Intent(getApplicationContext(), PixelPickerActivity.class);
            intent.putExtra("imagePath", targetImagePath);
            startActivityForResult(intent, REQUEST_PIXELPICKER);
            LogUtils.d(TAG, "【像素拾取启动】路径：" + targetImagePath);
        }
    };

    private View.OnClickListener onCleanPixelClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "【按钮点击】清空像素颜色");
            BackgroundBean bean = mBgSourceUtils.getPreviewBackgroundBean();
            int oldColor = bean.getPixelColor();
            bean.setPixelColor(0);
            mBgSourceUtils.saveSettings();
            doubleRefreshPreview();
			isPreviewBackgroundChanged = true;
            ToastUtils.show("像素颜色已清空");
            LogUtils.d(TAG, "【像素清空】旧颜色：" + oldColor);
        }
    };

    // ====================== 工具方法 ======================
    /**
     * 生成 FileProvider Uri，适配 Android 7.0+
     */
    public Uri getFileProviderUri(File file) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                String FILE_PROVIDER_AUTHORITY = getPackageName() + ".fileprovider";
                return FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, file);
            } else {
                return Uri.fromFile(file);
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "getFileProviderUri: 生成Uri失败：" + e.getMessage());
            return null;
        }
    }

    /**
     * 校验 Bitmap 是否有效（未被回收且不为空）
     */
    private boolean isBitmapValid(Bitmap bitmap) {
        return bitmap != null && !bitmap.isRecycled();
    }

    /**
     * 双重刷新预览，确保背景加载最新数据
     * 移除：缓存清空逻辑
     */
    private void doubleRefreshPreview() {
        LogUtils.d(TAG, "【工具方法】doubleRefreshPreview 开始执行");
        if (mBgSourceUtils == null || mBackgroundView == null || isFinishing()) {
            LogUtils.w(TAG, "【双重刷新】跳过：对象为空或Activity已结束");
            return;
        }

        // 第一重刷新
        try {
            mBgSourceUtils.loadSettings();
            mBackgroundView.loadBackgroundBean(mBgSourceUtils.getPreviewBackgroundBean(), true);
			mBackgroundView.setBackgroundColor(mBgSourceUtils.getPreviewBackgroundBean().getPixelColor());
            LogUtils.d(TAG, "【双重刷新】第一重完成");
        } catch (Exception e) {
            LogUtils.e(TAG, "【双重刷新】第一重异常：" + e.getMessage());
            return;
        }

        // 第二重刷新（延迟执行）
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
				@Override
				public void run() {
					if (mBackgroundView != null && !isFinishing() && mBgSourceUtils != null) {
						try {
							mBgSourceUtils.loadSettings();
							mBackgroundView.loadBackgroundBean(mBgSourceUtils.getPreviewBackgroundBean(), true);
							mBackgroundView.setBackgroundColor(mBgSourceUtils.getPreviewBackgroundBean().getPixelColor());
							LogUtils.d(TAG, "【双重刷新】第二重完成");
						} catch (Exception e) {
							LogUtils.e(TAG, "【双重刷新】第二重异常：" + e.getMessage());
						}
					}
				}
			}, 200);
    }

    /**
     * 解析裁剪临时文件为 Bitmap，带采样率优化
     */
    private Bitmap parseCropTempFileToBitmap(File cropTempFile) {
        LogUtils.d(TAG, "【工具方法】parseCropTempFileToBitmap 解析文件：" + (cropTempFile != null ? cropTempFile.getAbsolutePath() : "null"));
        if (cropTempFile == null || !cropTempFile.exists() || !cropTempFile.isFile() || cropTempFile.length() <= 100) {
            LogUtils.e(TAG, "【Bitmap解析】文件无效");
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(cropTempFile.getAbsolutePath(), options);

        int maxSize = 2048;
        int sampleSize = 1;
        while (options.outWidth / sampleSize > maxSize || options.outHeight / sampleSize > maxSize) {
            sampleSize *= 2;
        }
        sampleSize = Math.min(sampleSize, 16);
        LogUtils.d(TAG, "【Bitmap解析】采样率：" + sampleSize);

        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;

        try {
            Bitmap cropBitmap = BitmapFactory.decodeFile(cropTempFile.getAbsolutePath(), options);
            if (!isBitmapValid(cropBitmap)) {
                LogUtils.e(TAG, "【Bitmap解析】解析失败");
                return null;
            }
            LogUtils.d(TAG, "【Bitmap解析】成功，尺寸：" + cropBitmap.getWidth() + "x" + cropBitmap.getHeight());
            return cropBitmap;
        } catch (OutOfMemoryError e) {
            LogUtils.e(TAG, "【Bitmap解析】OOM异常");
            return null;
        } catch (Exception e) {
            LogUtils.e(TAG, "【Bitmap解析】异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 调整 Bitmap 比例至目标比例
     */
    private Bitmap adjustBitmapToFinalRatio(Bitmap originalBitmap, float finalCropRatio) {
        LogUtils.d(TAG, "【工具方法】adjustBitmapToFinalRatio 调整比例，目标比例：" + finalCropRatio);
        if (!isBitmapValid(originalBitmap) || finalCropRatio <= 0) {
            LogUtils.e(TAG, "【比例调整】参数无效");
            return null;
        }

        int originalWidth = originalBitmap.getWidth();
        int originalHeight = originalBitmap.getHeight();
        float originalRatio = (float) originalWidth / originalHeight;

        if (Math.abs(originalRatio - finalCropRatio) < 0.001f) {
            LogUtils.d(TAG, "【比例调整】比例一致，生成副本");
            return originalBitmap.copy(originalBitmap.getConfig(), false);
        }

        int targetWidth, targetHeight;
        targetHeight = originalHeight;
        targetWidth = Math.round(targetHeight * finalCropRatio);
        if (targetWidth > originalWidth) {
            targetWidth = originalWidth;
            targetHeight = Math.round(targetWidth / finalCropRatio);
        }
        targetWidth = Math.round(targetHeight * finalCropRatio);
        LogUtils.d(TAG, "【比例调整】调整前：" + originalWidth + "x" + originalHeight + "，调整后：" + targetWidth + "x" + targetHeight);

        try {
            Bitmap adjustedBitmap = Bitmap.createBitmap(
				originalBitmap,
				(originalWidth - targetWidth) / 2,
				(originalHeight - targetHeight) / 2,
				targetWidth,
				targetHeight
            );
            return adjustedBitmap;
        } catch (OutOfMemoryError e) {
            LogUtils.e(TAG, "【比例调整】OOM异常");
            return null;
        }
    }

    /**
     * 保存 Bitmap 到目标文件
     * 移除：原文件删除逻辑
     */
    private void saveScaledBitmapToFile(Bitmap bitmap, File targetFile) {
        LogUtils.d(TAG, "【工具方法】saveScaledBitmapToFile 保存图片：" + targetFile.getAbsolutePath());
        if (!isBitmapValid(bitmap) || targetFile == null) {
            LogUtils.e(TAG, "【图片保存】参数无效");
            return;
        }

        OutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
            bitmap.compress(CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            LogUtils.d(TAG, "【图片保存】成功，文件大小：" + targetFile.length() + " bytes");
        } catch (IOException e) {
            LogUtils.e(TAG, "【图片保存】异常：" + e.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    LogUtils.e(TAG, "【图片保存】关闭流异常");
                }
            }
        }
    }

    /**
     * 从裁剪文件中读取比例
     */
    private float getRatioFromSystemCropFile(File systemCropFile) {
        LogUtils.d(TAG, "【工具方法】getRatioFromSystemCropFile 读取比例：" + systemCropFile.getAbsolutePath());
        if (systemCropFile == null || !systemCropFile.exists() || !systemCropFile.isFile()) {
            LogUtils.e(TAG, "【比例读取】文件无效");
            return -1;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(systemCropFile.getAbsolutePath(), options);

        int cropWidth = options.outWidth;
        int cropHeight = options.outHeight;
        if (cropWidth <= 0 || cropHeight <= 0) {
            LogUtils.e(TAG, "【比例读取】尺寸无效");
            return -1;
        }

        float systemRatio = (float) cropWidth / cropHeight;
        LogUtils.d(TAG, "【比例读取】成功，比例：" + systemRatio);
        return systemRatio;
    }

    // ====================== 业务逻辑方法 ======================
    /**
     * 处理分享意图
     */
    private boolean handleShareIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            String action = intent.getAction();
            String type = intent.getType();
            if (Intent.ACTION_SEND.equals(action) && type != null && isImageType(type)) {
                BackgroundPicturePreviewDialog dlg = new BackgroundPicturePreviewDialog(this, new BackgroundPicturePreviewDialog.IOnRecivedPictureListener(){
						@Override
						public void onAcceptRecivedPicture(Uri uriRecivedPicture) {
							ToastUtils.show(String.format("uriRecivedPicture %s", uriRecivedPicture));
						}
					});
                dlg.show();
                LogUtils.d(TAG, "【分享处理】收到分享图片意图");
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否为图片类型
     */
    boolean isImageType(String lowerMimeType) {
        return lowerMimeType.equals("image/jpeg")
			|| lowerMimeType.equals("image/png")
			|| lowerMimeType.equals("image/tiff")
			|| lowerMimeType.equals("image/jpg")
			|| lowerMimeType.equals("image/svg+xml");
    }

    /**
     * 启动图片选择器
     */
    private void launchImageSelector() {
        LogUtils.d(TAG, "【业务逻辑】launchImageSelector 启动选择器");
        Intent[] intents = new Intent[3];
        Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT);
        getContentIntent.setType("image/*");
        getContentIntent.addCategory(Intent.CATEGORY_OPENABLE);
        getContentIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intents[0] = getContentIntent;

        Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setType("image/*");
        pickIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intents[1] = pickIntent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent openDocIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            openDocIntent.setType("image/*");
            openDocIntent.addCategory(Intent.CATEGORY_OPENABLE);
            openDocIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            intents[2] = openDocIntent;
        }

        Intent validIntent = null;
        for (Intent intent : intents) {
            if (intent != null && intent.resolveActivity(getPackageManager()) != null) {
                validIntent = intent;
                break;
            }
        }

        if (validIntent != null) {
            Intent chooser = Intent.createChooser(validIntent, "选择图片");
            chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            startActivityForResult(chooser, REQUEST_SELECT_PICTURE);
            LogUtils.d(TAG, "【选图意图】启动图片选择");
        } else {
            LogUtils.d(TAG, "【选图意图】无相册应用");
            runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ToastUtils.show("未找到相册应用，请安装后重试");
						new AlertDialog.Builder(BackgroundSettingsActivity.this)
                            .setTitle("无图片选择应用")
                            .setMessage("需要安装相册应用才能选择图片")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                                    marketIntent.setData(Uri.parse("market://details?id=com.android.gallery3d"));
                                    if (marketIntent.resolveActivity(getPackageManager()) != null) {
                                        startActivity(marketIntent);
                                    } else {
                                        ToastUtils.show("无法打开应用商店");
                                    }
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
					}
				});
        }
    }

    /**
     * 处理存储权限回调
     */
    private void handleStoragePermissionCallback() {
        if (Environment.isExternalStorageManager()) {
            LogUtils.d(TAG, "【权限回调】已授予");
            ToastUtils.show("存储权限已获取");
        } else {
            LogUtils.d(TAG, "【权限回调】已拒绝");
            ToastUtils.show("存储权限不足");
        }
    }

    /**
     * 处理操作取消或失败
     */
    private void handleOperationCancelOrFail() {
        mBgSourceUtils.setCurrentSourceToPreview();
        LogUtils.d(TAG, "【业务逻辑】操作取消或失败，恢复预览");
        ToastUtils.show("操作取消或失败");
        doubleRefreshPreview();
    }

    /**
     * 处理拍照结果
     */
    private void handleTakePhotoResult(int resultCode, Intent data) {
        LogUtils.d(TAG, "【业务逻辑】handleTakePhotoResult 处理拍照结果");
        if (resultCode != RESULT_OK || data == null) {
            handleOperationCancelOrFail();
            return;
        }

        if (!mfTakePhoto.exists() || mfTakePhoto.length() <= 0) {
            ToastUtils.show("拍照文件无效");
            return;
        }

        Bitmap photoBitmap = getTakePhotoBitmap(data);
        if (isBitmapValid(photoBitmap)) {
            mBgSourceUtils.compressQualityToRecivedPicture(photoBitmap);
        } else {
            ToastUtils.show("拍照图片为空");
            return;
        }

        mBgSourceUtils.saveFileToPreviewBean(mfTakePhoto, mfTakePhoto.getAbsolutePath());
        doubleRefreshPreview();

        ImageCropUtils.startImageCrop(BackgroundSettingsActivity.this,
									  mBgSourceUtils.getPreviewBackgroundBean(),
									  mBackgroundView.getWidth(),
									  mBackgroundView.getHeight(),
									  false,
									  REQUEST_CROP_IMAGE
									  );
        LogUtils.d(TAG, "【拍照完成】已启动裁剪");
    }

    /**
     * 解析拍照返回的 Bitmap
     */
    private Bitmap getTakePhotoBitmap(Intent data) {
        LogUtils.d(TAG, "【业务逻辑】getTakePhotoBitmap 解析拍照Bitmap");
        if (mfTakePhoto != null && mfTakePhoto.exists()) {
            LogUtils.d(TAG, "【拍照Bitmap解析】从文件解析");
            Bitmap photoBitmap = parseCropTempFileToBitmap(mfTakePhoto);
            if (isBitmapValid(photoBitmap)) {
                LogUtils.d(TAG, "【拍照Bitmap解析】成功");
                return photoBitmap;
            } else {
                LogUtils.w(TAG, "【拍照Bitmap解析】文件解析失败，尝试Intent");
            }
        } else {
            LogUtils.w(TAG, "【拍照Bitmap解析】文件无效，尝试Intent");
        }

        if (data != null) {
            try {
                Bitmap thumbnailBitmap = data.getParcelableExtra("data");
                if (isBitmapValid(thumbnailBitmap)) {
                    LogUtils.d(TAG, "【拍照Bitmap解析】从Intent获取成功");
                    return thumbnailBitmap;
                } else {
                    LogUtils.e(TAG, "【拍照Bitmap解析】Intent解析失败");
                }
            } catch (Exception e) {
                LogUtils.e(TAG, "【拍照Bitmap解析】Intent异常：" + e.getMessage());
            }
        } else {
            LogUtils.e(TAG, "【拍照Bitmap解析】Intent为空");
        }

        LogUtils.e(TAG, "【拍照Bitmap解析】失败");
        ToastUtils.show("拍照图片解析失败");
        return null;
    }

    /**
     * 处理选图结果
     * 移除：缓存清空逻辑
     */
    private void handleSelectPictureResult(int resultCode, Intent data) {
        LogUtils.d(TAG, "【业务逻辑】handleSelectPictureResult 处理选图结果");
        if (resultCode != RESULT_OK || data == null) {
            handleOperationCancelOrFail();
            return;
        }

        Uri selectedImage = data.getData();
        if (selectedImage == null) {
            ToastUtils.show("图片Uri为空");
            return;
        }
        LogUtils.d(TAG, "【选图回调】系统返回Uri : " + selectedImage.toString());

        if (Build.VERSION.SDK_INT >= SDK_VERSION_TIRAMISU) {
            getContentResolver().takePersistableUriPermission(
				selectedImage,
				Intent.FLAG_GRANT_READ_URI_PERMISSION
            );
            LogUtils.d(TAG, "【选图权限】已添加持久化权限");
        }

        if (putUriFileToPreviewSource(selectedImage)) {
            LogUtils.d(TAG, "【选图同步】路径绑定完成");
            ImageCropUtils.startImageCrop(BackgroundSettingsActivity.this,
										  mBgSourceUtils.getPreviewBackgroundBean(),
										  mBackgroundView.getWidth(),
										  mBackgroundView.getHeight(),
										  false,
										  REQUEST_CROP_IMAGE
										  );
        } else {
            ToastUtils.show("图片同步失败");
            LogUtils.e(TAG, "【选图同步】文件复制失败");
        }
    }

    /**
     * 将 Uri 文件同步到预览 Bean
     */
    boolean putUriFileToPreviewSource(Uri srcUriFile) {
        String filePath = UriUtils.getFilePathFromUri(this, srcUriFile);
        if (TextUtils.isEmpty(filePath)) {
            LogUtils.e(TAG, "putUriFileToPreviewSource: Uri解析路径为空");
            return false;
        }
        File srcFile = new File(filePath);
        return putUriFileToPreviewSource(srcFile);
    }

    /**
     * 将 File 同步到预览 Bean
     * 保留：核心修复逻辑（更新预览Bean路径）
     */
    boolean putUriFileToPreviewSource(File srcFile) {
        LogUtils.d(TAG, String.format("putUriFileToPreviewSource(File srcFile) srcFile %s", srcFile));
		mBgSourceUtils.loadSettings();
		BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
		File dstFile = new File(previewBean.getBackgroundFilePath());
		LogUtils.d(TAG, String.format("putUriFileToPreviewSource(File srcFile) dstFile %s", dstFile));
        if (FileUtils.copyFile(srcFile, dstFile)) {
			LogUtils.d(TAG, "putUriFileToPreviewSource(File srcFile) 文件拷贝成功。 ");
			return true;
		}
		LogUtils.d(TAG, "putUriFileToPreviewSource(File srcFile) 文件无法拷贝。 ");
		return false;
    }

    /**
     * 处理裁剪结果
     */
    private void handleCropImageResult(int requestCode, int resultCode, Intent data) {
        LogUtils.d(TAG, "【业务逻辑】handleCropImageResult 处理裁剪结果");
        File cropTempFile = new File(mBgSourceUtils.getPreviewBackgroundBean().getBackgroundScaledCompressFilePath());
        boolean isFileExist = cropTempFile.exists();
        boolean isFileReadable = isFileExist ? cropTempFile.canRead() : false;
        long fileSize = isFileExist ? cropTempFile.length() : 0;
        boolean isCropSuccess = (resultCode == RESULT_OK) && isFileExist && isFileReadable && fileSize > 100;

        if (isCropSuccess) {
            isPreviewBackgroundChanged = true;
            LogUtils.d(TAG, "【裁剪结果】裁剪成功");
            final BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
            previewBean.setIsUseBackgroundFile(true);
            previewBean.setIsUseBackgroundScaledCompressFile(true);
            mBgSourceUtils.saveSettings();

            float systemFileRatio = getRatioFromSystemCropFile(cropTempFile);
            if (systemFileRatio > 0) {
                Bitmap cropBitmap = parseCropTempFileToBitmap(cropTempFile);
                if (isBitmapValid(cropBitmap)) {
                    Bitmap scaledCropBitmap = adjustBitmapToFinalRatio(cropBitmap, systemFileRatio);
                    if (isBitmapValid(scaledCropBitmap)) {
                        saveScaledBitmapToFile(scaledCropBitmap, cropTempFile);
                        scaledCropBitmap.recycle();
                    }
                    cropBitmap.recycle();
                } else {
                    LogUtils.e(TAG, "【裁剪结果】裁剪Bitmap解析无效");
                }
            }

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
					@Override
					public void run() {
						if (!isFinishing()) {
							doubleRefreshPreview();
							LogUtils.d(TAG, "【裁剪结果】触发双重刷新");
						}
					}
				}, 300);
        } else {
            handleOperationCancelOrFail();
        }
    }

	private void handlePixelPickerResult(int requestCode, int resultCode, Intent data) {
		doubleRefreshPreview();
		isPreviewBackgroundChanged = true;
	}
}

