package com.qmth.sop.common.util;

import com.qmth.sop.common.contant.SystemConstant;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description:
 * @Author: CaoZixuan
 * @Date:
 */
public class FileUtil {
    private final static Logger log = LoggerFactory.getLogger(FileUtil.class);

    public static String fileToBase64(File imgFile) {
        String fileName=imgFile.getName();
        String suff=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        InputStream is = null;
        byte[] base64Byte;
        try {
            base64Byte = new byte[0];
            byte[] imgByte;
            is = new FileInputStream(imgFile);
            imgByte = IOUtils.toByteArray(is);
            base64Byte = Base64.encodeBase64(imgByte);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return new String(base64Byte);
    }

    public static void deleteFile(String path) {
        File file = new File(path);
        deleteFile(file);
    }

    public static void deleteFile(File file) {
        if (file.isFile() && file.exists()) {
            file.delete();
        }
    }

    public static void outputFile(HttpServletResponse response, File file, String fileName) {
        try {
            if (!file.exists()) {
                response.sendError(404, "File not found!");
            }

            BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
            String fName = URLEncoder.encode(fileName, SystemConstant.CHARSET_NAME);

            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fName);
            IOUtils.copy(br, response.getOutputStream());
            br.close();
//            outStream.close();
        } catch (IOException e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
    }
}
