package org.shop.crop.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class OssService {

    private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com"; // 你 bucket 的区域
    private static final String ACCESS_KEY_ID = "LTAI6do39W9jINpe";
    private static final String ACCESS_KEY_SECRET = "XLhp5w4WnRcqji204GYOm7hZsoXSB6";
    private static final String BUCKET_NAME = "ct-upimg";
    private static final String URL = "https://ct-upimg.yx090.com";
    private static final String PREFIX = "ju8hn6/shop";

    public OSS getClient() {
        return new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }

    /**
     * 上传文件到 OSS
     *
     * @param localFile 本地临时文件
     * @return 可访问的 URL
     */
    public String upload(File localFile) {
        String objectName = generateOssObjectName(localFile.getPath());
        log.info("文件名称{}", objectName);
        return upload(localFile, objectName);
    }

    /**
     * 上传文件到 OSS
     *
     * @param localFile  本地临时文件
     * @param objectName OSS 上的文件路径，如 media/2025/09/photo.jpg
     * @return 可访问的 URL
     */
    public String upload(File localFile, String objectName) {
        OSS ossClient = null;
        try {
            ossClient = getClient();

            // 设置元数据（主要是 Content-Type）
            ObjectMetadata metadata = new ObjectMetadata();
            String contentType = getContentType(objectName);
            metadata.setContentType(contentType);

            // 执行上传
            ossClient.putObject(BUCKET_NAME, objectName, localFile, metadata);
            OSSObject ossObject = ossClient.getObject(BUCKET_NAME, objectName);
            System.out.println("文件存在，大小为: " + ossObject.getObjectMetadata().getContentLength());
            // 生成可访问的 URL
            // 格式：https://bucket.oss-cn-hangzhou.aliyuncs.com/objectName
            String url = String.format("%s/%s", URL, objectName);

            return url;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 生成 OSS 文件路径：年/月/日/40位随机字符串.扩展名
     *
     * @param originalFileName 原始文件名，如 avatar.jpg
     * @return 路径字符串，如 2025/09/25/a1b2c3d4e5f67890123456789012345678901234.jpg
     */
    public static String generateOssObjectName(String originalFileName) {
        // 1. 获取当前日期：年/月/日
        LocalDate now = LocalDate.now();
        String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        // 2. 提取文件扩展名
        String extension = "";
        int lastDotIndex = originalFileName.lastIndexOf('.');
        if (lastDotIndex > 0) {
            extension = originalFileName.substring(lastDotIndex); // 包含 .
        } else {
            extension = ".bin"; // 无扩展名时默认
        }

        // 3. 生成 40 位随机字符串（a-z,0-9）
        String randomString = generateRandomString(40);

        // 4. 拼接路径
        return PREFIX + "/" + datePath + "/" + randomString + extension;
    }

    /**
     * 生成指定长度的随机字符串（十六进制风格）
     */
    private static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder();
        while (sb.length() < length) {
            sb.append(java.util.UUID.randomUUID().toString().replace("-", ""));
        }
        return sb.substring(0, length);
    }


    /**
     * 根据文件名后缀推断 Content-Type
     */
    private String getContentType(String fileName) {
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".gif")) {
            return "image/gif";
        } else if (fileName.endsWith(".webp")) {
            return "image/webp";
        } else if (fileName.endsWith(".mp4")) {
            return "video/mp4";
        } else if (fileName.endsWith(".avi")) {
            return "video/avi";
        } else if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        } else if (fileName.endsWith(".doc")) {
            return "application/msword";
        } else if (fileName.endsWith(".docx")) {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (fileName.endsWith(".xlsx")) {
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        } else {
            return "application/octet-stream"; // 默认二进制流
        }
    }
}