package org.wfc.file.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.wfc.file.utils.FileUploadUtils;

/**
 * 本地文件存储
 * 
 * @author wfc
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    @Value("${file.gateway}")
    public String gateway;

    @Value("${file.pathPrefix}")
    public String pathPrefix;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return FileUploadResult 包含本地和网关访问地址
     * @throws Exception
     */
    @Override
    public FileUploadResult uploadFile(MultipartFile file) throws Exception {
        String name = FileUploadUtils.upload(localFilePath, file);
        String url = localFilePrefix + name;
        String localUrl = domain + localFilePrefix + name;
        String gatewayUrl = gateway + pathPrefix + localFilePrefix + name;
        return new FileUploadResult(url, localUrl, gatewayUrl);
    }   

    public static class FileUploadResult {
        private final String url;
        private final String localUrl;
        private final String gatewayUrl;

        public FileUploadResult(String url, String localUrl, String gatewayUrl) {
            this.url = url;
            this.localUrl = localUrl;
            this.gatewayUrl = gatewayUrl;
        }

        public String getUrl() {
            return url;
        }

        public String getLocalUrl() {
            return localUrl;
        }

        public String getGatewayUrl() {
            return gatewayUrl;
        }
    }
}
