package cc.winboll.studio.powerbell.activities;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import cc.winboll.studio.libaes.dialogs.YesNoAlertDialog;
import cc.winboll.studio.libaes.views.AToolbar;
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.model.BackgroundBean;
import cc.winboll.studio.powerbell.dialogs.BackgroundPicturePreviewDialog;
import cc.winboll.studio.powerbell.dialogs.NetworkBackgroundDialog;
import cc.winboll.studio.powerbell.utils.BackgroundSourceUtils;
import cc.winboll.studio.powerbell.utils.FileUtils;
import cc.winboll.studio.powerbell.utils.UriUtil;
import cc.winboll.studio.powerbell.views.BackgroundView;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import androidx.core.util.Preconditions;

public class BackgroundSettingsActivity extends WinBoLLActivity implements BackgroundPicturePreviewDialog.IOnRecivedPictureListener {

    public static final String TAG = "BackgroundSettingsActivity";
    public BackgroundSourceUtils mBackgroundSourceUtils;

    // 图片选择请求码
    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 STORAGE_PERMISSION_REQUEST = 100;

    private AToolbar mAToolbar;
    private File mfBackgroundDir;       // 背景图片存储文件夹
    private File mfPictureDir;          // 拍照与剪裁临时文件夹
    private File mfTakePhoto;           // 拍照文件
    //private File mfRecivedPicture;      // 接收的图片文件

	// 背景视图预览图片的文件名
	private String preViewFilePath = "";
	private String preViewFileUrl = "";
	BackgroundView bvPreviewBackground;
	boolean isCommitSettings = false;

    // 静态变量
	// 源文件的临时剪裁图片保存名称
    private static String _mSourceCropTempFileName = "SourceCropTemp.jpg";
	// 源文件的临时剪裁图片保存文件对象
	private static File _mSourceCropTempFile;
    // 源文件的剪裁图片保存名称
    private static String _mSourceCroppedFileName = "SourceCropped.jpg";
	// 源文件的剪裁图片保存文件对象
	private static File _mSourceCroppedFile;
	// 源文件的剪裁图片保存路径
	private static String _mSourceCroppedFilePath;
    private static String _mszCommonFileType = "jpeg";
    private int mnPictureCompress = 100;
    //private static String _RecivedBackgroundFileName;

	@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_backgroundpicture);
		bvPreviewBackground = (BackgroundView) findViewById(R.id.activitybackgroundpictureBackgroundView1);
		
        //initEnv();

        // 初始化工具类和文件夹
        mBackgroundSourceUtils = BackgroundSourceUtils.getInstance(this);
        mfBackgroundDir = new File(mBackgroundSourceUtils.getBackgroundSourceDirPath());
        if (!mfBackgroundDir.exists()) {
            mfBackgroundDir.mkdirs();
        }

        mfPictureDir = new File(App.getTempDirPath());
        if (!mfPictureDir.exists()) {
            mfPictureDir.mkdirs();
        }

        // 初始化文件对象
        mfTakePhoto = new File(mfPictureDir, "TakePhoto.jpg");
        //mfTempCropPicture = new File(mfPictureDir, "TempCrop.jpg");

        //mfRecivedPicture = getRecivedPictureFile();
        _mSourceCropTempFile = new File(mfBackgroundDir, _mSourceCropTempFileName);
        _mSourceCroppedFile = new File(mfBackgroundDir, _mSourceCroppedFileName);
		_mSourceCroppedFilePath = _mSourceCroppedFile.getAbsolutePath().toString();
		LogUtils.d(TAG, String.format("_mSourceCroppedFilePath : %s", _mSourceCroppedFilePath));

        // 初始化工具栏
        mAToolbar = (AToolbar) findViewById(R.id.toolbar);
        setActionBar(mAToolbar);
        mAToolbar.setSubtitle(R.string.subtitle_activity_backgroundpicture);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        mAToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish(); // 点击导航栏返回按钮，触发 finish()
                }
            });

        // 设置按钮点击事件
        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);

        BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
		utils.setCurrentSourceToPreview();
		bvPreviewBackground.reloadPreviewBackground();

        // 处理分享的图片
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null && isImageType(type)) {
            BackgroundPicturePreviewDialog dlg = new BackgroundPicturePreviewDialog(this);
            dlg.show();
        }
    }

