package com.gz;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.gz.dto.archive.ArchiveDTO;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Slf4j
public class ConverOldSystemData {

    private static final Charset CHARSET = Charset.forName("UTF-8");


    private static List<JSON> rows = new ArrayList<>();

    public static void main(String[] args) throws FileNotFoundException {
        final String archiveTypePath = "H:\\10_建设用地类";
        // 数据目录文件夹
        File archiveTypeFolder = FileUtil.file(archiveTypePath);
        if (archiveTypeFolder == null || !archiveTypeFolder.exists()) {
            throw new FileNotFoundException("档案分类文件夹不存在");
        }
        // 循环档案文件夹
        for (File archiveFolder : archiveTypeFolder.listFiles()) {
            if (archiveFolder.isDirectory()) {
                // 存储图片文件
                List<File> images = new ArrayList<>();
                File[] files = archiveFolder.listFiles();
                // 数据Json
                JSON archiveJson = null;
                // 卷内目录Json
                JSON innerArchiveJson = null;
                for (File file : files) {
                    String fileType = FileTypeUtil.getType(file);
                    if ("jpg".equals(fileType)) {
                        // 图片文件
                        images.add(file);
                    } else if ("json".equals(fileType)) {
                        // Json文件
                        String fileName = FileUtil.getName(file);
                        if (fileName.equals("data.json")) {
                            archiveJson = JSONUtil.readJSON(file, CHARSET);
                        } else if (fileName.equals("inner.json")) {
                            innerArchiveJson = JSONUtil.readJSON(file, CHARSET);
                        }

                    }
                }
                // 排序图片
                Collections.sort(images, Comparator.comparingInt(o -> Integer.parseInt(getQuantity(FileUtil.getName(o)))));
                ArchiveDTO archiveDTO = convertArchiveData(archiveJson);
                imgToPdf(images, StrUtil.format("F:/temp/{}.pdf", archiveDTO.getDh()));
                log.info("读取档案文件成功 数据：{} 卷内目录：{} 图片文件：{}张", archiveJson, innerArchiveJson, images.size());
//                break;
            } else {
                log.warn("档案分类文件夹下出现非目录文件夹，地址：{}", archiveFolder.getAbsolutePath());
            }
        }
//        ExcelWriter writer = ExcelUtil.getWriter();
////        writer.addHeaderAlias("bgqx", "保管期限");
////        writer.addHeaderAlias("dh", "档号");
////        writer.addHeaderAlias("zny", "止年月");
////        writer.addHeaderAlias("js", "件数");
////        writer.addHeaderAlias("bz", "备注");
////        writer.addHeaderAlias("ys", "页数");
////        writer.addHeaderAlias("mj", "密级");
////        writer.addHeaderAlias("ajh", "案卷号");
////        writer.addHeaderAlias("qny", "起年月");
////        writer.addHeaderAlias("flh", "分类号");
////        writer.addHeaderAlias("mlh", "目录号");
////        writer.addHeaderAlias("nd", "年度");
////        writer.addHeaderAlias("tm", "题名");
//
//        writer.write(rows, true);
//        FileOutputStream out = new FileOutputStream("F:\\temp\\10_建设用地类.xls");
//        writer.flush(out, true);
//        writer.close();
//        IoUtil.close(out);
    }

    private static ArchiveDTO convertArchiveData(JSON json) {
        ArchiveDTO c = new ArchiveDTO();
        JSONArray a = (JSONArray) json;
        JSONObject b = (JSONObject) a.get(0);
//        c.setBgqx(b.getStr("bgqx"));
        c.setDh(b.getStr("dh"));
        rows.add(b);
        return c;
    }

    /**
     * 图片转Pdf
     *
     * @param images  图片集合
     * @param pdfPath pdf存储路径
     * @author LiuChangLan
     * @since 2022/1/25 14:07
     */
    private static void imgToPdf(List<File> images, String pdfPath) throws FileNotFoundException {
        Document document = new Document();
        // 设置文档页边距
        document.setMargins(0, 0, 0, 0);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pdfPath);
            PdfWriter.getInstance(document, fos);
            // 打开文档
            document.open();
            float firstImageHeight = 0;
            float firstImageWidth = 0;
            for (int i = 0; i < images.size(); i++) {
                File image = images.get(i);
                if ("jpg".equals(FileTypeUtil.getType(image))) {
                    Image instance = Image.getInstance(image.getAbsolutePath());
                    // 图片宽度
                    float imgWidth = instance.getWidth();
                    // 图片高度
                    float imgHeight = instance.getHeight();
                    // 读取第一张图片高度
                    if (i == 0) {
                        firstImageWidth = imgWidth;
                        firstImageHeight = imgHeight;
                    }
                    if (imgWidth != firstImageWidth) {
                        instance.scaleAbsolute(firstImageWidth, firstImageHeight);
                    }
                    // 设置页面宽高与图片一致
                    Rectangle rectangle = new Rectangle(firstImageWidth, firstImageHeight);
                    document.setPageSize(rectangle);
                    // 图片居中
                    instance.setAlignment(Image.ALIGN_CENTER);
                    // 新建一页添加图片
                    document.newPage();
                    document.add(instance);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
            IoUtil.close(fos);
            log.info("图片转换pdf成功");
        }
    }

    /**
     * 读取字符串中开头数字
     *
     * @author LiuChangLan
     * @since 2022/1/25 14:08
     */
    public static String getQuantity(String regular) {
        int index = 0;
        for (int i = 0; i < regular.length(); i++) {
            char c = regular.charAt(i);
            if (Character.isDigit(c)) {
                if (i == regular.length() - 1) {
                    index = i + 1;
                } else {
                    index = i;
                }
                continue;
            } else {
                index = i;
                break;
            }
        }
        return regular.substring(0, index);
    }
}
