package com.yd.oss.service.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.yd.oss.service.dao.ProductFileMapper;
import com.yd.oss.service.model.ProductFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private ProductFileMapper productFileMapper;

    @Autowired
    private String defaultBucket; // 从配置注入默认存储桶

    @Autowired
    private String defaultEndpoint; // 注入默认服务端点

    /**
     * 批量处理URL上传
     */
    public void batchProcessUrls() {
        List<ProductFile> productFileList = productFileMapper.selectList(null);
        for (ProductFile productFile : productFileList) {
            try {

                // 处理单个URL
                processSingleUrl(productFile);

            } catch (Exception e) {
                log.error("处理URL失败: {}, 错误: {}", productFile.getOldFileUrl(), e.getMessage());
            }
        }
    }

    /**
     * 处理单个URL
     */
    private void processSingleUrl(ProductFile productFile) throws Exception {
        // 1. 下载文件
        byte[] fileContent = downloadFile(productFile.getOldFileUrl());

        // 2. 生成OSS文件名（使用原始URL路径）
        String ossFileName = generateOssFileName(productFile.getOldFileUrl(), "");

        // 3. 上传到阿里云OSS
        String ossUrl = uploadToAliOss(fileContent, ossFileName);

        // 4. 更新数据库
        productFile.setNewFileUrl(ossUrl);
        productFileMapper.updateById(productFile);

        log.info("文件上传成功: {} -> {}", productFile.getFileName(), ossUrl);
    }

    /**
     * 下载文件
     */
    private byte[] downloadFile(String fileUrl) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(fileUrl);

        try (CloseableHttpResponse response = httpClient.execute(httpGet);
             InputStream inputStream = response.getEntity().getContent()) {

            return IOUtils.toByteArray(inputStream);
        } finally {
            httpClient.close();
        }
    }

    /**
     * 生成OSS文件名 - 保留原始URL路径结构
     */
    private String generateOssFileName(String originalUrl, String originalFileName) {
        try {
            // 解析原始URL，提取路径部分
            URL url = new URL(originalUrl);
            String path = url.getPath(); // 得到类似：/wslucky/product/2024/12/27/9ba093ee-be9a-4291-aa86-d6a1995e16f9.pdf

            // 移除开头的斜杠（如果有）
            if (path.startsWith("/")) {
                path = path.substring(1);
            }

            // 如果路径为空，使用备选方案
            if (path.isEmpty()) {
                return generateFallbackFileName(originalFileName);
            }

            return path;

        } catch (Exception e) {
            log.warn("解析URL路径失败: {}, 使用备选方案", originalUrl, e);
            return generateFallbackFileName(originalFileName);
        }
    }

    /**
     * 备选文件名生成方案
     */
    private String generateFallbackFileName(String originalFileName) {
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String timestamp = String.valueOf(System.currentTimeMillis());
        String randomStr = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

        return "insurance/" + timestamp + "_" + randomStr + fileExtension;
    }

    /**
     * 上传到阿里云OSS
     */
    private String uploadToAliOss(byte[] fileContent, String ossFileName) {
        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(defaultBucket, ossFileName,
                new ByteArrayInputStream(fileContent));

        // 上传文件
        ossClient.putObject(putObjectRequest);

        // 生成访问URL
        return String.format("https://%s.%s/%s", defaultBucket,
                defaultEndpoint, ossFileName);
    }
}