package com.skr.mdm.service.impl;

import com.skr.mdm.manager.oss.MinIoManager;
import com.skr.mdm.service.DownLoadFileService;
import com.skr.mdm.util.FileDownloadUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Properties;

@Service
public class DownLoadFileServiceImpl implements DownLoadFileService {

    @Autowired
    private MinIoManager minIoManager;

    @Override
    public void downloadFile(String fileUrl, HttpServletResponse response) throws Exception {
        Properties properties = System.getProperties();
        String osName = properties.getProperty("os.name");
        String path = properties.getProperty("user.dir");
        if (osName.toLowerCase().contains("win")) {
            path += "\\oss\\";
        } else {
            path += "/oss/";
        }
        String finalPath = path;
        File fileDir = new File(finalPath);
        if (!fileDir.isDirectory() && !fileDir.exists()) {
            fileDir.mkdirs();
        }
        fileUrl = StringUtils.substringAfter(fileUrl, "oss");
//        fileUrl = StringUtils.substringBefore(fileUrl, "?");
        String[] split = fileUrl.split("/");
        String fileName = split[split.length - 1];
        finalPath = finalPath + fileName;
        minIoManager.downLoadMinIoObject(fileUrl, finalPath);
        File ossFile = new File(finalPath);
        FileDownloadUtil.download(response, ossFile, fileName);
        // 删除本地临时文件
        if (fileDir.exists()) {
            File[] files = fileDir.listFiles();
            for (File file : files) {
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
            }
            if (fileDir.isDirectory()) {
                fileDir.delete();
            }
        }
    }
}
