package com.cslg.ppa.common.utils;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.cslg.ppa.PpaApplication;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class FileUtils {

    public static final String FILE_SEPARATOR = System.getProperty("file.separator");
    public static final String COMMON_FILE = "file";
    public static final String BACKUP_FILE = "backup";

    public static String getStaticPath(String fileName) {
        //ApplicationHome类 返回target目录层级
        ApplicationHome ah = new ApplicationHome(PpaApplication.class);
        //获取 applicationHome 内的路径 ...\target\classes 到这一层级下
        File file = ah.getSource();
        //获取 file的parentFile 即最后一级之前的所有层级路径(包括盘符) 这里能获得到的最终层级为  ...\target 后续用FILE_SEPARATOR(系统路径分割通配符 即 "\") 以及fileName拼接生成存放文件的目录层级 即为根目录 root
        String rootPath = null;

        if (fileName != null && !fileName.equals("")) {
            rootPath = file.getParentFile().toString() + FILE_SEPARATOR + fileName;
        } else {
            rootPath = file.getParentFile().toString();
        }
        //根据上方生成的根目录路径 生成对应文件夹 没有就新建
        File root = new File(rootPath);
        if (!root.exists()) {
            root.mkdir();
        }
        //返回的最终形式为 盘符:\项目层级\target\file
        return rootPath;
    }

    public String analysisJsonFile() {
        ApplicationHome ah = new ApplicationHome(BackupUtils.class);
        File file = ah.getSource();
//        String settingFilePath = file.getParentFile().toString() + FileUtils.FILE_SEPARATOR + "\\jsons\\" + "uploadSetting.json";
        String settingFilePath = file.getParentFile().toString() + FileUtils.FILE_SEPARATOR + "uploadSetting.json";
        BufferedReader reader = null;
        StringBuilder last = new StringBuilder();
        InputStreamReader inputStreamReader;
        try (FileInputStream fileInputStream = new FileInputStream(settingFilePath)) {
            inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);

            reader = new BufferedReader(inputStreamReader);
            String tempString;
            while ((tempString = reader.readLine()) != null) {
                last.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return last.toString();
    }

    public static File getFileByBytes(byte[] bytes, String prefix, String suffix) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {

            file = File.createTempFile(prefix, suffix);

            //输出流
            fos = new FileOutputStream(file);

            //缓冲流
            bos = new BufferedOutputStream(fos);

            //将字节数组写出
            bos.write(bytes);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return file;
        }
    }


    public static File getFileByUrl(String dataUrl) throws IOException {

        URL url = new URL(dataUrl);  //想要读取的url地址
        InputStream in = url.openStream();
        File file = File.createTempFile("new_url", ".pdf");  //创建文件
        OutputStream os = new FileOutputStream(file);  //创建文件输出流
        int bytesRead;
        byte[] buffer = new byte[8192];
        int len = 8192;
        while ((bytesRead = in.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        //关闭释放流
        os.close();
        in.close();
        return file;
    }

    public static File getPictureFileByUrl(String dataUrl) throws IOException {

        URL url = new URL(dataUrl);  //想要读取的url地址
        InputStream in = url.openStream();
        File file = File.createTempFile("new_url", ".jpg");  //创建文件
        OutputStream os = new FileOutputStream(file);  //创建文件输出流
        int bytesRead;
        byte[] buffer = new byte[8192];
        int len = 8192;
        while ((bytesRead = in.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        //关闭释放流
        os.close();
        in.close();
        return file;
    }

    public String getPath(String url) {
        return getStaticPath(COMMON_FILE) + url;
    }

    public String getDirectoryName() {
        return DateUtils.getNowTimeFormat("yyyyMMdd");
    }

    public String getSavePath(String directoryName) {
        return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + directoryName + FILE_SEPARATOR;
    }

    public String createDirectory() {
        String directoryName = this.getDirectoryName();
        String savePath = this.getSavePath(directoryName);
        File directory = new File(savePath);
        if (!directory.exists()) {
            directory.mkdir();
        }
        return directoryName;
    }

    public String createRandomDirectory() {
        String directoryName = IdUtil.simpleUUID();
        String savePath = this.getSavePath(directoryName);
        File directory = new File(savePath);
        if (!directory.exists()) {
            directory.mkdir();
        }
        return directoryName;
    }

    public static FileInputStream byteToFile(byte[] bytes) {
        String fileName = IdUtil.simpleUUID() + ".png";
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        try {
            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
            bufferedOutput.write(bytes);
            fileInputStream = new FileInputStream(file);
            file.deleteOnExit();
            return fileInputStream;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileInputStream;
    }

    public String getTempPath(String fileName) {
        String tempPath = getStaticPath(COMMON_FILE) + FILE_SEPARATOR + "temp";
        File file = new File(tempPath);
        if (!file.exists()) {
            file.mkdir();
        }
        return tempPath + FILE_SEPARATOR + fileName;
    }

    public String getDirectory(String fileName) {
        return FILE_SEPARATOR + this.createDirectory() + FILE_SEPARATOR + fileName;
    }

    public String getSystemPath(String url) {
        return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + url;
    }

    public static String getSystemPath2(String url) {
        return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + url;
    }

    public static void writeFile(String json, String FilePath) {

        try {
            File file = new File(FilePath);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
                file.createNewFile();
            }

            // true = append file
            FileWriter fileWritter = new FileWriter(file, false);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(json);
            bufferWritter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File getFileByName(File file, String name) {
        for (File file1 : file.listFiles()) {
            if (file1.getName().equals(name)) {
                return file1;
            }
        }
        return null;
    }


    public static void writeFile(Object object, File file) {
        String json = JSON.toJSONString(object);
        try {
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
                file.createNewFile();
            }
            // true = append file
            FileWriter fileWritter = new FileWriter(file, false);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(json);
            bufferWritter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file == null || file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
