package com.friday.custody.service.trustService.mailHandleService.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("fileUtil")
public class FileUtil {
    public static void main(String[] args) throws Exception {
        String filePath = "D:\\wj\\mailFile\\ABD20220608\\TAInfoo.Txt"; // 文件路径
//        String s = readLine(filePath);
//        System.out.println(s.replace("FundInfo","").replace(" ","").replaceFirst("0*",""));
//        readPointLine(filePath,4).stream().forEach(e->{
//            String string = getString(8, 108, e);
//            System.out.println(string);
//        });
//        List<String> read = read(filePath);
//        read.stream().forEach(e->{
////            System.out.println("eeeee:"+e);
//            //String s = e.substring(112, 123).replaceFirst("0*", "");//.replaceFirst("0*", "");s.substring(0,s.length()-2)+"."+s.substring(s.length()-2)
//
//            System.out.println(e);
//        });
//        File file = new File(CJConstants.filePath);
//        deleteFile(file);
    }

    /*public static String getFileCharsetName(String fileName) throws IOException {
        InputStream inputStream = new FileInputStream(fileName);
        byte[] head = new byte[3];
        inputStream.read(head);
        String charsetName = "GBK";// 或GB2312，即ANSI
        if (head[0] == -1 && head[1] == -2) // 0xFFFE
            charsetName = "UTF-16";
        else if (head[0] == -2 && head[1] == -1) // 0xFEFF
            charsetName = "Unicode";// 包含两种编码格式：UCS2-Big-Endian和UCS2-Little-Endian
        else if (head[0] == -27 && head[1] == -101 && head[2] == -98)
            charsetName = "UTF-8"; // UTF-8(不含BOM)
        else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
            charsetName = "UTF-8"; // UTF-8-BOM
        inputStream.close();
        return charsetName;
    }*/


    // 使用GBK编码表进行字符串的截取，一个英文字符对应码表一个正数，一个汉字对应两个负数
//    public static String cutStringByByte(String str, int len)
//            throws IOException {
//        byte[] buf = str.getBytes("gbk");
//        int count = 0;
//        for (int x = len - 1; x >= 0; x--) {
//            if (buf[x] < 0) {
//                count++;
//            } else {
//                break;
//            }
//        }
//        if (count % 2 == 0) {
//            return new String(buf, 0, len, "gbk");
//        } else {
//            return new String(buf, 0, len - 1, "gbk");
//        }
//    }

