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.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import cc.winboll.studio.powerbell.App;
import cc.winboll.studio.powerbell.models.BackgroundBean;
import java.io.File;

/**
 * 基于Java7的BackgroundView（LinearLayout+ImageView，保持原图比例居中平铺）
 * 核心：ImageView保持原图比例，在LinearLayout中居中平铺，无拉伸、无裁剪
 */
public class BackgroundView extends RelativeLayout {

    public static final String TAG = "BackgroundView";
    // 新增：记录当前已缓存的图片路径
    private String mCurrentCachedPath = "";

    private Context mContext;
    private LinearLayout mLlContainer; // 主容器LinearLayout
    private ImageView mIvBackground;   // 图片显示控件
    private float mImageAspectRatio = 1.0f; // 原图宽高比（宽/高）

    // ====================================== 构造器（Java7兼容） ======================================
    public BackgroundView(Context context) {
        super(context);
        LogUtils.d(TAG, "=== BackgroundView 构造器1 启动 ===");
        this.mContext = context;
        initView();
    }

    public BackgroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LogUtils.d(TAG, "=== BackgroundView 构造器2 启动 ===");
        this.mContext = context;
        initView();
    }

    public BackgroundView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LogUtils.d(TAG, "=== BackgroundView 构造器3 启动 ===");
        this.mContext = context;
        initView();
    }

    // ====================================== 初始化 ======================================
    private void initView() {
        LogUtils.d(TAG, "=== initView 启动 ===");
        // 1. 配置当前控件：全屏+透明
        setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        // 2. 初始化主容器LinearLayout
        initLinearLayout();

        // 3. 初始化ImageView
        initImageView();

        // 初始设置透明背景
        setDefaultTransparentBackground();

        LogUtils.d(TAG, "=== initView 完成 ===");
    }

    private void initLinearLayout() {
        LogUtils.d(TAG, "=== initLinearLayout 启动 ===");
        mLlContainer = new LinearLayout(mContext);
        // 配置LinearLayout：全屏+垂直方向+居中
        LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.MATCH_PARENT,
			LinearLayout.LayoutParams.MATCH_PARENT
        );
        mLlContainer.setLayoutParams(llParams);
        mLlContainer.setOrientation(LinearLayout.VERTICAL);
        mLlContainer.setGravity(android.view.Gravity.CENTER); // 子View居中
        mLlContainer.setBackgroundColor(0x00000000);
        this.addView(mLlContainer);
        LogUtils.d(TAG, "=== initLinearLayout 完成 ===");
    }

    private void initImageView() {
        LogUtils.d(TAG, "=== initImageView 启动 ===");
        mIvBackground = new ImageView(mContext);
        // 配置ImageView：wrap_content+居中+透明背景
        LinearLayout.LayoutParams ivParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT
        );
        mIvBackground.setLayoutParams(ivParams);
        mIvBackground.setScaleType(ScaleType.FIT_CENTER); // 保持比例+居中平铺
        mIvBackground.setBackgroundColor(0x00000000);
        mLlContainer.addView(mIvBackground);
        LogUtils.d(TAG, "=== initImageView 完成 ===");
    }

    public void loadBackgroundBean(BackgroundBean bean) {
        loadBackgroundBean(bean, false);
    }

	public void loadBackgroundBean(BackgroundBean bean, boolean isRefresh) {
        if (!bean.isUseBackgroundFile()) {
            setDefaultTransparentBackground();
            return;
        }
        String targetPath = bean.isUseBackgroundScaledCompressFile()
			? bean.getBackgroundScaledCompressFilePath()
			: bean.getBackgroundFilePath();

		if (!(new File(targetPath).exists())) {
			LogUtils.d(TAG, String.format("视图控件图片不存在：%s", targetPath));
			return;
		}

		// 调用带路径判断的loadImage方法
		if (isRefresh) {
			App._mBitmapCacheUtils.removeCachedBitmap(targetPath);
			App._mBitmapCacheUtils.cacheBitmap(targetPath);
		}
		loadImage(targetPath);
    }

    // ====================================== 对外方法 ======================================
    /**
     * 改造后：添加路径判断，路径更新时同步更新缓存；缓存Bitmap为null时提示并加载透明背景
     * @param imagePath 图片绝对路径
     */
    public void loadImage(String imagePath) {
        LogUtils.d(TAG, "=== loadImage 启动，路径：" + imagePath + " ===");
        if (TextUtils.isEmpty(imagePath)) {
            setDefaultTransparentBackground();
            return;
        }

        File imageFile = new File(imagePath);
        if (!imageFile.exists() || !imageFile.isFile()) {
            LogUtils.e(TAG, "图片文件无效");
            setDefaultTransparentBackground();
            return;
        }

        mIvBackground.setVisibility(View.GONE);

        // ======================== 新增：路径判断逻辑 ========================
        // 1. 路径未变化：直接使用缓存
        if (imagePath.equals(mCurrentCachedPath)) {
			Bitmap cachedBitmap = App._mBitmapCacheUtils.getCachedBitmap(imagePath);
			// 核心修改：判断缓存Bitmap是否为null
			if (cachedBitmap != null && !cachedBitmap.isRecycled()) {
				LogUtils.d(TAG, "loadImage: 路径未变，使用缓存 Bitmap");
				mImageAspectRatio = (float) cachedBitmap.getWidth() / cachedBitmap.getHeight();
				mIvBackground.setImageBitmap(cachedBitmap);
				adjustImageViewSize();
				mIvBackground.setVisibility(View.VISIBLE);
				return;
			} else {
                // 缓存Bitmap为空或已回收，提示并加载透明背景
                LogUtils.e(TAG, "loadImage: 全局位图缓存为空或已回收 - " + imagePath);
                ToastUtils.show("全局位图缓存为空，无法加载图片");
                setDefaultTransparentBackground();
                return;
            }
        }

        // 2. 路径已更新：移除旧缓存，加载新图片并更新缓存
        if (!TextUtils.isEmpty(mCurrentCachedPath)) {
            App._mBitmapCacheUtils.removeCachedBitmap(mCurrentCachedPath);
            LogUtils.d(TAG, "loadImage: 路径已更新，移除旧缓存 - " + mCurrentCachedPath);
        }
        // ======================== 路径判断逻辑结束 ========================

        // 无缓存/路径更新：走原有逻辑加载图片
        if (!calculateImageAspectRatio(imageFile)) {
            setDefaultTransparentBackground();
            return;
        }

        Bitmap bitmap = decodeBitmapWithCompress(imageFile, 1080, 1920);
        if (bitmap == null) {
            LogUtils.e(TAG, "loadImage: 图片解码失败");
            ToastUtils.show("图片解码失败，无法加载");
            setDefaultTransparentBackground();
            return;
        }

        // 缓存新图片，并更新当前缓存路径记录
        App._mBitmapCacheUtils.cacheBitmap(imagePath);
        mCurrentCachedPath = imagePath;
        LogUtils.d(TAG, "loadImage: 加载新图片并更新缓存 - " + imagePath);

        mIvBackground.setImageDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
        adjustImageViewSize();
        mIvBackground.setVisibility(View.VISIBLE);
        LogUtils.d(TAG, "=== loadImage 完成 ===");
    }

    // ====================================== 内部工具方法 ======================================
    private boolean calculateImageAspectRatio(File file) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            int width = options.outWidth;
            int height = options.outHeight;
            if (width <= 0 || height <= 0) {
                LogUtils.e(TAG, "图片尺寸无效");
                return false;
            }

            mImageAspectRatio = (float) width / height;
            LogUtils.d(TAG, "原图比例：" + mImageAspectRatio);
            return true;
        } catch (Exception e) {
            LogUtils.e(TAG, "计算比例失败：" + e.getMessage());
            return false;
        }
    }

    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 adjustImageViewSize() {
        if (mLlContainer == null || mIvBackground == null) {
            return;
        }

        int llWidth = mLlContainer.getWidth();
        int llHeight = mLlContainer.getHeight();

        if (llWidth != 0 && llHeight != 0) {
            int ivWidth, ivHeight;
            if (mImageAspectRatio >= 1.0f) {
                ivWidth = Math.min((int) (llHeight * mImageAspectRatio), llWidth);
                ivHeight = (int) (ivWidth / mImageAspectRatio);
            } else {
                ivHeight = Math.min((int) (llWidth / mImageAspectRatio), llHeight);
                ivWidth = (int) (ivHeight * mImageAspectRatio);
            }

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mIvBackground.getLayoutParams();
            params.width = ivWidth;
            params.height = ivHeight;
            mIvBackground.setLayoutParams(params);
            mIvBackground.setScaleType(ScaleType.FIT_CENTER);
            mIvBackground.setVisibility(View.VISIBLE);
        }
    }

    private void setDefaultTransparentBackground() {
        mIvBackground.setImageBitmap(null);
        mIvBackground.setBackgroundColor(0x00000000);
        mImageAspectRatio = 1.0f;
        // 清空缓存路径记录
        mCurrentCachedPath = "";
        mIvBackground.setVisibility(View.GONE);
    }

    // ====================================== 重写方法 ======================================
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        adjustImageViewSize(); // 尺寸变化时重新调整
    }
}

