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

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.yd.oss.service.service.ExcelService;
import com.yd.oss.service.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Excel服务实现类
 */
@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {

    @Resource
    private OssService ossService;

    @Autowired
    private OSS ossClient; // 注入OSS客户端

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

    /**
     * 从OSS下载模板到临时文件
     * @param ossObjectKey
     * @return
     * @throws IOException
     */
    @Override
    public File downloadTemplateToTempFile(String ossObjectKey) throws IOException {
        // 创建临时文件
        Path tempPath = Files.createTempFile("template", ".xlsx");
        File tempFile = tempPath.toFile();
        tempFile.deleteOnExit(); // JVM退出时删除

        try (OSSObject ossObject = ossClient.getObject(defaultBucket, ossObjectKey);
             InputStream inputStream = ossObject.getObjectContent();
             FileOutputStream outputStream = new FileOutputStream(tempFile)) {

            // 复制流到文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return tempFile;
    }

    /**
     * 保存工作簿到临时文件
     * @param workbook
     * @return
     * @throws IOException
     */
    @Override
    public File saveWorkbookToTempFile(Workbook workbook) throws IOException {
        Path tempPath = Files.createTempFile("processed", ".xlsx");
        File tempFile = tempPath.toFile();
        tempFile.deleteOnExit();

        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            workbook.write(fos);
        }

        return tempFile;
    }

}