//    private void initEnv() {
//        LogUtils.d(TAG, "initEnv()");
//        _RecivedBackgroundFileName = "SourcePicture.data";
//    }

    public static String getBackgroundFileName() {
        return _mSourceCroppedFileName;
    }

    @Override
    public void onAcceptRecivedPicture(String szPreRecivedPictureName) {
		ToastUtils.show("onAcceptRecivedPicture not yet.");
//        BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(this);
//        utils.getCurrentBackgroundBean().setIsUseBackgroundFile(true);
//        utils.saveSettings();
//
//        File sourceFile = new File(utils.getBackgroundSourceDirPath(), szPreRecivedPictureName);
//        if (FileUtils.copyFile(sourceFile, mfRecivedPicture)) {
//            startCropImageActivity(false);
//        } else {
//            ToastUtils.show("图片复制失败，请重试");
//        }
    }

    /**
     * 更新背景图片预览，
	 * 如果sourceFile参数为空，则加载旧的背景图片资源
     */
    public void updateBackgroundView(File sourceFile, String sourceFileInfo) {
        LogUtils.d(TAG, "updatePreviewBackground");
		BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(this);
		if (sourceFile == null) {
			bvPreviewBackground.reloadCurrentBackground();
		} else {
			utils.saveFileToPreviewBean(sourceFile, sourceFileInfo);
			bvPreviewBackground.reloadPreviewBackground();
		}

//        boolean isUseBackgroundFile = utils.getCurrentBackgroundBean().isUseBackgroundFile();
//		LogUtils.d(TAG, String.format("isUseBackgroundFile is %s, _mSourceCroppedFile.exists() is %s ", isUseBackgroundFile, _mSourceCroppedFile.exists()));
//
//        //if (isUseBackgroundFile && _mSourceCroppedFile.exists()) {
//		if (_mSourceCroppedFile.exists()) {
//			//try {
//			//String filePath = utils.getBackgroundDir() + getBackgroundFileName();
//			preViewFilePath = _mSourceCroppedFilePath;
//			LogUtils.d(TAG, String.format("preViewFilePathBackgroundView : %s", preViewFilePath));
//			bvPreviewBackground.previewBackgroundImage(preViewFilePath);
//			/*Drawable drawable = FileUtils.getImageDrawable(filePath);
//			 if (drawable != null) {
//			 //drawable.setAlpha(120);
//			 //bvPreviewBackground.setImageDrawable(drawable);
//			 }*/
//			//ToastUtils.show("背景图片已更新");
////            } catch (IOException e) {
////                LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
////                ToastUtils.show("背景图片加载失败");
////            }
//        } else {
//            ToastUtils.show("未使用背景图片");
//			preViewFilePath = "";
//			bvPreviewBackground.previewBackgroundImage(preViewFilePath);
////            Drawable drawable = getResources().getDrawable(R.drawable.blank10x10);
////            if (drawable != null) {
////                drawable.setAlpha(120);
////                bvPreviewBackground.setImageDrawable(drawable);
////            }
//        }
    }

    // 点击事件监听器
    private View.OnClickListener onOriginNullClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
            BackgroundBean bean = utils.getCurrentBackgroundBean();
            bean.setIsUseBackgroundFile(false);
            utils.saveSettings();
			bvPreviewBackground.reloadPreviewBackground();
        }
    };

    private View.OnClickListener onSelectPictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (checkAndRequestStoragePermission()) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_SELECT_PICTURE);
            }
        }
    };

    private View.OnClickListener onCropPictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            File fCheck = new File(mfBackgroundDir, getBackgroundFileName());
            if (fCheck.exists()) {
                startCropImageActivity(false);
            } else {
                ToastUtils.show("没有可剪裁的图片");
            }
        }
    };

    private View.OnClickListener onCropFreePictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            File fCheck = new File(mfBackgroundDir, getBackgroundFileName());
            if (fCheck.exists()) {
                startCropImageActivity(true);
            } else {
                ToastUtils.show("没有可剪裁的图片");
            }
        }
    };

    private View.OnClickListener onTakePhotoClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d(TAG, "onTakePhotoClickListener");
            LogUtils.d(TAG, "mfTakePhoto : " + mfTakePhoto.getPath());

            if (mfTakePhoto.exists()) {
                mfTakePhoto.delete();
            }
            try {
                mfTakePhoto.createNewFile();
            } catch (IOException e) {
                LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
                ToastUtils.show("拍照文件创建失败");
                return;
            }

            if (checkAndRequestStoragePermission()) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    };

    private View.OnClickListener onReceivedPictureClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
			ToastUtils.show("onReceivedPictureClickListener not yet.");
