package com.css.simulation.resource.server.infra.util;

import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import lombok.SneakyThrows;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import java.awt.*;
import java.awt.Font;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.jfree.chart.ChartUtils;

import java.io.*;
import java.util.Arrays;


/**
 * @author 15765
 * @date 2024/3/26 12:47
 */
public class ChartUtil {
    private static final Color[] BAR_COLORS = new Color[]{new Color(79, 129, 189), new Color(192, 80, 77), new Color(155, 187, 89),};

    private static final Color[] PIE_COLORS = new Color[]{new Color(75, 172, 198), new Color(128, 100, 162), new Color(155, 187, 89), new Color(192, 80, 77), new Color(79, 129, 189), new Color(44, 77, 117), new Color(247, 150, 70), new Color(165, 165, 165),};


    static StandardChartTheme initChartTheme() {
        StandardChartTheme currentTheme = new StandardChartTheme("JFree");
        // 横轴纵轴标题文字大小
        currentTheme.setLargeFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 13));
        // 横轴纵轴数值文字大小
        currentTheme.setRegularFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 11));
        currentTheme.setExtraLargeFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 13));
        // 背景颜色
        currentTheme.setPlotBackgroundPaint(new Color(255, 255, 204, 0));
        // 边框线条
        currentTheme.setPlotOutlinePaint(new Color(0, 0, 0, 0));
        // 网格线条
        currentTheme.setRangeGridlinePaint(new Color(78, 74, 74));
        return currentTheme;
    }


    /**
     * 柱状图
     *
     * @param title
     * @param categoryAxisLabel
     * @param valueAxisLabel
     * @param dataset           数据集
     * @return org.jfree.chart.JFreeChart
     * @author Hou_fx
     * @date 2021.8.4 14:03
     */
    public static JFreeChart barChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset) {
        ChartFactory.setChartTheme(initChartTheme());

        JFreeChart chart = ChartFactory.createBarChart(title, categoryAxisLabel, valueAxisLabel, dataset, PlotOrientation.VERTICAL, true, true, false);

        CategoryPlot plot = chart.getCategoryPlot();
        plot.getDomainAxis().setTickLabelFont(new Font("宋体",Font.PLAIN,9));
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        // 纯色显示
        renderer.setBarPainter(new StandardBarPainter());
        // 柱子上显示小数字
        renderer.setDefaultItemLabelsVisible(false);
        renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        //设置不能在柱子上正常显示的那些数值的显示方式，将这些数值显示在柱子外面
        ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(
                ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT,
                TextAnchor.HALF_ASCENT_LEFT, -1.57D);

        //设置不能正常显示的柱子label的position
        renderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
        renderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);
        // 显示每个柱的数值，并修改该数值的字体属性


