package com.org.utils.upload;

import cn.hutool.core.util.IdUtil;
import com.org.utils.HttpServletUtil;
import com.org.utils.StringUtils;
import com.org.utils.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Slf4j
@Component
public class CommonUtil {

    public static String downloadPath;

    @Value("${oss.downloadPath}")
    public void setDownloadPath(String downloadPath){
        this.downloadPath = downloadPath;
        if(!this.downloadPath.endsWith(File.separator)) this.downloadPath += File.separator;
    }

    public static String getDownloadPath(){
        log.info("CommonUtil - getDownloadPath downloadPath:{}", downloadPath);
        return downloadPath;
    }

    /**
     * 通用文件下载
     *
     * @param fileName
     * @param delete
     */
    public static void download(String fileName, boolean delete){
        log.info("commonUtil - download fileName:{}", fileName);
        log.info("commonUtil - download delete:{}", delete);

        try{
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = downloadPath + fileName;

            HttpServletResponse response = HttpServletUtil.getResponse();

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());

            if (delete) FileUtils.deleteFile(filePath);
        } catch (Exception e) {
            log.error("下载文件失败 {}", e);
        }
    }

    /**
     * 通用下载文件保存
     *
     * @param data
     * @param fileName
     * @return
     */
    public static String saveFile(byte[] data, String fileName) {
        log.info("commonUtil - saveFile fileName:{}", fileName);

        if (data.length < 3 ) throw new CustomException("上传文件为空");

        try {
            fileName = IdUtil.simpleUUID() + "-" + fileName;
            String dateDir = fileName.split("/")[1];

            //文件夹
            File dirFile = new File(downloadPath);
            if (!dirFile.exists())  dirFile.mkdirs();

            File file = new File(downloadPath + fileName);
            if (!file.exists()) file.createNewFile();

            //打开输入流
            FileImageOutputStream imageOutput = new FileImageOutputStream(file);
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
        } catch (Exception e) {
            log.error("{}", e);
            throw new CustomException("上传文件失败", e);
        }

        return fileName;
    }


}
