package com.microservices.wiki.refactoring.utils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName FileUtils
 * Description 文件工具类
 *
 * @author ZengWei
 * Date 2021/3/31
 */
@Component
public class FileUtils {
    // 文件在服务器端保存的主目录
    @Value("${FILES.BASEPATHFILE}")
    private String basePath;

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * @author ZengWei
     * Description 生成保存文件名称
     * Date 2021/3/31
     * @param oldName
     * @return java.lang.String
     **/
    public String getNewFilePathAndName(String oldName) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");
        StringBuilder newPathAndName = new StringBuilder();
        newPathAndName.append(basePath);
        newPathAndName.append(simpleDateFormat.format(new Date()));
        newPathAndName.append("/");
        newPathAndName.append(IDUtils.getFileName());
        newPathAndName.append(oldName.lastIndexOf(".") > -1 ? oldName.substring(oldName.lastIndexOf(".")) : "");
        return newPathAndName.toString();
    }

    /**
     * @author ZengWei
     * Description 创建文件
     * Date 2021/3/31
     * @param file
     * @return boolean
     **/
    public boolean createFile(File file) {
        if(!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                logger.info("创建目录失败");
                return false;
            }
        }
        try {
            if (!file.createNewFile()) {
                logger.info("创建文件失败");
                return false;
            }
        } catch (IOException e) {
            logger.info(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * @author ZengWei
     * Description 保存上传文件
     * Date 2021/3/31
     * @param file
     * @return java.lang.String
     **/
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            logger.info("上传的文件为空");
            return "";
        }

        String filePathAndName = this.getNewFilePathAndName(file.getOriginalFilename());

        File dest = new File(filePathAndName);

        if (!this.createFile(dest)) {
            return "";
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            logger.info("保存文件失败");
            logger.info(e.getMessage());
            return "";
        }

        return filePathAndName;
    }

    /**
     * @author ZengWei
     * Description 下去载文件
     * Date 2021/4/7
     * @param response
     * @param filePath
     * @param fileName
     * @return void
     **/
    public void downLoadFile(HttpServletResponse response, String filePath, String fileName) throws IOException {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new FileInputStream(new File(filePath));
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }

    /**
     * @author ZengWei
     * Description 获取文件编码
     * Date 2021/4/7
     * @param file
     * @return java.lang.String
     **/
    public String codeString(File file) throws Exception {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file));
        int p = (bin.read() << 8) + bin.read();
        bin.close();
        String code = null;

        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }

        return code;
    }

    public void writeStringToFile(String s, String fileName, String path ){
        try {
            Path directory = Paths.get(path);
            Files.createDirectories(directory); // 创建目录，如果目录已存在则清空
            Path filePath = directory.resolve(fileName);
            Files.write(filePath, s.getBytes());
        } catch (IOException iox) {
            iox.printStackTrace();
        }
    }

}
