package cc.winboll.studio.powerbell.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.powerbell.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/11/19 18:01
 * @Describe 背景图片视图控件（支持预览临时图片 + 外部刷新）
 */
public class BackgroundView extends RelativeLayout {

    public static final String TAG = "BackgroundView";

    Context mContext;
    private ImageView ivBackground;

    private static String BACKGROUND_IMAGE_FOLDER = "Background";
    private static String BACKGROUND_IMAGE_FILENAME = "current.data";
    private static String BACKGROUND_IMAGE_PREVIEW_FILENAME = "current_preview.data";
    private static String backgroundSourceFilePath;
    private float imageAspectRatio = 1.0f; // 默认 1:1
    // 标记当前是否处于预览状态
    private boolean isPreviewMode = false;

    public BackgroundView(Context context) {
        super(context);
        this.mContext = context;
        initView();
    }

    public BackgroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
    }

    public BackgroundView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();
    }

    public BackgroundView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.mContext = context;
        initView();
    }

    void initView() {
        initBackgroundImageView();
        initBackgroundImagePath();
        loadAndSetImageViewBackground();
    }

    private void initBackgroundImageView() {
        ivBackground = new ImageView(mContext);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        ivBackground.setLayoutParams(layoutParams);
        ivBackground.setScaleType(ImageView.ScaleType.FIT_CENTER);
        this.addView(ivBackground);
    }

    private void initBackgroundImagePath() {
        File externalFilesDir = mContext.getExternalFilesDir(null);
        if (externalFilesDir == null) {
            LogUtils.e(TAG, "外置存储不可用，无法初始化背景图片路径");
            return;
        }

        File backgroundDir = new File(externalFilesDir, BACKGROUND_IMAGE_FOLDER);
        if (!backgroundDir.exists()) {
            backgroundDir.mkdirs();
        }
        backgroundSourceFilePath = new File(backgroundDir, BACKGROUND_IMAGE_FILENAME).getAbsolutePath();
    }

    /**
     * 拷贝图片文件到背景资源目录（正式背景）
     */
    public void saveToBackgroundSources(String srcBackgroundPath) {
        initBackgroundImagePath();
        if (backgroundSourceFilePath == null) {
            LogUtils.e(TAG, "目标路径初始化失败，无法保存背景图片");
            return;
        }

        File srcFile = new File(srcBackgroundPath);
        if (!srcFile.exists() || !srcFile.isFile()) {
            LogUtils.e(TAG, String.format("源文件不存在或不是文件：%s", srcBackgroundPath));
            return;
        }

        File destFile = new File(backgroundSourceFilePath);
        File destDir = destFile.getParentFile();
        if (destDir != null && !destDir.exists()) {
            boolean isDirCreated = destDir.mkdirs();
            if (!isDirCreated) {
                LogUtils.e(TAG, "目标目录创建失败：" + destDir.getAbsolutePath());
                return;
            }
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            byte[] buffer = new byte[4096];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();

            LogUtils.d(TAG, String.format("文件拷贝成功：%s -> %s", srcBackgroundPath, backgroundSourceFilePath));
            // 拷贝成功后，若处于预览模式则退出预览，加载正式背景
            if (isPreviewMode) {
                exitPreviewMode();
            } else {
                loadAndSetImageViewBackground();
            }

        } catch (Exception e) {
            LogUtils.e(TAG, String.format("文件拷贝失败：%s", e.getMessage()), e);
            if (destFile.exists()) {
                destFile.delete();
                LogUtils.d(TAG, "已删除损坏的目标文件");
            }
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    LogUtils.e(TAG, "输入流关闭失败：" + e.getMessage());
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    LogUtils.e(TAG, "输出流关闭失败：" + e.getMessage());
                }
            }
        }
    }

    /**
     * 【新增公共函数】预览临时图片（不修改正式背景文件）
     * @param previewImagePath 临时预览图片的路径
     */
    public void previewBackgroundImage(String previewImagePath) {
        if (previewImagePath == null || previewImagePath.isEmpty()) {
            LogUtils.e(TAG, "预览图片路径为空");
            return;
        }

        File previewFile = new File(previewImagePath);
        if (!previewFile.exists() || !previewFile.isFile()) {
            LogUtils.e(TAG, "预览图片不存在或不是文件：" + previewImagePath);
            return;
        }

        // 计算预览图片宽高比
        if (!calculateImageAspectRatio(previewFile)) {
            LogUtils.e(TAG, "预览图片尺寸无效，无法预览");
            return;
        }

        // 压缩加载预览图片
        Bitmap previewBitmap = decodeBitmapWithCompress(previewFile, 1080, 1920);
        if (previewBitmap == null) {
            LogUtils.e(TAG, "预览图片加载失败");
            return;
        }

        // 设置预览图片到 ImageView
        Drawable previewDrawable = new BitmapDrawable(mContext.getResources(), previewBitmap);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            ivBackground.setBackground(previewDrawable);
        } else {
            ivBackground.setBackgroundDrawable(previewDrawable);
        }

        // 调整 ImageView 尺寸以匹配预览图片宽高比
        adjustImageViewSize();
        isPreviewMode = true;
        LogUtils.d(TAG, "进入预览模式，预览图片路径：" + previewImagePath);
    }

    /**
     * 【新增公共函数】退出预览模式，恢复显示正式背景图片
     */
    public void exitPreviewMode() {
        if (isPreviewMode) {
            loadAndSetImageViewBackground();
            isPreviewMode = false;
            LogUtils.d(TAG, "退出预览模式，恢复正式背景");
        }
    }

    /**
     * 公共函数：供外部类调用，重新加载正式背景图片（刷新显示）
     */
    public void reloadBackgroundImage() {
        LogUtils.d(TAG, "外部调用重新加载背景图片");
        initBackgroundImagePath();
        loadAndSetImageViewBackground();
        // 若处于预览模式，退出预览
        if (isPreviewMode) {
            isPreviewMode = false;
        }
    }

    /**
     * 加载正式背景图片并设置到 ImageView
     */
    private void loadAndSetImageViewBackground() {
        if (backgroundSourceFilePath == null) {
            setDefaultImageViewBackground();
            return;
        }

        File backgroundFile = new File(backgroundSourceFilePath);
        if (!backgroundFile.exists() || !backgroundFile.isFile()) {
            LogUtils.e(TAG, "背景图片不存在：" + backgroundSourceFilePath);
            setDefaultImageViewBackground();
            return;
        }

        if (!calculateImageAspectRatio(backgroundFile)) {
            setDefaultImageViewBackground();
            return;
        }

        Bitmap bitmap = decodeBitmapWithCompress(backgroundFile, 1080, 1920);
        if (bitmap == null) {
            LogUtils.e(TAG, "图片加载失败，无法解析为 Bitmap");
            setDefaultImageViewBackground();
            return;
        }

        Drawable backgroundDrawable = new BitmapDrawable(mContext.getResources(), bitmap);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            ivBackground.setBackground(backgroundDrawable);
        } else {
            ivBackground.setBackgroundDrawable(backgroundDrawable);
        }

        adjustImageViewSize();
        LogUtils.d(TAG, "ImageView 背景加载成功，宽高比：" + imageAspectRatio);
    }

    /**
     * 计算图片宽高比（宽/高）
     */
    private boolean calculateImageAspectRatio(File file) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            int imageWidth = options.outWidth;
            int imageHeight = options.outHeight;

            if (imageWidth <= 0 || imageHeight <= 0) {
                LogUtils.e(TAG, "图片尺寸无效：宽=" + imageWidth + ", 高=" + imageHeight);
                return false;
            }

            imageAspectRatio = (float) imageWidth / imageHeight;
            return true;
        } catch (Exception e) {
            LogUtils.e(TAG, "计算图片宽高比失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 动态调整 ImageView 尺寸以匹配图片宽高比
     */
    private void adjustImageViewSize() {
        int parentWidth = getWidth();
        int parentHeight = getHeight();

        if (parentWidth == 0 || parentHeight == 0) {
            post(new Runnable() {
					@Override
					public void run() {
						adjustImageViewSize();
					}
				});
            return;
        }

        int imageViewWidth, imageViewHeight;
        if (imageAspectRatio >= 1.0f) { // 横图
            imageViewWidth = Math.min(parentWidth, (int) (parentHeight * imageAspectRatio));
            imageViewHeight = (int) (imageViewWidth / imageAspectRatio);
        } else { // 竖图
            imageViewHeight = Math.min(parentHeight, (int) (parentWidth / imageAspectRatio));
            imageViewWidth = (int) (imageViewHeight * imageAspectRatio);
        }

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ivBackground.getLayoutParams();
        layoutParams.width = imageViewWidth;
        layoutParams.height = imageViewHeight;
        ivBackground.setLayoutParams(layoutParams);
    }

    /**
     * 带压缩的 Bitmap 解码（避免 OOM）
     */
    private Bitmap decodeBitmapWithCompress(File file, int maxWidth, int maxHeight) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            int scaleX = options.outWidth / maxWidth;
            int scaleY = options.outHeight / maxHeight;
            int inSampleSize = Math.max(scaleX, scaleY);
            if (inSampleSize <= 0) {
                inSampleSize = 1;
            }

            options.inJustDecodeBounds = false;
            options.inSampleSize = inSampleSize;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        } catch (Exception e) {
            LogUtils.e(TAG, "图片压缩加载失败：" + e.getMessage());
            return null;
        }
    }

    /**
     * 设置默认背景（图片加载失败时兜底）
     */
    private void setDefaultImageViewBackground() {
        ivBackground.setBackgroundResource(R.drawable.default_background);
        imageAspectRatio = 1.0f;
        adjustImageViewSize();
        LogUtils.d(TAG, "已设置 ImageView 默认背景");
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        adjustImageViewSize();
    }

    /**
     * 对外提供：判断当前是否处于预览模式
     */
    public boolean isPreviewMode() {
        return isPreviewMode;
    }
}