//            BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
//            utils.getCurrentBackgroundBean().setIsUseBackgroundFile(true);
//            utils.saveSettings();
//            updateBackgroundView();
        }
    };

	private View.OnClickListener onPixelPickerClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
			// 从文件路径启动像素拾取活动
			//String imagePath = "/storage/emulated/0/DCIM/Camera/sample.jpg";
			String imagePath = _mSourceCroppedFile.toString();
			Intent intent = new Intent(getApplicationContext(), PixelPickerActivity.class);
			intent.putExtra("imagePath", imagePath);
			startActivity(intent);
            //App.getWinBoLLActivityManager().startWinBoLLActivity(getActivity(), intent, PixelPickerActivity.class);
        }
    };

	private View.OnClickListener onCleanPixelClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
			BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
			BackgroundBean bean = utils.getCurrentBackgroundBean();
			bean.setPixelColor(0);
			utils.saveSettings();
			setBackgroundColor();
        }
    };

    /**
     * 压缩图片并保存到接收文件
     */
    void compressQualityToRecivedPicture(Bitmap bitmap) {
        OutputStream outStream = null;
        try {
			BackgroundSourceUtils utils= BackgroundSourceUtils.getInstance(this);
            File fRecivedPicture = new File(utils.getPreviewBackgroundScaledCompressFilePath());
            if (!fRecivedPicture.exists()) {
                fRecivedPicture.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(fRecivedPicture);
            outStream = new BufferedOutputStream(fos);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
        } catch (IOException e) {
            LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
            ToastUtils.show("图片压缩失败");
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
                }
            }
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
    }

    /**
     * 启动图片裁剪活动
     * @param isCropFree 是否自由裁剪
     */
    public void startCropImageActivity(boolean isCropFree) {
        LogUtils.d(TAG, "startCropImageActivity");
		BackgroundSourceUtils utils= BackgroundSourceUtils.getInstance(this);
	    BackgroundBean bean = utils.getPreviewBackgroundBean();
		bean.setIsUseScaledCompress(true);
		utils.saveSettings();
		
		File fRecivedPicture = new File(utils.getPreviewBackgroundFilePath());
		
        Uri uri = UriUtil.getUriForFile(this, fRecivedPicture);
        LogUtils.d(TAG, "uri : " + uri.toString());

        if (_mSourceCropTempFile.exists()) {
            _mSourceCropTempFile.delete();
        }

        try {
            _mSourceCropTempFile.createNewFile();
        } catch (IOException e) {
            LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
            ToastUtils.show("剪裁临时文件创建失败");
            return;
        }

        Uri cropOutPutUri = Uri.fromFile(_mSourceCropTempFile);
        LogUtils.d(TAG, "mfTempCropPicture : " + _mSourceCropTempFile.getPath());

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/" + _mszCommonFileType);
        intent.putExtra("crop", "true");
        intent.putExtra("noFaceDetection", true);

        if (!isCropFree) {
            intent.putExtra("aspectX", bean.getBackgroundWidth());
            intent.putExtra("aspectY", bean.getBackgroundHeight());
        }

        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropOutPutUri);
        intent.putExtra("scale", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        startActivityForResult(intent, REQUEST_CROP_IMAGE);
    }

    /**
     * 保存剪裁后的Bitmap（优化版）
     */
    private void saveCropBitmap(Bitmap bitmap) {
        if (bitmap == null) {
            ToastUtils.show("剪裁图片为空");
            return;
        }

        // 内存优化：大图片自动缩放
        Bitmap scaledBitmap = bitmap;
        if (bitmap.getByteCount() > 10 * 1024 * 1024) { // 超过10MB
            float scale = 1.0f;
            while (scaledBitmap.getByteCount() > 5 * 1024 * 1024) {
                scale -= 0.2f; // 每次缩小20%
                if (scale < 0.2f) break; // 最小缩放到20%
                scaledBitmap = scaleBitmap(scaledBitmap, scale);
            }
            if (scaledBitmap != bitmap) {
                bitmap.recycle(); // 回收原Bitmap
            }
        }

        // 优化：创建保存目录
        File backgroundDir = new File(mBackgroundSourceUtils.getBackgroundSourceDirPath());
        if (!backgroundDir.exists()) {
            if (!backgroundDir.mkdirs()) {
                ToastUtils.show("无法创建保存目录");
                if (scaledBitmap != bitmap) scaledBitmap.recycle();
                return;
            }
        }

		// 剪裁的图片的保存地址
        File fScaledCompressBitmapFile = new File(backgroundDir, BackgroundSourceUtils.getInstance(this).getPreviewBackgroundScaledCompressFilePath());

        // 优化：检查文件是否可写
        if (fScaledCompressBitmapFile.exists() && !fScaledCompressBitmapFile.canWrite()) {
            if (!fScaledCompressBitmapFile.delete()) {
                ToastUtils.show("无法删除旧文件");
                if (scaledBitmap != bitmap) scaledBitmap.recycle();
                return;
            }
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fScaledCompressBitmapFile);
            boolean success = scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            if (success) {
				ToastUtils.show("图片压缩保存成功");
				BackgroundSourceUtils.getInstance(this).getPreviewBackgroundBean().setIsUseScaledCompress(true);
				BackgroundSourceUtils.getInstance(this).saveSettings();
				bvPreviewBackground.reloadPreviewBackground();

            } else {
                ToastUtils.show("图片压缩保存失败");
				BackgroundSourceUtils.getInstance(this).getPreviewBackgroundBean().setIsUseScaledCompress(false);
				BackgroundSourceUtils.getInstance(this).saveSettings();
				bvPreviewBackground.reloadPreviewBackground();
            }
        } catch (FileNotFoundException e) {
            LogUtils.e(TAG, "文件未找到" + e);
            ToastUtils.show("文件未找到" + e);
        } catch (IOException e) {
            LogUtils.e(TAG, "写入异常" + e);
            ToastUtils.show("写入异常" + e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    LogUtils.e(TAG, "流关闭异常" + e);
					ToastUtils.show("流关闭异常" + e);
				}
			}
			if (scaledBitmap != null && !scaledBitmap.isRecycled()) {
				scaledBitmap.recycle();
			}
		}
	}

    /**
     * 缩放Bitmap
     */
    private Bitmap scaleBitmap(Bitmap original, float scale) {
        if (original == null) {
            return null;
        }
        int width = (int) (original.getWidth() * scale);
        int height = (int) (original.getHeight() * scale);
        return Bitmap.createScaledBitmap(original, width, height, true);
    }

    /**
     * 分享图片
     */
    void sharePicture() {
		BackgroundSourceUtils utils= BackgroundSourceUtils.getInstance(this);
		File fRecivedPicture = new File(utils.getCurrentBackgroundFilePath());
        Uri uri = UriUtil.getUriForFile(this, fRecivedPicture);
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.setType("image/" + _mszCommonFileType);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "Share Image"));
    }

