package com.erp.file.service.storage;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 本地存储策略
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LocalStorageStrategy implements StorageStrategy {
    
    @Value("${file.storage.local.base-path:/var/erp/uploads}")
    private String basePath;
    
    @Value("${file.storage.local.base-url:http://localhost:8080/files}")
    private String baseUrl;
    
    private Path rootLocation;
    
    @PostConstruct
    @Override
    public void init() {
        this.rootLocation = Paths.get(basePath);
        try {
            Files.createDirectories(rootLocation);
            log.info("本地存储初始化成功，路径: {}", rootLocation.toAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException("无法创建本地存储目录", e);
        }
    }
    
    @Override
    public String upload(MultipartFile file, String path, String storageName) {
        try {
            if (file.isEmpty()) {
                throw new RuntimeException("上传文件不能为空");
            }
            
            Path directory = rootLocation.resolve(path);
            Files.createDirectories(directory);
            
            Path targetPath = directory.resolve(storageName);
            
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
            }
            
            log.info("文件上传成功: {}", targetPath);
            return getUrl(path + "/" + storageName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
    
    @Override
    public InputStream download(String path) {
        try {
            Path filePath = rootLocation.resolve(path);
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() && resource.isReadable()) {
                return resource.getInputStream();
            } else {
                throw new RuntimeException("文件不存在或无法读取: " + path);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("文件路径错误", e);
        } catch (IOException e) {
            throw new RuntimeException("读取文件失败", e);
        }
    }
    
    @Override
    public void delete(String path) {
        try {
            Path filePath = rootLocation.resolve(path);
            Files.deleteIfExists(filePath);
            log.info("文件删除成功: {}", filePath);
        } catch (IOException e) {
            log.error("删除文件失败: {}", path, e);
            throw new RuntimeException("删除文件失败", e);
        }
    }
    
    @Override
    public boolean exists(String path) {
        Path filePath = rootLocation.resolve(path);
        return Files.exists(filePath);
    }
    
    @Override
    public String getUrl(String path) {
        return baseUrl + "/" + path;
    }
    
    @Override
    public String getFullPath(String path) {
        return rootLocation.resolve(path).toString();
    }
    
    @Override
    public String getType() {
        return "local";
    }
}