    /**
     * 读取内容
     */
    public static List<byte[]> read(String filePath){
        BufferedReader read = null;
        InputStreamReader in = null;
        List<byte[]> list = new ArrayList<>();
        FileInputStream fi = null;
        try {
            fi = new FileInputStream(filePath);
            in = new InputStreamReader(fi, "GBK");
            read = new BufferedReader(in);
            String line = "";
            //循环读取文件的每一行，对需要修改的行进行修改，放入缓冲对象中
            while ((line = read.readLine()) != null) {
                if(line.length()>50){
                    byte[] bytes = line.getBytes("GBK");
                    list.add(bytes);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (read != null) {
                    read.close();
                }
                if (in != null) {
                    in.close();
                }
                if (fi != null) {
                    fi.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 读取内容
     */
//    public static List<String> readChar(String filePath){
//        List<String> list = new ArrayList<>();
//        try {
//            //通过InputStreamReader指定编码读文件
//            InputStreamReader ir = new InputStreamReader(new FileInputStream(filePath),"gbk");
//            //创建一个char类型的数组接收读取到的内容
//            char[] chars = new char[new FileInputStream(filePath).available()];
//            //用于接收在文件中读到的有效内容的长度
//            int len;
//            //循环读取文件，当读到文件末尾时len=-1
//            while ((len=ir.read(chars))!=-1)
//            {
//                //从chars数组头部开始将len个字符转为String对象
//               list.add(new String(chars,0,len));
//            }
//            ir.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return list;
//    }

    //读取第一行

    /**
     * 查询关键字所在行内容以及行数
     * @param filePath
     * @param keyWord
     * @return
     */
    public static Map<String, String> readLine(String filePath, String keyWord){
        int lineNum = 0;
        BufferedReader read = null;
        String line = null;
        InputStreamReader in = null;
        FileInputStream fi = null;
        Map<String, String> lineMap = new HashMap<>();
        try {
            fi = new FileInputStream(filePath);
            in = new InputStreamReader(fi, Charset.forName("GBK"));
            read = new BufferedReader(in);
            //循环读取文件的每一行
            while ((line = read.readLine()) != null) {
                lineNum++;
                //读取到fundInfo所在行,返回所在行号,已经所在行内容
                if(line.contains(keyWord)) {
                    lineMap.put("line", line);
                    lineMap.put("lineNum", String.valueOf(lineNum));
                    return lineMap;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (read != null) {
                    read.close();
                }
                if (in != null) {
                    in.close();
                }
                if (fi != null) {
                    fi.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lineMap;
    }

    //读取指定行数

    /**
     *
     * @param filePath
     * @param readLine 要读取的数据行
     * @param startLine 要读取的开始行数
     * @return
     */
    public static List<byte[]> readPointLine(String filePath,int readLine, int startLine){
        BufferedReader read = null;
        List<byte[]> list = new ArrayList<>();
        InputStreamReader in = null;
        FileInputStream fi = null;
        try {
            int i =0;
            fi = new FileInputStream(filePath);
            in = new InputStreamReader(fi, Charset.forName("GBK"));
            read = new BufferedReader(in);
            String line = "";
            //循环读取文件的每一行，对需要修改的行进行修改，放入缓冲对象中
            while ((line = read.readLine()) != null) {
                i++;
                //第一行数据为次要数据，所以设定行长度大于50
                if (line.length() > 50 && i > startLine && i <= startLine + readLine + 1) {
                    byte[] bytes = line.getBytes("GBK");
                    list.add(bytes);
                }
            }
            //循环读取文件的每一行，对需要修改的行进行修改，放入缓冲对象中
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (read != null) {
                    read.close();
                }
                if (in != null) {
                    in.close();
                }
                if (fi != null) {
                    fi.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static void deleteFile(File file) throws IOException {
        File[] files = file.listFiles();
        if (files!=null){//如果包含文件进行删除操作
            for (File f:files) {
                //判断遍历出的文件是不是文件
                if (f.isFile()){
                    //如果是则直接删除
                    f.delete();
                }else if (f.isDirectory()){//通过递归的方法找到文件夹里的文件
                    deleteFile(f);
                }
                f.delete();//删除子目录
            }
        }
    }

    private static String getString(int offSet, int lastSet, byte[] bytes){
        byte[] bytes1 = new byte[1024];
        for (int j = offSet; j < lastSet; j++) {
            bytes1[j - offSet] = bytes[j];
        }
        String s = null;
        try {
            s = new String(bytes1,"gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 递归删除空文件夹
     * @param file
     */
    public static void deleteFolder(File file){
        if (file.exists()) {
            File[] files = file.listFiles();
            if(files.length == 0){
                file.delete();
            } else {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isDirectory() && files[i].listFiles().length != 0) {
                        System.out.println(files[i].getName() + "是文件夹");
                        deleteFolder(files[i]);
                        if (files[i].listFiles().length == 0) {
                            files[i].delete();
                        }
                    }
                }
            }
        }
    }

    /**
     * 递归查找最后一层文件夹
     * @param filePath
     * @return
     */
    public static String findLastDir(String filePath) {
        StringBuilder lastDir = new StringBuilder(filePath);
        File checkFile = new File(filePath);
        //递归找最后一层文件夹
        File[] checkFiles = checkFile.listFiles();
        for(File file : checkFiles){
            if(file != null && file.isDirectory()){
                lastDir = new StringBuilder(findLastDir(file.getAbsolutePath()));
                break;
            }
        }
        return lastDir.toString();
    }

}