//    public File getRecivedPictureFile() {
//        BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(this);
//        utils.loadSettings();
//        return new File(utils.getBackgroundSourceDirPath(), _RecivedBackgroundFileName);
//    }

//	public void saveToRecivedBackground(String srcFilePath, String srcFillSourcePath) {
//        BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(this);
//        utils.loadSettings();
//        File dstFile = new File(utils.getBackgroundSourceDirPath(), _RecivedBackgroundFileName);
//		//compressQualityToRecivedPicture(srcFilePath);
//		ToastUtils.show("compressQualityToRecivedPicture not yet.");
//		FileUtils.copyFile(new File(srcFilePath), dstFile);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_PICTURE && resultCode == RESULT_OK) {
            try {
                Uri selectedImage = data.getData();
                LogUtils.d(TAG, "Uri is : " + selectedImage.toString());
                File fSrcImage = new File(UriUtil.getFilePathFromUri(this, selectedImage));
				BackgroundSourceUtils utils= BackgroundSourceUtils.getInstance(this);
				utils.saveFileToPreviewBean(fSrcImage, selectedImage.toString());
				startCropImageActivity(false);
				//mfRecivedPicture = getRecivedPictureFile();
//				BackgroundBean bean = utils.getPreviewBackgroundBean();
//                mfRecivedPicture = getRecivedPictureFile();
//                if (FileUtils.copyFile(fSrcImage, mfRecivedPicture)) {
//                    startCropImageActivity(false);
//                } else {
//                    ToastUtils.show("图片复制失败，请重试");
//                }
            } catch (Exception e) {
                LogUtils.e(TAG, "选择图片异常" + e);
                ToastUtils.show("选择图片失败：" + e.getMessage());
            }
        } else if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            LogUtils.d(TAG, "REQUEST_TAKE_PHOTO");
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                if (imageBitmap != null) {
                    compressQualityToRecivedPicture(imageBitmap);
                    startCropImageActivity(false);
                } else {
                    ToastUtils.show("拍照图片为空");
                }
            } else {
                ToastUtils.show("拍照数据获取失败");
            }
        } else if (requestCode == REQUEST_CROP_IMAGE && resultCode == RESULT_OK) {
            LogUtils.d(TAG, "CROP_IMAGE_REQUEST_CODE");
            try {
                Bitmap cropBitmap = null;
                // 方案1：通过Intent获取剪裁后的Bitmap
                if (data != null && data.hasExtra("data")) {
                    cropBitmap = data.getParcelableExtra("data");
                } else if (_mSourceCropTempFile.exists()) {
					LogUtils.d(TAG, String.format("_mSourceCropTempFile Exists, Path is ：%s ", _mSourceCropTempFile.getPath()));
                    cropBitmap = BitmapFactory.decodeFile(_mSourceCropTempFile.getPath());
                } else {
                    ToastUtils.show("剪裁文件不存在");
                    return;
                }

                if (cropBitmap != null) {
                    saveCropBitmap(cropBitmap);
                } else {
                    ToastUtils.show("获取剪裁图片失败");
                }
            } catch (OutOfMemoryError e) {
                LogUtils.e(TAG, "内存溢出" + e);
                ToastUtils.show("保存失败：内存不足，请尝试裁剪更小的图片");
            } catch (Exception e) {
                LogUtils.e(TAG, "剪裁保存异常" + e);
                ToastUtils.show("保存失败：" + e.getMessage());
            }/* finally {
			 // 安全删除临时文件
			 if (mfTempCropPicture.exists()) {
			 mfTempCropPicture.delete();
			 }
			 }*/
        } else if (resultCode != RESULT_OK) {
            LogUtils.d(TAG, "操作取消或失败，requestCode: " + requestCode);
            ToastUtils.show("操作已取消");
        }
    }

    /**
     * 检查类型是否为图片
     */
    private boolean isImageType(String type) {
        return type.startsWith("image/") || "image/jpeg".equals(type) || 
            "image/jpg".equals(type) || "image/png".equals(type) || 
            "image/webp".equals(type);
    }

    /**
     * 检查并申请存储权限
     */
    private boolean checkAndRequestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, 
                                                  new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
                                                  STORAGE_PERMISSION_REQUEST);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ToastUtils.show("存储权限已获取");
            } else {
                ToastUtils.show("需要存储权限才能保存图片");
            }
        }
    }

	void setBackgroundColor() {
		BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
		BackgroundBean bean = utils.getCurrentBackgroundBean();
		int nPixelColor = bean.getPixelColor();
		RelativeLayout mainLayout = findViewById(R.id.activitybackgroundpictureRelativeLayout1);
		mainLayout.setBackgroundColor(nPixelColor);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setBackgroundColor();
	}

	public void onNetworkBackgroundDialog(View view) {
		// 在需要显示对话框的地方（如网络状态监听回调中）
		NetworkBackgroundDialog dialog = new NetworkBackgroundDialog(this, new NetworkBackgroundDialog.OnDialogClickListener() {
				@Override
				public void onConfirm(String szConfirmFilePath, String szConfirmFileUrl) {
					//ToastUtils.show("onConfirm");
					// 保存预览资源信息
					preViewFilePath = szConfirmFilePath;
					preViewFileUrl = szConfirmFileUrl;
					onRecivedPictureListener.onRecivedPicture(preViewFilePath, preViewFileUrl);
				}

				@Override
				public void onCancel() {
					//ToastUtils.show("onCancel");
				}
			});

		// 可选：修改对话框标题和内容（适配自定义场景）
		dialog.setTitle("网络图片下载对话框");
		dialog.setContent("是否下载地址中的图片资源，作为应用背景图片？");

		// 显示对话框
		dialog.show();

	}

	interface OnRecivedPictureListener {
		void onRecivedPicture(String srcFilePath, String srcFileUrl);
	}

	OnRecivedPictureListener onRecivedPictureListener = new OnRecivedPictureListener(){
		@Override
		public void onRecivedPicture(String srcFilePath, String srcFileUrl) {
			BackgroundSourceUtils utils= BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
			utils.saveFileToPreviewBean(new File(srcFilePath), srcFileUrl);
			startCropImageActivity(true);
		}
	};

    /**
     * 重写finish方法，确保所有退出场景都触发Toast
     */
    @Override
    public void finish() {
        if (!isCommitSettings) {
			YesNoAlertDialog.show(this, "应用背景更改提示：", "是否应用预览图片？", new YesNoAlertDialog.OnDialogResultListener(){

					@Override
					public void onNo() {
						isCommitSettings = true;
						BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
						BackgroundBean bean = utils.getCurrentBackgroundBean();
						bean.setIsUseBackgroundFile(!preViewFilePath.equals(""));
						utils.saveSettings();
						finish();
					}

					@Override
					public void onYes() {
						BackgroundSourceUtils utils = BackgroundSourceUtils.getInstance(BackgroundSettingsActivity.this);
						utils.commitPreviewSourceToCurrent();
						isCommitSettings = true;
						finish();
					}
				});
		} else {
			super.finish();
		}
    }
}

