package com.ann.demo.utils;

import org.apache.cxf.common.logging.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.LocalDate;
import java.util.Objects;

/**
 * @Author: LeiJiaXin
 * @Date: 2019/7/24 16:42
 */
@Component
public class FileUtils {

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

    // pdf地址
    public static String pdfPath;

    @Value("${file.pdfPath}")
    public void setPdfPath(String pdfPath) {
        FileUtils.pdfPath = pdfPath;
    }

    public static String getPdfPath() {
        return pdfPath;
    }

    // image地址
    public static String imagePath;

    @Value("${file.imagePath}")
    public void setImagePath(String imagePath) {
        FileUtils.imagePath = imagePath;
    }

    public static String getImagePath() {
        return imagePath;
    }


    public static File createFile(String fileType, String inpNo, String visitId, String path) throws IOException {
        File localFile = null;
        try {
            //生成图片地址
            // ---------------------------此处写死 年月需改善
            LocalDate date = LocalDate.now();
            String fileDirName = null;
            if (Objects.equals(fileType, "images")) {
                fileDirName = imagePath+ date.getYear() + "/" + date.getMonthValue() + "/" + inpNo + "_" + visitId;
            } else if (Objects.equals(fileType, "pdfs")) {
                fileDirName = pdfPath + "/" + date.getYear() + "/" + date.getMonthValue() + "/" + inpNo + "_" + visitId;
            }

            //判断是否有该文件夹 否则创建
            File fileDir = new File(fileDirName);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            String fileName = null;
            if (Objects.equals(fileType, "images")) {
                fileName = fileDir + "/" + path + ".jpg";
            } else if (Objects.equals(fileType, "pdfs")) {
                fileName = fileDir + "/" + path + ".pdf";
            }

            localFile = new File(fileName);
            if (!localFile.exists()) {
                localFile.createNewFile();
            }

        } catch (IOException e) {
            logger.error("出错咯！错误信息:" + e);
            throw e;
        }
        return localFile;
    }


    public static void deleteImageFile(File file) {
        if (!file.exists()) {
            System.out.println(file.getAbsolutePath() + "文件不存在");
        } else {
            if (file.length() == 0) {
                // 当前文件 大小为0
                File fileParent = new File(file.getParent());
                File[] fileParents = fileParent.listFiles();
                // 如果文件个数大于1 那么已经有其他的报告 只删除本身 否则就删除当前文件以及父级目录
                if (fileParents.length > 1) {
                    // -----------------------------改成log 形式
                    file.delete();
                    System.out.println("删除文件为:" + file.getAbsolutePath());
                } else {
                    file.delete();
                    fileParent.delete();
                    System.out.println("删除文件为:" + file.getAbsolutePath() + ",以及父文件:" + fileParent.getName());
                }
            }
        }
    }


    public static int deleteImageFile1(File file, int i) {
        if (!file.exists()) {
            System.out.println(file.getAbsolutePath() + "文件不存在");
            return i;
        } else {
            // 当前文件 大小为0
            File fileParent = new File(file.getParent());
            File[] fileParents = fileParent.listFiles();
            // 如果文件个数大于1 那么已经有其他的报告 只删除本身 否则就删除当前文件以及父级目录
            if (fileParents.length > 1) {
                // -----------------------------改成log 形式
                file.delete();
                System.out.println("删除文件为:" + file.getAbsolutePath());
            } else {
                file.delete();
                fileParent.delete();
                System.out.println("删除文件为:" + file.getAbsolutePath() + ",以及父文件:" + fileParent.getName());
            }
            return i++;
        }
    }

    public static File getImageFileByByteArray(Object[] objects, File file) throws Exception {
        OutputStream out = null;
        InputStream is = null;
        try {
            out = new FileOutputStream(file);
            is = new ByteArrayInputStream((byte[])objects[0]);
            byte[] buff = new byte[1024];
            int len = 0;
            while((len=is.read(buff))!=-1){
                out.write(buff, 0, len);
            }
            return file;
        } catch (Exception e) {
            FileUtils.deleteImageFile(file);
            logger.error("出错咯！错误信息:" + e);
            throw e;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    FileUtils.deleteImageFile(file);
                    logger.error("出错咯！错误信息:" + e1);
                    throw e1;
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e1) {
                    FileUtils.deleteImageFile(file);
                    logger.error("出错咯！错误信息:" + e1);
                    throw e1;
                }
            }
        }
    }

    public static String haha(String path,byte[] bytes){
        int n = 1024;
        FileOutputStream os = null;
        try {
            // 创建文件输出流对象
            File file = new File(path);
            os= new FileOutputStream(file);
            // 写入输出流
            int length = bytes.length;
            int start = 0;
            while(length>start+n){
                os.write(bytes, start, n);
                start= start+n;
            }

            if(length != start+n){
                n = length-start;
                os.write(bytes, start, n);
            }
            return path;
        } catch (IOException e) {
            return null;
        }finally{
            // 关闭输出流
            try {
                if(os !=null){
                    os.close();
                }
            } catch (IOException e) {
                return null;
            }
        }
    }


    public static void main(String[] args) throws ClassNotFoundException {
        String address = "ftp://10.6.0.155/2019-10-21/000581031700_1_000581031700_0_1_JHR06.00.02_34_2_0.pdf";
        String a = address.substring(0, address.indexOf(".pdf"));
        String emrPath = a.substring(a.lastIndexOf("_") + 1, a.length());

        System.out.println(emrPath);
    }
}
