package cn.cslg.pas.common.utils;

import cn.cslg.pas.common.model.dto.UploadFileDTO;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
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(FileUtils.class);
        //获取 applicationHome 内的路径 ...\target\classes 到这一层级下
        File file = ah.getSource();
        //获取 file的parentFile 即最后一级之前的所有层级路径(包括盘符) 这里能获得到的最终层级为  ...\target 后续用FILE_SEPARATOR(系统路径分割通配符 即 "\") 以及fileName拼接生成存放文件的目录层级 即为根目录 root
        String rootPath = file.getParentFile().toString() + FILE_SEPARATOR + fileName;
        //根据上方生成的根目录路径 生成对应文件夹 没有就新建
        File root = new File(rootPath);
        if (!root.exists()) {
            root.mkdir();
        }
        //返回的最终形式为 盘符:\项目层级\target\file
        return rootPath;
    }

    public UploadFileDTO uploadFile(MultipartFile file) {
        UploadFileDTO fileDTO = new UploadFileDTO();
        //以下操作为 先取得传入文件的完整文件名 (文件名 + 后缀) 然后用FileUtil分别取出 文件名 和 不带 "." 的后缀 然后将这些内容装配进 实体中
        //file.getOriginFilename 获取源文件
        //FileUtil.getPrefix 返回主文件名
        fileDTO.setName(FileUtil.getPrefix(file.getOriginalFilename()));
        //FileUtil.extName 获取文件的扩展名(后缀名),扩展名不带 "."
        fileDTO.setExtName(FileUtil.extName(file.getOriginalFilename()));
        //获取目录名 用时间作为目录名称
        String directoryName = this.getDirectoryName();
        //用IdUtil生成的UUID 与实体中的 extName(后缀名) 拼接后作为文件名 simpleUUID与randomUUID的区别是 simpleUUID 没有 "-"
        String fileName = IdUtil.simpleUUID() + "." + fileDTO.getExtName();
        //将完整文件名进行装配
        fileDTO.setFileName(fileName);
        //生成存储文件的路径
        String savePath = this.getSavePath(directoryName);
        //根据生成存储文件的路径 生成对应文件夹 没有就新建
        File directory = new File(savePath);
        if (!directory.exists()) {
            directory.mkdir();
        }
        this.saveFile(file, savePath + fileName);
        fileDTO.setPath(FILE_SEPARATOR + directoryName + FILE_SEPARATOR + fileName);
        fileDTO.setFileSize(file.getSize());
        return fileDTO;
    }

    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 void saveFile(MultipartFile file, String path) {
        try {
            file.transferTo(new File(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    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 getSavePath(String directoryName) {
        return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + directoryName + FILE_SEPARATOR;
    }

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

    public String getDirectory2(String directoryName) {
        return FILE_SEPARATOR + directoryName + FILE_SEPARATOR;
    }

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

    public String getSystemPath() {
        return getStaticPath(COMMON_FILE);
    }

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

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

    public String analysisJsonFile() {
        ApplicationHome ah = new ApplicationHome(BackupUtils.class);
        File file = ah.getSource();
        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 String analysisJsonFile(String fileName) {
        ApplicationHome ah = new ApplicationHome(BackupUtils.class);
        File file = ah.getSource();
        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 MultipartFile fileToMultipartFile(File file) {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null);
        FileItem item = diskFileItemFactory.createItem(file.getName(), "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            int len = 8192;
            while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (MultipartFile) new CommonsMultipartFile(item);
    }

    public static File getFile(String url) throws Exception {
        //读取图片类型
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("new_url", ".jpg");
            //获取文件
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

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

        return file;
    }


}

