package com.zhentao.util;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * 头像上传工具类
 */
@Slf4j
@Component
public class AvatarUploadUtil {
    
    @Autowired
    private MinioClient minioClient;
    
    @Autowired
    private com.zhentao.config.MinioConfig minioConfig;
    
    /**
     * 初始化：确保桶存在并设置为公共访问
     */
    @PostConstruct
    public void init() {
        try {
            String bucketName = minioConfig.getBucketName();
            
            // 检查桶是否存在
            boolean exists = minioClient.bucketExists(
                BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build()
            );
            
            if (!exists) {
                log.info("MinIO桶不存在，开始创建: {}", bucketName);
                
                // 创建桶
                minioClient.makeBucket(
                    MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build()
                );
                
                log.info("✅ MinIO桶创建成功: {}", bucketName);
                
                // 设置桶为公共访问（允许匿名读取）
                String policy = String.format(
                    "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::%s/*\"]}]}",
                    bucketName
                );
                
                minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                        .bucket(bucketName)
                        .config(policy)
                        .build()
                );
                
                log.info("✅ MinIO桶权限设置成功（公共读取）: {}", bucketName);
            } else {
                log.info("MinIO桶已存在: {}", bucketName);
            }
            
        } catch (Exception e) {
            log.error("❌ 初始化MinIO失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 上传base64格式的头像到MinIO
     * 
     * @param base64Avatar base64格式的头像字符串（包含data:image/jpeg;base64,前缀）
     * @param userId 用户ID
     * @return MinIO中的对象URL（永久有效，不使用预签名）
     */
    public String uploadBase64Avatar(String base64Avatar, Integer userId) {
        try {
            // 1. 解析base64字符串
            String base64Data;
            String contentType = "image/jpeg"; // 默认类型
            
            if (base64Avatar.contains(",")) {
                // 提取content type和base64数据
                String[] parts = base64Avatar.split(",");
                String header = parts[0]; // data:image/jpeg;base64
                base64Data = parts[1];
                
                // 提取content type
                if (header.contains("image/png")) {
                    contentType = "image/png";
                } else if (header.contains("image/gif")) {
                    contentType = "image/gif";
                } else if (header.contains("image/webp")) {
                    contentType = "image/webp";
                }
            } else {
                base64Data = base64Avatar;
            }
            
            // 2. 解码base64
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            
            // 3. 生成唯一文件名
            String fileExtension = getFileExtension(contentType);
            String fileName = String.format("user_%d_%s%s", 
                userId, 
                UUID.randomUUID().toString().replace("-", ""), 
                fileExtension);
            
            // 4. 构建对象路径
            String objectName = minioConfig.getUserAvatarFolder() + "/" + fileName;
            
            log.info("开始上传头像到MinIO: userId={}, objectName={}, size={}bytes", 
                userId, objectName, imageBytes.length);
            
            // 5. 上传到MinIO
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .stream(new ByteArrayInputStream(imageBytes), imageBytes.length, -1)
                    .contentType(contentType)
                    .build()
            );
            
            // 6. 生成公共访问URL（不使用预签名，永久有效）
            String avatarUrl = String.format("%s/%s/%s", 
                minioConfig.getEndpoint(),
                minioConfig.getBucketName(),
                objectName);
            
            log.info("✅ 头像上传成功: userId={}, url={}", userId, avatarUrl);
            return avatarUrl;
            
        } catch (Exception e) {
            log.error("❌ 上传头像失败: userId={}, error={}", userId, e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 根据content type获取文件扩展名
     */
    private String getFileExtension(String contentType) {
        switch (contentType) {
            case "image/png":
                return ".png";
            case "image/gif":
                return ".gif";
            case "image/webp":
                return ".webp";
            case "image/jpeg":
            default:
                return ".jpg";
        }
    }
    
    /**
     * 获取默认头像URL
     */
    public String getDefaultAvatarUrl() {
        return "https://via.placeholder.com/200x200.png?text=默认头像";
    }
}