//        renderer.setMaximumBarWidth(0.05);
        // 设置柱子间隔
        renderer.setItemMargin(0.0);
        // 设置柱子颜色
        for (int i = 0; i < dataset.getRowKeys().size(); i++) {
            renderer.setSeriesPaint(i, BAR_COLORS[i]);
        }
        return chart;
    }

    /**
     * 饼图
     *
     * @param title
     * @param dataset
     * @return org.jfree.chart.JFreeChart
     * @author Hou_fx
     * @date 2021.8.4 14:04
     */
    public static JFreeChart pieChart(String title, DefaultPieDataset dataset) {
        ChartFactory.setChartTheme(initChartTheme());

        JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, true, false);
        PiePlot plot = (PiePlot) chart.getPlot();
        // 设置扇区颜色
        for (int i = 0; i < dataset.getKeys().size(); i++) {
            plot.setSectionPaint(dataset.getKey(i), PIE_COLORS[i]);
        }
        // 设置扇区的线条颜色
        plot.setDefaultSectionOutlinePaint(new Color(255, 255, 255));
        // 设置扇区的线条大小
        plot.setDefaultSectionOutlineStroke(new BasicStroke(2));
        // 设置标签颜色
        plot.setLabelLinkPaint(new Color(255, 255, 255, 0));
        // 设置标签背景色
        plot.setLabelBackgroundPaint(new Color(255, 255, 255, 0));
        // 设置标签线条颜色
        plot.setLabelOutlinePaint(new Color(255, 255, 255, 0));
        // 设置标签阴影颜色
        plot.setLabelShadowPaint(new Color(255, 255, 255, 0));
        // 设置饼图阴影颜色
        plot.setShadowPaint(new Color(255, 255, 255, 0));
        // 添加标签数字百分比显示
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(("{0}{2}"), NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
        return chart;
    }

    @SneakyThrows
    public static void main(String[] args) {
        PdfWriter writer = null;
        OutputStream outputStream = null;
        Document doc = null;
        try {
            doc = new Document(PageSize.A4);
            doc.setMargins(55, 46, 27, 20);

            File f = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\9.pdf");
            if (!f.getParentFile().exists()) {
                FileUtils.forceMkdir(f.getParentFile());
            }
            outputStream = new FileOutputStream(f);
            writer = PdfWriter.getInstance(doc, outputStream);

            doc.open();


            // 饼图
            ByteArrayOutputStream pieBos = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(pieBos, ChartUtil.pieChart("复杂度等级分布图", getPieDataset()), 300, 188);
            Image pieImage = Image.getInstance(pieBos.toByteArray());
            pieBos.close();
//            pieImage.scalePercent(80);
//            doc.add(pieImage);
            // 饼图
            ByteArrayOutputStream pieBos1 = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(pieBos1, ChartUtil.pieChart("危险度等级分布图", getPieDataset()), 300, 188);
            Image pieImage1 = Image.getInstance(pieBos1.toByteArray());
            pieBos1.close();
//            pieImage1.scalePercent(80);
//            doc.add(pieImage1);

            float[] floats = new float[2];
            Arrays.fill(floats, 60);
            PdfPTable table = new PdfPTable(floats);
            table.setTotalWidth(600);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            PdfPCell cell = new PdfPCell(pieImage);
            pieImage.scaleAbsolute(300, 188);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
            table.addCell(cell);

            PdfPCell cell2 = new PdfPCell(pieImage1);
            pieImage1.scaleAbsolute(300, 188);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
            table.addCell(cell2);
            doc.add(table);
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Paragraph elements2 = new Paragraph(40, " ", new com.itextpdf.text.Font(font, 14));

            doc.add(elements2);

            ByteArrayOutputStream pieBos2 = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(pieBos2, ChartUtil.barChart("复杂度分布图", null, "复杂度", getDataSet()), 620, 200);
            Image pieImage3 = Image.getInstance(pieBos2.toByteArray());
            pieImage3.setAlignment(Element.ALIGN_CENTER);
            pieBos2.close();

            ByteArrayOutputStream pieBos3 = new ByteArrayOutputStream();
            ChartUtils.writeChartAsJPEG(pieBos3, ChartUtil.barChart("危险度分布图", null, "危险度", getDataSet()), 620, 200);
            Image pieImage4 = Image.getInstance(pieBos3.toByteArray());
            pieImage4.setAlignment(Element.ALIGN_CENTER);
            pieBos3.close();

//            float[] floats1 = new float[2];
//            Arrays.fill(floats1, 60);
//            PdfPTable table1 = new PdfPTable(floats1);
//            table1.setTotalWidth(600);
//            table1.setLockedWidth(true);
//            table1.setHorizontalAlignment(Element.ALIGN_CENTER);
//            table1.getDefaultCell().setBorder(1);
//            PdfPCell cell1 = new PdfPCell(pieImage3);
//            pieImage3.scaleAbsolute(300, 188);
//            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
//            cell1.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
//            table1.addCell(cell1);
//
//            PdfPCell cell3 = new PdfPCell(pieImage4);
//            pieImage4.scaleAbsolute(300, 188);
//            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
//            cell3.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
//            table1.addCell(cell3);
            doc.add(pieImage3);
            doc.add(pieImage4);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            doc.close();
            writer.close();
            outputStream.close();

        }

    }

    public static DefaultCategoryDataset getDataSet() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(50, "场景名称", "[0,10]");
        dataset.addValue(40, "场景名称", "(10,20]");
        dataset.addValue(23, "场景名称", "(20,30]");
        dataset.addValue(24, "场景名称", "(30,40]");
        dataset.addValue(11, "场景名称", "(40,50]");
        dataset.addValue(55, "场景名称", "(50,60]");
        dataset.addValue(55, "场景名称", "(60,70]");
        dataset.addValue(55, "场景名称", "(70,80]");
        dataset.addValue(55, "场景名称", "(80,90]");
        dataset.addValue(55, "场景名称", "(90,100]");
        return dataset;
    }

    public static DefaultPieDataset getPieDataset() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("S ", 2);
        dataset.setValue("A ", 3);
        dataset.setValue("B ", 1);
        dataset.setValue("C ", 5);
        return dataset;
    }

}
