package cc.winboll.studio.powerbell.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/11/21 18:55
 * @Describe
 * 图片下载工具类（指定目录保存：Pictures/PowerBell/BackgroundHistory）
 */
public class PictureUtils {
    private static final String TAG = "PictureUtils";
    private static final String ROOT_DIR = "PowerBell/BackgroundHistory"; // 自定义目录结构
    private static OkHttpClient sOkHttpClient;

    static {
        sOkHttpClient = new OkHttpClient();
    }

    /**
     * 下载网络图片到指定目录（外部存储/Pictures/PowerBell/BackgroundHistory）
     * @param context 上下文（用于通知相册刷新）
     * @param imgUrl 图片网络URL
     * @param callback 下载结果回调（成功/失败）
     */
    public static void downloadImageToAlbum(final Context context, final String imgUrl, final DownloadCallback callback) {
        // 检查参数合法性
        if (context == null) {
            if (callback != null) {
                callback.onFailure(new IllegalArgumentException("Context不能为空"));
            }
            return;
        }
        if (imgUrl == null || imgUrl.isEmpty()) {
            if (callback != null) {
                callback.onFailure(new IllegalArgumentException("图片URL为空"));
            }
            return;
        }

        startDownload(context, imgUrl, callback);
    }

    /**
     * 执行实际的下载逻辑
     */
    private static void startDownload(final Context context, final String imgUrl, final DownloadCallback callback) {
        Request request = new Request.Builder().url(imgUrl).build();
        sOkHttpClient.newCall(request).enqueue(new Callback() {
				@Override
				public void onResponse(Call call, Response response) throws IOException {
					if (!response.isSuccessful()) {
						if (callback != null) {
							callback.onFailure(new IOException("请求失败，响应码：" + response.code()));
						}
						return;
					}

					InputStream inputStream = null;
					FileOutputStream outputStream = null;
					try {
						inputStream = response.body().byteStream();
						// 1. 获取并创建指定保存目录（外部存储/Pictures/PowerBell/BackgroundHistory）
						File saveDir = getTargetSaveDir(context);
						if (!saveDir.exists()) {
							boolean isDirCreated = saveDir.mkdirs(); // 递归创建多级目录
							if (!isDirCreated) {
								if (callback != null) {
									callback.onFailure(new IOException("创建目录失败：" + saveDir.getAbsolutePath()));
								}
								return;
							}
						}

						// 2. 解析图片后缀
						String fileSuffix = getImageSuffix(imgUrl, response);
						// 3. 生成时间戳文件名
						String fileName = generateTimeFileName() + fileSuffix;
						// 4. 创建文件
						final File saveFile = new File(saveDir, fileName);

						// 5. 写入文件
						outputStream = new FileOutputStream(saveFile);
						byte[] buffer = new byte[1024 * 4];
						int len;
						while ((len = inputStream.read(buffer)) != -1) {
							outputStream.write(buffer, 0, len);
						}
						outputStream.flush();

						// 6. 通知相册刷新（使图片显示在系统相册中）
						notifyAlbumRefresh(context, saveFile);

						// 成功回调
						if (callback != null) {
							callback.onSuccess(saveFile.getAbsolutePath());
						}

					} catch (Exception e) {
						Log.e(TAG, "下载图片异常", e);
						if (callback != null) {
							callback.onFailure(e);
						}
					} finally {
						// 关闭资源
						if (inputStream != null) inputStream.close();
						if (outputStream != null) outputStream.close();
						if (response.body() != null) response.body().close();
					}
				}

				@Override
				public void onFailure(Call call, final IOException e) {
					Log.e(TAG, "下载图片失败", e);
					if (callback != null) {
						callback.onFailure(e);
					}
				}
			});
    }

    /**
     * 获取目标保存目录：外部存储/Pictures/PowerBell/BackgroundHistory
     */
    private static File getTargetSaveDir(Context context) {
        // 优先使用公共Pictures目录（兼容多数设备）
        File publicPicturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (publicPicturesDir.exists()) {
            return new File(publicPicturesDir, ROOT_DIR);
        }
        // 备选：应用私有Pictures目录（若公共目录不可用）
        File appPicturesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (appPicturesDir != null) {
            return new File(appPicturesDir, ROOT_DIR);
        }
        // 极端情况：外部存储根目录
        return new File(Environment.getExternalStorageDirectory(), ROOT_DIR);
    }

    /**
     * 解析图片后缀名
     */
    private static String getImageSuffix(String imgUrl, Response response) {
        // 优先从URL解析
        if (imgUrl.lastIndexOf('.') != -1) {
            String suffix = imgUrl.substring(imgUrl.lastIndexOf('.'));
            if (suffix.length() <= 5 && (suffix.contains("png") || suffix.contains("jpg") || suffix.contains("jpeg") || suffix.contains("gif"))) {
                return suffix.toLowerCase(Locale.getDefault());
            }
        }
        // 从响应头解析
        String contentType = response.header("Content-Type");
        if (contentType != null) {
            if (contentType.contains("png")) return ".png";
            if (contentType.contains("jpeg") || contentType.contains("jpg")) return ".jpg";
            if (contentType.contains("gif")) return ".gif";
        }
        return ".jpg"; // 默认后缀
    }

    /**
     * 生成时间戳文件名
     */
    private static String generateTimeFileName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        return sdf.format(new Date());
    }

    /**
     * 通知相册刷新
     */
    private static void notifyAlbumRefresh(Context context, File file) {
        try {
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {
            Log.e(TAG, "通知相册刷新失败", e);
        }
    }

    /**
     * 下载结果回调接口
     */
    public interface DownloadCallback {
        void onSuccess(String savePath); // 下载成功（子线程回调）
        void onFailure(Exception e);    // 下载失败（子线程回调）
    }
}

