package yem.base.common.utils;

import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * 文件处理工具类
 *
 * @author longh
 * @description:
 * @date 2021年10月18日 下午2:03:50
 */
public class FileUtil {
    private static final String[] SPECIAL_SYMBOLS = new String[]{"%", "=", "+", "&"};//特殊字符
    private static boolean isLinux = isOSLinux();//是否Linux操作系统
    protected String realePath;//存储地址
    private String monthStr = getMonthStr();//时间字符串，yyyyMM掩码

    /**
     * 实例化工具类
     *
     * @param formId 单据标识/应用标识
     */
    public FileUtil(String formId) {
        String uuid = createUUID();
        if (isLinux) {
            realePath = String.format("/kingdee/tpwm/files/%s/%s/%s/", monthStr, formId, uuid);
        } else {
            realePath = String.format("C:/kingdee/tpwm/files/%s/%s/%s/", monthStr, formId, uuid);
        }
    }

    public static boolean isLinux() {
        return isLinux;
    }

    /**
     * create new File
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static boolean createNewFile(File file) throws IOException {
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        boolean created = file.createNewFile();
        if (isLinux) {
            file.setExecutable(true);//设置可执行权限
            file.setReadable(true);//设置可读权限
            file.setWritable(true);//设置可写权限
        }
        return created;
    }

    /**
     * 下载文件到指定位置
     *
     * @param file
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    public static String downloadFile(File file, String downloadUrl) throws IOException {
        URL url = new URL(downloadUrl);
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        httpURLConnection.setConnectTimeout(1000 * 5);
//        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.connect();

        int fileLength = httpURLConnection.getContentLength();
        System.out.println("您要下载的文件大小为:" + fileLength / 1024 + "K");

        createNewFile(file);
        InputStream inputStream = httpURLConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        BufferedInputStream bin = new BufferedInputStream(inputStream);
        int size = 0;
        byte[] buf = new byte[1024];
        while ((size = bin.read(buf)) != -1) {
            fileOutputStream.write(buf, 0, size);
        }
        bin.close();
        fileOutputStream.close();

        return file.getPath();
    }

    /**
     * 判断服务器操作系统是否为Linux
     *
     * @return
     */
    private static boolean isOSLinux() {
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 替换特殊字符
     *
     * @param str
     * @return
     */
    public static String replaceSpeSymbol(String str) {
        for (int i = 0; i < SPECIAL_SYMBOLS.length; ++i) {
            if (str.contains(SPECIAL_SYMBOLS[i])) {
                str = str.replace(SPECIAL_SYMBOLS[i], "_");
            }
        }

        return str;
    }

    /**
     * 获取UUID
     *
     * @return
     */
    public static String createUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取当月时间字符串	yyyyMM掩码
     *
     * @return
     */
    public static String getMonthStr() {
        return new SimpleDateFormat("yyyyMM").format(new Date());
    }

    /**
     * new File
     *
     * @param fileName
     * @return
     */
    public File newFile(String fileName) {
        return new File(realePath + replaceSpeSymbol(fileName));
    }

    /**
     * create new File
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public File createNewFile(String fileName) throws IOException {
        File file = newFile(fileName);
        createNewFile(file);
        return file;
    }

    /**
     * 下载文件到指定位置
     *
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    public String downloadFile(String downloadUrl) throws IOException {
        String fileName = FilenameUtils.getName(downloadUrl);
        return downloadFile(fileName, downloadUrl);
    }

    /**
     * 下载文件到指定位置
     *
     * @param fileName
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    public String downloadFile(String fileName, String downloadUrl) throws IOException {
        return downloadFile(newFile(fileName), downloadUrl);
    }

}
