package com.dxhy.core.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Gy Chen
 * @date 2021/3/17
 */
@Component
@Slf4j
@SuppressWarnings({"AliDeprecation", "AlibabaUndefineMagicConstant"})
public class PDFExportUtil {
    private static PdfWriter writer;
    private static ArrayList<PdfPRow> listRow;
    private static PdfPTable table;

    public static void pdfExport(String fileTitle, String filePath, String orgInfo, java.util.List<String[]> dataList,
        String[] titleColumns, float[] columnWidths, boolean firstPage, boolean lastPage) {
        Document document = new Document(PageSize.A4);
        try {

            // 中文字体，解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 正文字体风格
            Font contextFont = new Font(bfChinese, 10, Font.NORMAL);
            if (firstPage) {

                // 两列的表
                table = new PdfPTable(titleColumns.length);
                // 宽度100%填充
                table.setWidthPercentage(100);
                // 前间距
                table.setSpacingBefore(10f);
                // 后间距
                table.setSpacingAfter(10f);
                listRow = table.getRows();
                // 设置列宽比例 1:3
                table.setWidths(columnWidths);
                // 一行两格
                PdfPCell[] cells1 = new PdfPCell[titleColumns.length];
                PdfPRow row1 = new PdfPRow(cells1);
                for (int i = 0; i < titleColumns.length; i++) {
                    cells1[i] = new PdfPCell(new Paragraph(titleColumns[i], contextFont));
                    cells1[i].setUseAscender(true);
                    cells1[i].setUseDescender(true);
                    cells1[i].setHorizontalAlignment(Element.ALIGN_CENTER);
                }

                listRow.add(row1);
            }

            for (String[] datas : dataList) {
                // 一行两格
                PdfPCell[] cells1 = new PdfPCell[titleColumns.length];
                PdfPRow row1 = new PdfPRow(cells1);
                for (int i = 0; i < datas.length; i++) {
                    cells1[i] = new PdfPCell(new Paragraph(datas[i], contextFont));
                    cells1[i].setUseAscender(true);
                    cells1[i].setUseDescender(true);
                    if (i == 7 || i == 8 || i == 9) {
                        cells1[i].setHorizontalAlignment(Element.ALIGN_RIGHT);
                    } else {
                        cells1[i].setHorizontalAlignment(Element.ALIGN_LEFT);
                    }
                }
                listRow.add(row1);
            }
            if (lastPage) {
                document = new Document(new RectangleReadOnly(842.0F, 595.0F));
                // 新建一个pdf文件
                writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
                document.open();
                // 红标题字体风格
                Font redTitleFont = new Font(bfChinese, 20, Font.BOLD, BaseColor.BLACK);
                // 红标题抬头
                Paragraph redTitle = new Paragraph(fileTitle, redTitleFont);
                // 居中
                redTitle.setAlignment(Element.ALIGN_CENTER);
                // 文档中加入红标题字段
                document.add(redTitle);

                // 标题字体风格
                Font titleFont = new Font(bfChinese, 12, Font.NORMAL);
                // 标题内容
                Paragraph title = new Paragraph(orgInfo, titleFont);
                // 离上一段落（标题）空的行数
                title.setSpacingBefore(25);
                // 设置标题格式对齐方式
                title.setAlignment(Element.ALIGN_LEFT);
                // 文档中加入标题字段
                document.add(title);
                // 把表格添加到文件中
                document.add(table);
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        } finally {
            if (lastPage) {
                document.close();
                writer.close();
            }
        }
    }


    public static void pdfExport(String fileTitle, String filePath, String orgInfo, List dataList,
                                 JSONObject jsonObject, float[] columnWidths, boolean firstPage, boolean lastPage) {
        Document document = new Document(PageSize.A4);
        try {

            // 中文字体，解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 正文字体风格
            Font contextFont = new Font(bfChinese, 10, Font.NORMAL);

            // 生成excel
            JSONArray jsonArray = jsonObject.getJSONArray("titleExcleList");
            Object[] objects = jsonArray.toArray();
            String[] titleColumns = Arrays.copyOf(objects, objects.length, String[].class);
            JSONArray jsonArray1 = jsonObject.getJSONArray("titleExcleProp");
            Object[] objects1 = jsonArray1.toArray();
            String[] titleProp = Arrays.copyOf(objects1, objects1.length, String[].class);

            if (firstPage) {
                List<List<String>> list1 = new ArrayList<>();
                if (dataList != null && dataList.size() > 0) {
                    for (Object o : dataList) {
                        List<String> data = new ArrayList<>();
                        for (String s : titleProp) {
                            String value = (String)getValue(o, s);
                            data.add(value);
                        }
                        list1.add(data);
                    }
                }


                // 两列的表
                table = new PdfPTable(titleColumns.length);
                // 宽度100%填充
                table.setWidthPercentage(100);
                // 前间距
                table.setSpacingBefore(10f);
                // 后间距
                table.setSpacingAfter(10f);
                listRow = table.getRows();
                // 设置列宽比例 1:3
                table.setWidths(columnWidths);
                // 一行两格
                PdfPCell[] cells1 = new PdfPCell[titleColumns.length];
                PdfPRow row1 = new PdfPRow(cells1);
                for (int i = 0; i < titleColumns.length; i++) {
                    cells1[i] = new PdfPCell(new Paragraph(titleColumns[i], contextFont));
                    cells1[i].setUseAscender(true);
                    cells1[i].setUseDescender(true);
                    cells1[i].setHorizontalAlignment(Element.ALIGN_CENTER);
                }

                listRow.add(row1);
            }

            List<List<String>> list1 = new ArrayList<>();
            if (dataList != null && dataList.size() > 0) {
                for (Object o : dataList) {
                    List<String> data = new ArrayList<>();
                    for (String s : titleProp) {
                        String value = (String)getValue(o, s);
                        data.add(value);
                    }
                    list1.add(data);
                }
            }

            for (List<String> datas : list1) {
                // 一行两格
                PdfPCell[] cells1 = new PdfPCell[titleColumns.length];
                PdfPRow row1 = new PdfPRow(cells1);
                for (int i = 0; i < datas.size(); i++) {
                    cells1[i] = new PdfPCell(new Paragraph(datas.get(i), contextFont));
                    cells1[i].setUseAscender(true);
                    cells1[i].setUseDescender(true);
                    if (i == 7 || i == 8 || i == 9) {
                        cells1[i].setHorizontalAlignment(Element.ALIGN_RIGHT);
                    } else {
                        cells1[i].setHorizontalAlignment(Element.ALIGN_LEFT);
                    }
                }
                listRow.add(row1);
            }
            if (lastPage) {
                document = new Document(new RectangleReadOnly(842.0F, 595.0F));
                // 新建一个pdf文件
                writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
                document.open();
                // 红标题字体风格
                Font redTitleFont = new Font(bfChinese, 20, Font.BOLD, BaseColor.BLACK);
                // 红标题抬头
                Paragraph redTitle = new Paragraph(fileTitle, redTitleFont);
                // 居中
                redTitle.setAlignment(Element.ALIGN_CENTER);
                // 文档中加入红标题字段
                document.add(redTitle);

                // 标题字体风格
                Font titleFont = new Font(bfChinese, 12, Font.NORMAL);
                // 标题内容
                Paragraph title = new Paragraph(orgInfo, titleFont);
                // 离上一段落（标题）空的行数
                title.setSpacingBefore(25);
                // 设置标题格式对齐方式
                title.setAlignment(Element.ALIGN_LEFT);
                // 文档中加入标题字段
                document.add(title);
                // 把表格添加到文件中
                document.add(table);
            }
        } catch (Exception e) {
            log.info("业务处理异常：{}", e);
        } finally {
            if (lastPage) {
                document.close();
                writer.close();
            }
        }
    }


    public static Object getValue(Object dto, String name) throws Exception {
        String s = name.substring(0, 1).toUpperCase();
        String substring = name.substring(1);
        try {
            Method method = dto.getClass().getMethod("get" + s + substring);
            return method.invoke(dto);
        } catch (Exception e) {
            return "";
        }
    }

}
